window.onbeforeunload = function() {return '\n=====================================\n\nLeaving or Refreshing this page will cause you to lose\n unsaved changes to your Form.\n\nGo to the \'Save\' Tab to save your changes.\n\n=====================================\n\n';}
formbuilder = function()
{
	myFormTitle = '';
	theForm = [];
	templateName = '';
	
	
	this.checkBrowser = function (string)
	{
		detect = navigator.userAgent.toLowerCase();
		place = detect.indexOf(string) + 1;
		thestring = string;
		return place;
	}
	
	
	
	this.checkDuplicate = function(elementName,editField)
	{
		var noDupe = true;
		if(typeof(editField)!="undefined")
		{
			return true;
		}
		else if(theForm.length>0)
		{
			for(i=0;i<theForm.length;i++)
			{
				if(typeof(theForm[i].attributes)=='object' && typeof(theForm[i].attributes['name'])=='string')
				{
					if(theForm[i].attributes['name']==elementName)
					{
						alert('The field name ' + elementName + ' is already in use.  Please select another field name.');
						noDupe = false;
					}
				}
			}
			return noDupe;
		}
		else
		{
			return true;
		}
	}
	this.createForm = function(formWrapper)
	{
		renderer = new JsonRenderer(formWrapper, theForm, {format: 'html'});
		this.createCode();
		this.updateManager();
	}
	this.updateForm = function(formWrapper,fieldSettings,Pos)
	{
		if(typeof(Pos)=="undefined") var Pos = theForm.length;
		theForm.splice(Pos,0,fieldSettings[0],fieldSettings[1],fieldSettings[2]);
		renderer.render(theForm);
		this.createCode();
		
		thisField = fieldSettings[1].attributes['name'];
		// Update the Manager and Display a message of the action
		this.updateManager();
	}
	this.Message = function(theText)
	{	
		$('actionWrapper').innerHTML = '<p style="color:red;padding:5px;">' + theText + '</p>';
		$('actionWrapper').style.display='block';
		fader = setTimeout("formbuilder.fadeMessage()", 1500);
	}
	this.fadeMessage = function()
	{
		$('actionWrapper').style.display='none';
	}
	this.createCode = function()
	{
		coderender = new JsonRenderer('codeOutput', theForm, {format: 'code'});
        var formCode = BNJQ('#formCode').html();
        formCode = formCode.replace(/\&gt;/ig,">").replace(/\&lt;/ig,"<").replace(/\<div name=\"codeOutput\" id=\"codeOutput\">/,'');
        BNJQ('#formCode').hide();
        BNJQ('#formCopy').val(formCode).show();
	}
	this.updateManager = function()
	{
		fieldTypes = new Array('text','radio','select','checkbox','textarea');
		for(z=0;z<fieldTypes.length;z++)
		{
			$(fieldTypes[z]+'fieldOptions').style.display='none';
			
			switch(fieldTypes[z])
			{
				case "radio" : case "select" : case "checkbox" :
					this.resetOptions(fieldTypes[z]);
				break;
			}
		}
		$('addElement').reset();
		this.populatePositions();
		this.populateElements();
		$('formPreview').innerHTML = 'Previewing \'' + templateName + '\'';
		$('formTitle').innerHTML = templateName;
		$('pFormTitle').innerHTML = templateName;
		var url 	= 'builderajax_getforms.php';
		var target	= 'savedDBForms';
		var myAjax	= new Ajax.Updater(target, url, {asynchronous:true});
		$('labelTitle').readOnly = '';
		$('elementName').readOnly = '';
	}
	
	this.deleteElement = function(fieldID)
	{
		if(theForm.length>0)
		{
			// Get the id of the fields to be removed.
			fieldID = parseInt(fieldID*3);
			// Get the id of the field that contains a name then get the fieldName
			fieldNameID=(fieldID+1);
			//alert(fieldNameID);
			fieldName = theForm[fieldNameID].attributes['name'];
			
	  		// Remove the element
			theForm.splice(fieldID,3);
			renderer.render(theForm);
			
			// Update message and manager
			this.Message('Removed field successfully');
			this.updateManager();
			this.createCode();
			if(this.checkBrowser('safari')) 
			{
				Tab('previewWrapper');
			}
			else
			{
				document.location.href='#3';
			}
		}
		else
		{
			alert('No form question to delete.');
		}
		return false;
		
	}
	this.editElement = function(fieldID)
	{
		if(theForm.length>0)
		{
			// Get the id of the fields to be removed.
			fieldID = parseInt(fieldID*3);
			$('myElements').style.display='none';
			$('addQuestion').style.display='block';
			// Get the id of the field that contains a name then get the fieldName
			fieldNameID=(fieldID+1);
			fieldName = theForm[fieldNameID].attributes['name'];
			this.Message('Loading field to edit..');
			
			$('addElement').reset();
			$('buildHeader').innerHTML 	= 'Edit Question';
			$('buildButton').value		= 'Save Changes';
			var editElements = theForm.slice(fieldID,(fieldID+3));
			//alert(editElements[1].children.length);
			
			$('labelTitle').value = editElements[0].children;
			$('elementName').value = editElements[1].attributes['name'];
			
			if(editElements[0].attributes['style'].indexOf('float')==-1)
			{
				$('labelPOSAbove').checked = true;
			}
			else
			{
				$('labelPOSLeft').checked = true;
			}
			if (editElements[1].attributes['type'] && editElements[1].attributes['type']!="hidden") {
				fieldType = editElements[1].attributes['type'];
			}
			else if(editElements[1].attributes['type']=="hidden")
			{
				fieldType = editElements[1].attributes['name'];
			}
			else if(editElements[1].tag=="textarea" || editElements[1].tag=="select")
			{
				fieldType = editElements[1].tag;
			}
			else
			{
				fieldType = editElements[1].children[0].attributes['type'];
			}
			this.resetOptions(fieldType);
			formbuilder.fieldOptions(fieldType);
			$('fieldType').value = fieldType;
			$('addElement').onsubmit=function() { return formbuilder.insertElement('formbuilder','buildWrapper',fieldID); }
			switch(fieldType)
			{
				case "text":
					$('fieldValue').value = editElements[1].attributes['value'];
					fieldSize = editElements[1].attributes['style'].replace('width:','');
					fieldSize = fieldSize.replace('px;','');
					$('fieldSize').value = fieldSize;
					$('fieldMaxLength').value = editElements[1].attributes['maxlength'];
				break;
				
				case "subject":
					$('subjectValue').value = editElements[1].attributes['value'];
				break;
				
				case "thankyou":
					$('thanksURL').value = editElements[1].attributes['value'];
				break;
				
				case "radio" : case "checkbox" :
					numRadios = editElements[1].children.length;
					formbuilder.delOption(fieldType,1);
					for(m=0;m<numRadios;m++)
					{
						vval = editElements[1].children[m].attributes['value'];
						tval = editElements[1].children[m].children[0].children;
						formbuilder.addOption(fieldType,tval,vval);
						if (editElements[1].children[m].attributes['checked']=="checked")
						{
							radioChecked = (m+1);
							$(fieldType + 'OptionSelected' + radioChecked).checked = true;
						}
						i++;
					}
				break;
				
				case "carboncopy" :
					Emails = editElements[1].attributes['value'];
					Emails = Emails.split(',');
					formbuilder.delOption(fieldType,1);
					for(m=0;m<Emails.length;m++)
					{
						tval = Emails[m];
						formbuilder.addOption(fieldType,tval);
						
					}
				break;
				
				case "textarea" :
					$('textboxValue').value = editElements[1].children;
					Dimensions = editElements[1].attributes['style'];
					
					Dimensions = Dimensions.replace(/(width\:)([0-9]+)(px\;)(height\:)([0-9]+)(px\;)/gi,"$2" + ':' + "$5");
					Dimensions = Dimensions.split(":");
					$('fieldWidth').value = Dimensions[0];
					$('fieldHeight').value = Dimensions[1];
				break;
				
				case "select" :
					numOpts = editElements[1].children.length;
					formbuilder.delOption(fieldType,1);
					for(m=0;m<numOpts;m++)
					{
						svval = editElements[1].children[m].attributes['value'];
						stval = editElements[1].children[m].children;
						formbuilder.addOption(fieldType,stval,svval);
						if (editElements[1].children[m].attributes['selected']=="selected")
						{
							radioChecked = (m+1);
							$(fieldType + 'OptionSelected' + radioChecked).checked = true;
						}
						i++;
					}
					if(editElements[1].attributes['multiple']=="multiple")
					{
						$('multiSelect').value = "1";
					}
				break;
			}
			this.populateEditPos(fieldName);
		}
		else
		{
			alert('No form question to edit');
		}
	}
	
	this.insertElement = function(formWrapper,tabLocation,editField)
	{
		var insertEl = true;
		if(!Pos) var Pos = 0;
		var fieldSettings = new Object();
		
		fieldType		= $('fieldType').value;
		elementName		= $('elementName').value;
		labelTitle		= $('labelTitle').value;
		labelPOS		= ($('labelPOSLeft').checked==true) ? 'left':'above';
		fieldPosition	= $('element-pos').value;
		
		fieldPosition	= (fieldPosition==0) ? 0:(fieldPosition * 3);
		labelPOS		= (labelPOS=="above") ? 'display:block;margin-bottom:5px;':'float:left;width:140px;';
		
		customTypes = {
						'userfile':'file',
						'carboncopy':'carboncopy',
						'thankyou':'thankyou',
						'subject':'subject',
						'MAX_FILE_SIZE':'hidden'
						};
		
		$H(customTypes).each(
			function(ctype)
			{
				if(elementName==ctype.key && fieldType!=ctype.value && typeof(editField)=="undefined")
				{
								alert('The field name ' + ctype.key + ' is reserved for special use listed under custom field types.  Please select another field name.');
								insertEl = false;
				}
			}
		);
		if(typeof(editField)=="undefined")
		{
			if(theForm.length>0)
			{
				for(i=0;i<theForm.length;i++)
				{
					if(typeof(theForm[i].attributes)=='object' && typeof(theForm[i].attributes['name'])=='string')
					{
						if (elementName=='userfile' && theForm[i].attributes['name']=='fileUpload')
						{
							alert('You may only use one custom field type within each form.');
							insertEl = false;
							break;
						}
					}
				}
			}
		}
		
		if(!labelTitle || !elementName || !fieldType)
		{
			window.alert('You must enter a title for your label, a name for your field or a question type');
			return false;
		}
		if(!elementName.match(/^[\w-]+$/))
		{
			window.alert('Your element name may only contain letters, numbers, dashes or underscores.');
			return false;
		}
		if(!labelTitle.match(/^[\w\s?$@:%*\/+!.\-,\'()]+$/))
		{
			window.alert('Your question may only contain letters, spaces, numbers, dashes or underscores.  You may also use the following characters: ?:$@%*+!.,\'()');
			return false;
		}
		if(this.checkDuplicate(elementName,editField))
		{
			switch(fieldType)
			{
				case "text" :
					fieldValue 		= $('fieldValue').value;
					if(fieldValue!='')
					{
						if(!fieldValue.match(/^[\w\s?$@:%*\/+!.\-,\'()]+$/))
						{
							window.alert('Your field value may only contain letters, spaces, numbers, dashes or underscores.  You may also use the following characters: ?:$@%*+!.,\'()');
							insertEl = false;
							break;
						}
					}
					fieldSize		= $('fieldSize').value;
					if(fieldSize=='') fieldSize=200;
					fieldMaxLength	= $('fieldMaxLength').value;
					// the object for insertion
					fieldSettings = 
					[
						{tag: 'label', attributes: {'for': elementName, style: labelPOS}, children: [labelTitle]},
						{tag: 'input', attributes: {type: fieldType, name: elementName, id: elementName, value: fieldValue, maxlength: fieldMaxLength, style: 'width:' + fieldSize + 'px;'}},
						{tag: 'div', attributes: {style: 'clear:left;height:20px;'}, children: ['&nbsp;']},
					];
				break;
				
				case "file" :
					if(!pU)
					{
						if(window.confirm('You must have the Professional Version of Email Forms service in order to use file attachments within your forms.  Would you like to upgrade now?'))
						{
							window.onbeforeunload=null;
							window.location.href='pro_upgrade.php';
						}
						insertEl = false;
						break;
					}
					else
					{
						fieldSettings = 
						[
							{tag: 'label', attributes: {'for': elementName, style: labelPOS}, children: [labelTitle]},
							{tag: 'span', attributes: {style: 'display:block;', name: 'fileUpload'}, children: []},
							{tag: 'div', attributes: {style: 'clear:left;height:20px;'}, children: ['&nbsp;']}
						];
						// The File Upload Field
						newJsonTag = {tag: 'input', attributes: {type: fieldType, name: elementName, id: elementName}};
						fieldSettings[1].children.push(newJsonTag);
						// The hidden input for max filesize
						newJsonTag = {tag: 'input', attributes: {type: 'hidden', name: 'MAX_FILE_SIZE', value: '2000000'}};
						fieldSettings[1].children.push(newJsonTag);
					}
					$('elementName').readOnly='';
				break;
				
				case "thankyou" :
					thanksURL 		= $('thanksURL').value;
					if(thanksURL!='http://'  && thanksURL!='')
					{
						if(!thanksURL.match(/^(http(s)?:\/\/)?[a-z0-9_.:-]+\.[a-z0-9_.:-]+\/?[ a-z0-9%;\/?:@&=+#$,_.!~*\'(){}-]*$/))
						{
							window.alert('You must enter a valid URL. Please Try Again');
							insertEl = false;
							return false;
							break;
						}
					}
					else
					{
						window.alert('You must enter a thank you URL. Please try again.');
						insertEl = false;
						return false;
						break;
					}
					fieldSettings = 
					[
						{tag: 'label', attributes: {'for': elementName, style: 'display:none;'}, children: [labelTitle]},
						{tag: 'input', attributes: {type: 'hidden', name: 'thankyou', id: 'thankyou', value: thanksURL}},
						{tag: 'div', attributes: {style: 'clear:left;height:20px;display:none;'}, children: ['&nbsp;']}
					];
				break;
				
				case "subject" :
					subjectValue 		= $('subjectValue').value;
					if(subjectValue!='')
					{
						if(!subjectValue.match(/^[\w\s?$@:%*\/+!.\-,\'()]+$/))
						{
							window.alert('Your subject value may only contain letters, spaces, numbers, dashes or underscores.  You may also use the following characters: ?:$@%*+!.,\'()');
							insertEl = false;
							return false;
							break;
						}
					}
					else
					{
						window.alert('You must enter a Email Subject. Please try again.');
						insertEl = false;
						return false;
						break;
					}
					fieldSettings = 
					[
						{tag: 'label', attributes: {'for': elementName, style: 'display:none;'}, children: [labelTitle]},
						{tag: 'input', attributes: {type: 'hidden', name: 'subject', id: 'subject', value: subjectValue}},
						{tag: 'div', attributes: {style: 'clear:left;height:20px;display:none;'}, children: ['&nbsp;']}
					];
				break;

				case "carboncopy" :
					fieldSettings = 
					[
						{tag: 'label', attributes: {'for': elementName, style: 'display:none;'}, children: [labelTitle]},
						{tag: 'input', attributes: {type: 'hidden', name: 'carboncopy', id: 'carboncopy', value: ''}},
						{tag: 'div', attributes: {style: 'clear:left;height:20px;display:none;'}, children: ['&nbsp;']}
					];
					Opts = this.getOptions(fieldType);
					for(k=0;k<Opts.length;k++)
					{
						thisOption = Opts[k].split(':|:');
						if(thisOption[0]=='')
						{
							alert('All email addresses must be entered.  Please fix this error and try again');
							insertEl = false;
							break;
							
						}
						else if(!thisOption[0].match(/^[\w\s?$:@\/%*+!.\-,\'()]+$/))
						{
							window.alert('All email addresses may only contain letters, spaces, numbers, dashes or underscores.  You may also use the following characters: ?:$@%*+!.,\'()');
							insertEl = false;
							return false;
							break;
						}
						else if(!thisOption[0].match(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/))
						{
							window.alert('All email addresses entered must be valid.  Please double-check all your email addresses and try again.');
							insertEl = false;
							return false;
							break;
						}
						else
						{
							eleName	= elementName + (k + 1);
							//newJsonTag = {tag: 'input', attributes: {type: 'hidden', name: 'carboncopy', id: 'carboncopy', value: '', style: 'vertical-align: middle;border:0px;background-color:transparent'}, children:[{tag: 'label', attributes: {'for': elementName + (k + 1) + fieldType + 'Option'}, children: [thisOption[0]]}]};
							//if(thisOption[2]==1) newJsonTag.attributes['checked']="checked";
							newEmail = ((k+1)==Opts.length) ? thisOption[0]:newEmail = thisOption[0] + ',';
							fieldSettings[1].attributes['value']+=newEmail;
						}
					}

				break;
				
				case "textarea" :
					textboxValue 	= $('textboxValue').value;
					if(textboxValue!='')
					{
						if(!textboxValue.match(/^[\w\s?$@:%*\/+!.\-,\'()]+$/))
						{
							window.alert('Your textbox value may only contain letters, spaces, numbers, dashes or underscores.  You may also use the following characters: ?:$@%*+!.,\'()');
							insertEl = false;
							return false;
							break;
						}
					}
					fieldWidth		= $('fieldWidth').value;
					if(fieldWidth=='') fieldWidth=200;
					fieldHeight		= $('fieldHeight').value;
					if(fieldHeight=='') fieldHeight=160;
					// the object for insertion
					fieldSettings = 
					[
						{tag: 'label', attributes: {'for': elementName, style: labelPOS}, children: [labelTitle]},
						{tag: 'textarea', attributes: {name: elementName, id: elementName, style: 'width:' + fieldWidth + 'px;height:' + fieldHeight + 'px;'}, children: [textboxValue]},
						{tag: 'div', attributes: {style: 'clear:left;height:20px;'}, children: ['&nbsp;']},
					];
				break;
				
				case "radio" : case "checkbox" :
					// Get the options
					Opts = this.getOptions(fieldType);
					optionsWidth=400;
					// The object for insertion
					fieldSettings =
					[
						{tag: 'label', attributes: {style: labelPOS}, children: [labelTitle]},
						{tag: 'span', attributes: {name: elementName, style: 'display:block;width: ' + optionsWidth + 'px;'}, children: []},
						{tag: 'div', attributes: {style: 'clear:left;height:20px;'}, children: ['&nbsp;']},
					];
					
					for(k=0;k<Opts.length;k++)
					{
						thisOption = Opts[k].split(':|:');
						if(thisOption[0]=='' || thisOption[1]=='')
						{
							alert('All option titles and values must be entered.  Please fix this error and try again');
							insertEl = false;
							break;
							
						}
						else if(!thisOption[0].match(/^[\w\s?$:@\/%*+!.\-,\'()]+$/) || !thisOption[1].match(/^[\w\s?$:@\/%*+!.\-,\'()]+$/))
						{
							window.alert('Your option titles and values may only contain letters, spaces, numbers, dashes or underscores.  You may also use the following characters: ?:$@%*+!.,\'()');
							insertEl = false;
							return false;
							break;
						}
						else
						{
							eleName	= (fieldType=="checkbox") ? elementName + (k + 1):elementName;
							newJsonTag = {tag: 'input', attributes: {type: fieldType, name: eleName, id: elementName + (k + 1) + fieldType + 'Option', value: thisOption[1], style: 'vertical-align: middle;border:0px;background-color:transparent'}, children:[{tag: 'label', attributes: {'for': elementName + (k + 1) + fieldType + 'Option'}, children: [thisOption[0]]}]};
							if(thisOption[2]==1) newJsonTag.attributes['checked']="checked";
							fieldSettings[1].children.push(newJsonTag);
						}
					}
				break;
				
				case "select" :
					// Get the options
					Opts = this.getOptions(fieldType);
	        
	        // Determine if we will be making a multiple select box
	        multiSelect	= $('multiSelect').value;
		
		        if(multiSelect==1) { elementName = elementName + '[]';}
    			// The object for insertion
					fieldSettings =
					[
						{tag: 'label', attributes: {style: labelPOS, 'for': elementName}, children: [labelTitle]},
						{tag: 'select', attributes: {name: elementName, id: elementName}, children: []},
						{tag: 'div', attributes: {style: 'clear:left;height:20px;'}, children: ['&nbsp;']},
					];
		      if(multiSelect==1)
		      {
            fieldSettings[1].attributes['multiple']='multiple';		
				  }
					for(k=0;k<Opts.length;k++)
					{
						thisOption = Opts[k].split(':|:');
						if(thisOption[0]=='' || thisOption[1]=='')
						{
							alert('All option titles and values must be entered.  Please fix this error and try again');
							insertEl = false;
							break;
							
						}
						else if(!thisOption[0].match(/^[\w\s?$:@\/%*+!.\-,\'()]+$/) || !thisOption[1].match(/^[\w\s?$:@\/%*+!.\-,\'()]+$/))
						{
							window.alert('Your option titles and values may only contain letters, spaces, numbers, dashes or underscores.  You may also use the following characters: ?:$@%*+!.,\'()');
							insertEl = false;
							return false;
							break;
						}
						else
						{
							newJsonTag = {tag: 'option', attributes: {value: thisOption[1]}, children:[thisOption[0]]};
							if(thisOption[2]==1) newJsonTag.attributes['selected']="selected";
							fieldSettings[1].children.push(newJsonTag);
						}
					}
				break;
				
			}
			if(insertEl)
			{
				if(typeof(editField)!='undefined')
				{
					theForm.splice(editField,3);
					renderer.render(theForm);
					$('buildHeader').innerHTML 	= 'Add Question';
					$('buildButton').value		= 'Add Field';
					$('addElement').onsubmit=function() { return formbuilder.insertElement('formbuilder','buildWrapper'); }
				}
				if(typeof(editField)!='undefined')
				{
					this.Message('Updated field successfully');
				} else {
					this.Message('Added  field successfully');
				}
				this.updateForm('formwrapper',fieldSettings,fieldPosition);
				this.fieldOptions();
				if(this.checkBrowser('safari'))
				{
					Tab('previewWrapper');
				}
				else
				{
					document.location.href='#3';
				}
			}
		}
		return false;
	}
	this.getOptions = function(fieldType)
	{
		theOptions = $(fieldType+'Options').getElementsByTagName('span');
		var Opts = new Array();
		for(i=1;i<=theOptions.length;i++)
		{
			if ($(fieldType+'Option'+i)) 
			{
				if($(fieldType+'OptionTitle'+i))
				{
					selected = ($(fieldType+'OptionSelected'+i).checked==true) ? '1':'0';
					Opts[i-1] = $(fieldType+'OptionTitle'+i).value + ':|:' + $(fieldType+'OptionValue'+i).value + ':|:' + selected;
				}
				else if($(fieldType+'OptionEmail'+i))
				{
					Opts[i-1] = $(fieldType+'OptionEmail'+i).value + ':|:' + ':|:';
				}
			}
		}
		return Opts;
	}
	// This last bit is to populate the element position options select box
	this.populatePositions = function()
	{
		
		fieldSettings =	[{tag: 'select', attributes: {name: 'element-pos', id: 'element-pos', style: 'width: 220px;'}, children: []}];
		if(theForm.length>0)
		{
			p=0;
			for(n=0;n<theForm.length;n++)
			{
				if(typeof(theForm[n].attributes)=='object' && typeof(theForm[n].attributes['name'])=='string')
				{
					newJsonTag = {tag: 'option', attributes: {value: (p)}, children:['Before ' + theForm[n].attributes['name']]};
					fieldSettings[0].children.push(newJsonTag);
					p++;
				}
			}
			newJsonTag = {tag: 'option', attributes: {value: (fieldSettings[0].children.length), 'selected': 'selected'}, children:['At the end']};
			fieldSettings[0].children.push(newJsonTag);
		}
		else
		{
			newJsonTag = {tag: 'option', attributes: {value: (fieldSettings[0].children.length)}, children:['At the beginning']};
			fieldSettings[0].children.push(newJsonTag);
		}
		elemRender = new JsonRenderer('elemPos',fieldSettings,{format: 'html'});
		//new Effect.Highlight('element-pos', {startcolor:'#FFFAEB', endcolor:'#ffffff'});*/
	}
	this.populateEditPos=function(editField)
	{
		
		fieldSettings =	[{tag: 'select', attributes: {name: 'element-pos', id: 'element-pos', style: 'width: 220px;'}, children: []}];
		
		k=0;
		
		for(i=0;i<theForm.length;i++) 
		{ 
			if(typeof(theForm[i].attributes)=='object' && typeof(theForm[i].attributes['name'])=='string')
			{
				if(typeof(editField)=="string" && theForm[i].attributes['name']==editField)
				{
					currentPosition = k;
				}
				k++;
			}
		}
		beforeAfter = (((currentPosition+1)*3)==theForm.length) ? 'Before':'After';
		p = 0;
		for(n=0;n<theForm.length;n++)
		{
			if(typeof(theForm[n].attributes)=='object' && typeof(theForm[n].attributes['name'])=='string')
			{
				if(typeof(currentPosition)!="undefined")
				{
					if(currentPosition==p)
					{
						
						newJsonTag = {tag: 'option', attributes: {value: (p), 'selected': 'selected'}, children:['Current Position']};
						fieldSettings[0].children.push(newJsonTag);
					}
					else if (theForm[n].attributes['name']!=editField)
					{
						newJsonTag = {tag: 'option', attributes: {value: (p)}, children:[beforeAfter + ' ' + theForm[n].attributes['name']]};
						fieldSettings[0].children.push(newJsonTag);
					}
					p++;
				}
				
			}
		}
		
		new JsonRenderer('elemPos',fieldSettings,{format: 'html'});
		//new Effect.Highlight('element-pos', {startcolor:'#FFFAEB', endcolor:'#ffffff'});
	}
	this.populateElements = function()
	{
		headerSettings = [{tag: 'div', attributes: {'class': 'ulsub', style: 'margin-top:0px;margin-bottom: 10px;'}, children: ['Questions for \'' + templateName + '\'']}];
		fieldSettings = [{tag: 'table', attributes: {'border': '0', 'cellpadding': '5', 'cellspacing': '0', 'width': '100%', style: 'margin-bottom:15px;'}, children: []}];
		j=0;
		if(theForm.length>0)
		{
		  	for(i=0;i<theForm.length;i++)
			{
				if(typeof(theForm[i].attributes)=='object' && typeof(theForm[i].attributes['name'])=='string')
				{
					backgroundColor = (j%2==0) ? '#F7F7F7':'#fff';
				 	newRow = {tag: 'tr', attributes: {style: 'background-color: ' + backgroundColor}, children:[]};
				 	//newJsonTag = {tag: 'option', attributes: {value: (j)}, children: ['' + theForm[i].attributes['name']]};
				 	fieldSettings[0].children.push(newRow);
				 	newData = {tag: 'td', attributes: {style: 'width:30px;'}, children:['<img src="http://assets.bravenet.com/common/images/webtools/serviceicons/membershelping.gif" style="border:0px;">']};
				 	fieldSettings[0].children[j].children.push(newData);
				 	newData = {tag: 'td', attributes: {style: 'width:240px;font-weight:bold'}, children:[theForm[i].attributes['name']]};
				 	fieldSettings[0].children[j].children.push(newData);
				 	qType = (typeof(theForm[i].attributes['type'])!='undefined') ? theForm[i].attributes['type']:theForm[i].tag;
				 	qType = (qType=="textarea") ? 'textbox':qType;
				 	if(qType=="span")
				 	{
				 		if(typeof(theForm[i].children[0])!='undefined') qType = theForm[i].children[0].attributes['type'];
				 	}
				 	newData = {tag: 'td', attributes: {style: 'width:200px;text-align:center;'}, children:[qType]};
				 	fieldSettings[0].children[j].children.push(newData);
				 	newData = {tag: 'td', attributes: {style: 'width:80px;'}, children:['<a href="#2" onclick="formbuilder.editElement(\'' + j + '\');">Edit</a>']};
				 	fieldSettings[0].children[j].children.push(newData);
				 	newData = {tag: 'td', attributes: {style: 'text-align:right;'}, children:['<a href="#2" onclick="if(window.confirm(\'Are you sure you want to delete this question?\')) {formbuilder.deleteElement(\'' + j + '\');}else{return false;}">Delete</a>']};
				 	fieldSettings[0].children[j].children.push(newData);
					j++;
				}
			}
			myEleHRender = new JsonRenderer('myElementsHeader',headerSettings,{format: 'html'});
			myEleRender = new JsonRenderer('myElementsTable',fieldSettings,{format: 'html'});
			$('addQuestion').style.display='none';
			$('myElements').style.display='block';
		}
		else
		{
			$('addQuestion').style.display='block';
			$('myElements').style.display='none';
			$('eleShow').style.display='none';
		}
		

		
	}
	//Changes which field options to show when they select a field type for a new field
	this.fieldOptions = function(fieldType)
	{
		divs = $('fieldOptions').getElementsByTagName('div');
		for(i=0;i<divs.length;i++)
		{
			divs[i].style.display = 'none';
		}
		if(fieldType) 
		{
			$(fieldType+'fieldOptions').style.display = 'block';
			$('buildButton').style.display = 'block';
		}
		else
		{
			$('guideImage').style.display = 'block';
			$('buildButton').style.display = 'none';
		}
		if(fieldType=="file")
		{
			$('elementName').value = 'userfile';
			$('elementName').readOnly = 'read-only';
		}
		else if (fieldType!='file' && $('elementName').value=='userfile')
		{
			$('elementName').readOnly = '';
			$('elementName').value = '';
		}
		if(fieldType=="carboncopy")
		{
			$('elementName').value = 'carboncopy';
			$('labelTitle').value = 'hidden field';
			$('labelTitle').readOnly = 'read-only';
			$('elementName').readOnly = 'read-only';
		}
		else if (fieldType!='carboncopy' && $('elementName').value=='carboncopy')
		{
			$('elementName').readOnly = '';
			$('elementName').value = '';
			$('labelTitle').value = '';
			$('labelTitle').readOnly = '';
		}
		if(fieldType=="thankyou")
		{
			$('elementName').value = 'thankyou';
			$('labelTitle').value = 'hidden field';
			$('labelTitle').readOnly = 'read-only';
			$('elementName').readOnly = 'read-only';
		}
		else if (fieldType!='thankyou' && $('elementName').value=='thankyou')
		{
			$('elementName').readOnly = '';
			$('elementName').value = '';
			$('labelTitle').value = '';
			$('labelTitle').readOnly = '';
		}
		if(fieldType=="subject")
		{
			$('elementName').value = 'subject';
			$('labelTitle').value = 'hidden field';
			$('labelTitle').readOnly = 'read-only';
			$('elementName').readOnly = 'read-only';
		}
		else if (fieldType!='subject' && $('elementName').value=='subject')
		{
			$('elementName').readOnly = '';
			$('elementName').value = '';
			$('labelTitle').value = '';
			$('labelTitle').readOnly = '';
		}
	}
	//Add Options for Radio, Select, and checkboxes
	this.addOption = function(fieldType,TValue,VValue)
	{
		var TitleValue = '';
		var ValueValue = '';
		options = $(fieldType+'Options').getElementsByTagName('span');
		newID = (options.length+1);
	
	if(typeof(TValue)!="undefined" && typeof(VValue)!="undefined")
	{
		var TitleValue = ' value="' + TValue + '"';
		var ValueValue = ' value="' + VValue + '"';
	}
	if(typeof(TValue)!="undefined" && typeof(VValue)=="undefined")
	{
		var CustomValue = 'value="' + TValue + '"';
	}
	switch(fieldType)
    {
		case "radio" : 
        	newOption = '<span id="' + fieldType + 'Option' + newID + '"><label for="' + fieldType + 'OptionTitle' + newID + '">Radio Title :</label> <input type="text" style="width:120px;" name="' + fieldType + 'OptionTitle' + newID + '" id="' + fieldType + 'OptionTitle' + newID + '" onblur="formbuilder.checkOptDupe(\'' + fieldType + '\',\'Title\');"' + TitleValue + '> <label for="' + fieldType + 'OptionValue' + newID + '">Value :</label> <input type="text" name="' + fieldType + 'OptionValue' + newID + '" id="' + fieldType + 'OptionValue' + newID + '" onblur="return formbuilder.checkOptDupe(\'' + fieldType + '\',\'Value\');"' + ValueValue + ' style="width:70px;"> <label for="' + fieldType + 'OptionSelected' + newID + '">Selected?</label> <input type="radio" name="' + fieldType + 'OptionSelected" id="' + fieldType + 'OptionSelected' + newID + '" value="' + newID + '" style="background-color:transparent;border:0;"> &nbsp;&nbsp;[ <a href="#2" onclick="formbuilder.addOption(\'' + fieldType + '\');" id="'+ fieldType + 'Add' + newID + '">Add</a> ] [ <a href="#2" onclick="formbuilder.delOption(\'' + fieldType + '\',\'' + newID + '\');" id="'+ fieldType + 'Remove' + newID + '">Remove</a> ]<br></span>'+"\n";
      	break;
      	case "select" :
      		newOption = '<span id="' + fieldType + 'Option' + newID + '"><label for="' + fieldType + 'OptionTitle' + newID + '">Option Title :</label> <input type="text" style="width:110px;" name="' + fieldType + 'OptionTitle' + newID + '" id="' + fieldType + 'OptionTitle' + newID + '" onblur="formbuilder.checkOptDupe(\'' + fieldType + '\',\'Title\');"' + TitleValue + '> <label for="' + fieldType + 'OptionValue' + newID + '">Value :</label> <input type="text" name="' + fieldType + 'OptionValue' + newID + '" id="' + fieldType + 'OptionValue' + newID + '" onblur="return formbuilder.checkOptDupe(\'' + fieldType + '\',\'Value\');"' + ValueValue + ' style="width:70px;"> <label for="' + fieldType + 'OptionSelected' + newID + '">Selected?</label> <input type="radio" name="' + fieldType + 'OptionSelected" id="' + fieldType + 'OptionSelected' + newID + '" value="' + newID + '" style="background-color:transparent;border:0;"> &nbsp;&nbsp;[ <a href="#2" onclick="formbuilder.addOption(\'' + fieldType + '\');" id="'+ fieldType + 'Add' + newID + '">Add</a> ] [ <a href="#2" onclick="formbuilder.delOption(\'' + fieldType + '\',\'' + newID + '\');" id="'+ fieldType + 'Remove' + newID + '">Remove</a> ]<br></span>'+"\n";
      	break;
      	case "checkbox" :  
        	newOption = '<span id="' + fieldType + 'Option' + newID + '"><label for="' + fieldType + 'OptionTitle' + newID + '">Checkbox Title :</label> <input type="text" style="width:100px;" name="' + fieldType + 'OptionTitle' + newID + '" id="' + fieldType + 'OptionTitle' + newID + '" onblur="formbuilder.checkOptDupe(\'' + fieldType + '\',\'Title\');"' + TitleValue + '> <label for="' + fieldType + 'OptionValue' + newID + '">Value :</label> <input type="text" name="' + fieldType + 'OptionValue' + newID + '" id="' + fieldType + 'OptionValue' + newID + '" onblur="return formbuilder.checkOptDupe(\'' + fieldType + '\',\'Value\');"' + TitleValue + ' style="width:70px"> <label for="' + fieldType + 'OptionSelected' + newID + '">Selected?</label> <input type="checkbox" name="' + fieldType + 'OptionSelected' + newID + '" id="' + fieldType + 'OptionSelected' + newID + '" value="' + newID + '" style="background-color:transparent;border:0;"> &nbsp;&nbsp;[ <a href="#2" onclick="formbuilder.addOption(\'' + fieldType + '\');" id="'+ fieldType + 'Add' + newID + '">Add</a> ] [ <a href="#2" onclick="formbuilder.delOption(\'' + fieldType + '\',\'' + newID + '\');" id="'+ fieldType + 'Remove' + newID + '">Remove</a> ]<br></span>'+"\n";
     	break;
     	case "carboncopy" :
     		newOption = '<span id="' + fieldType + 'Option' + newID + '"><label for="' + fieldType + 'OptionEmail' + newID + '">Email Address:</label> <input type="text" style="width:305px;" name="' + fieldType + 'OptionEmail' + newID + '" id="' + fieldType + 'OptionEmail' + newID + '"' + CustomValue + '> &nbsp;&nbsp;[ <a href="#2" onclick="formbuilder.addOption(\'' + fieldType + '\');" id="'+ fieldType + 'Add' + newID + '">Add</a> ] [ <a href="#2" onclick="formbuilder.delOption(\'' + fieldType + '\',\'' + newID + '\');" id="'+ fieldType + 'Remove' + newID + '">Remove</a> ]<br></span>'+"\n";
     	break;
	}
	new Insertion.Bottom($(fieldType+'Options'), newOption);
		
	}
	// Delete an Option from Options List for new Radio, Select or Checkbox.
	this.delOption = function(fieldType,OID)
	{
		options = $(fieldType+'Options').getElementsByTagName('span');
		numOptions = options.length;
		
		if(OID!=numOptions)
		{
			var tvalues = new Array();
			var vvalues = new Array();
			for(i=OID;i<=numOptions;i++)
			{
				if(i!=OID && $(fieldType+'OptionTitle'+i) && $(fieldType+'OptionValue'+i))
				{
					tvalues[(i-1)] = $(fieldType+'OptionTitle'+i).value;
					vvalues[(i-1)] = $(fieldType+'OptionValue'+i).value;
				}
				else if(i!=OID && $(fieldType+'OptionEmail'+i))
				{
					tvalues[(i-1)] = $(fieldType+'OptionEmail'+i).value;
				}
				Element.remove($(fieldType+'Option'+i));
				//Element.remove($(fieldType+'Option'+i))
				
			}
			addLoop = numOptions-OID;
			z=OID;
			for(k=0;k<addLoop;k++)
			{
				formbuilder.addOption(fieldType,tvalues[z],vvalues[z]);
				z++;
			}
		}
		else
		{
			Element.remove($(fieldType+'Option'+OID));
		}
		
	}
	this.resetOptions = function(fieldType)
	{
		if(typeof('options')!='undefined' && $(fieldType+'Options')) 
		{
			options = $(fieldType+'Options').getElementsByTagName('span');
			numOptions = options.length;
			
			if(numOptions>1)
			{
				for(i=options.length;i>=options.length;i--)
				{
					if(i>1)	Element.remove($(fieldType+'Option'+i));
				}
			}
		}
	}
	this.checkOptDupe = function(fieldType,optionPart)
	{
	  var optionParts= new Array('Title','Value');
	  var dupeFound=0;
		if(typeof('options')!='undefined' && $(fieldType+'Option'+optionPart+'2')) 
		{
				options = $(fieldType+'Options').getElementsByTagName('span');
				thisID = options.length;
				
				thisValue = $(fieldType + 'Option' + optionPart + (thisID)).value;
				
				if(thisValue!='')
				{
					for(i=1;i<thisID;i++)
					{
						if(typeof($(fieldType + 'Option' + optionPart + i))=="object")
						{
							prevValue = $(fieldType + 'Option' + optionPart + (i)).value;
							if(thisValue==prevValue)
							{
							   dupeFound=thisID;
							}
						}
						if(dupeFound)
						{
              					alert('Duplicate ' + optionPart + ' detected in your options list. Please enter a different Option ' + optionPart);
								$(fieldType + 'Option' + optionPart + thisID).style.border='2px outset #f00';
								$(fieldType + 'Option' + optionPart + thisID).focus();
								if(optionPart==optionParts[0])
								{
								  $(fieldType + 'Option' + optionParts[1] + thisID).readOnly='read-only';
                  				  $(fieldType + 'Option' + optionParts[1] + thisID).style.border='2px inset #ccc';
								  $(fieldType + 'Option' + optionParts[1] + thisID).blur();
								}
								new Effect.Highlight(fieldType + 'Option' + optionPart + thisID);
								break;
            }
            else
            {
              $(fieldType + 'Option' + optionPart + thisID).style.border='2px inset #404040';
			  $(fieldType + 'Option' + optionParts[1] + thisID).readOnly='';
              $(fieldType + 'Option' + optionParts[1] + thisID).style.border='2px inset #404040';
            }
					}
				}
		}
	}
	
	this.loadTemplate = function(tID)
	{
		/* Templates */
		/* Custom templates that the user can select from before they start building */
		var templates = new Array();
		var template_names = new Array('Contact Form','Contest Entry Form','Feedback Form','Order Form','Review Form','Survey Form','Blank Form');
		/* Personal Contact Form */
		templates[0] = [{"tag":"label","attributes":{"for":"FirstLastName","style":"float:left;width:140px;"},"children":["First and Last Name:"]},{"tag":"input","attributes":{"type":"text","name":"FirstLastName","id":"FirstLastName","value":"","maxlength":"","style":"width:200px;"}},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"for":"replyemail","style":"float:left;width:140px;"},"children":["E-Mail Address:"]},{"tag":"input","attributes":{"type":"text","name":"replyemail","id":"replyemail","value":"","maxlength":"","style":"width:200px;"}},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"for":"Message","style":"float:left;width:140px;"},"children":["Message:"]},{"tag":"textarea","attributes":{"name":"Message","id":"Message","maxlength":"","style":"width:200px;height:200px;"},"children":[""]},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]}];
		/* Contest Entry Form */
		templates[1] = [{"tag":"label","attributes":{"for":"FirstLastName","style":"float:left;width:140px;"},"children":["First and Last Name:"]},{"tag":"input","attributes":{"type":"text","name":"FirstLastName","id":"FirstLastName","value":"","maxlength":"","style":"width:200px;"}},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"for":"PhoneNumber","style":"float:left;width:140px;"},"children":["Phone Number:"]},{"tag":"input","attributes":{"type":"text","name":"PhoneNumber","id":"PhoneNumber","value":"","maxlength":"","style":"width:200px;"}},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"style":"float:left;width:140px;"},"children":["Your Age:"]},{"tag":"span","attributes":{"name":"Age"},"children":[{"tag":"input","attributes":{"type":"radio","name":"Age","id":"Age1radioOption","value":"19 and under","style":"vertical-align: middle;border:0px;background-color:transparent"},"children":[{"tag":"label","attributes":{"for":"Age1radioOption"},"children":["19 and under"]}]},{"tag":"input","attributes":{"type":"radio","name":"Age","id":"Age2radioOption","value":"20-30","style":"vertical-align: middle;border:0px;background-color:transparent","checked":"checked"},"children":[{"tag":"label","attributes":{"for":"Age2radioOption"},"children":["20-30"]}]},{"tag":"input","attributes":{"type":"radio","name":"Age","id":"Age3radioOption","value":"31 and older","style":"vertical-align: middle;border:0px;background-color:transparent"},"children":[{"tag":"label","attributes":{"for":"Age3radioOption"},"children":["31 and older"]}]}]},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"for":"Comments","style":"float:left;width:140px;"},"children":["Comments:"]},{"tag":"textarea","attributes":{"name":"Comments","id":"Comments","maxlength":"","style":"width:200px;height:150px;"},"children":[""]},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]}];
		/* Feedback Form */
		templates[2] = [{"tag":"label","attributes":{"for":"YourName","style":"float:left;width:140px;"},"children":["Your Name:"]},{"tag":"input","attributes":{"type":"text","name":"YourName","id":"YourName","value":"","maxlength":"","style":"width:200px;"}},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"for":"replyemail","style":"float:left;width:140px;"},"children":["Your Email:"]},{"tag":"input","attributes":{"type":"text","name":"replyemail","id":"replyemail","value":"","maxlength":"","style":"width:200px;"}},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"style":"float:left;width:140px;","for":"HearAboutUs"},"children":["How did you hear about us?"]},{"tag":"select","attributes":{"name":"HearAboutUs","id":"HearAboutUs"},"children":[{"tag":"option","attributes":{"value":"Friend"},"children":["Friend"]},{"tag":"option","attributes":{"value":"TV"},"children":["TV"]},{"tag":"option","attributes":{"value":"Radio"},"children":["Radio"]},{"tag":"option","attributes":{"value":"Newspaper"},"children":["Newspaper"]},{"tag":"option","attributes":{"value":"Ad"},"children":["Ad"]},{"tag":"option","attributes":{"value":"Internet"},"children":["Internet"]},{"tag":"option","attributes":{"value":"Other"},"children":["Other"]}]},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"for":"MessageComments","style":"display:block;margin-bottom:5px;"},"children":["Message/Comments:"]},{"tag":"textarea","attributes":{"name":"MessageComments","id":"MessageComments","maxlength":"","style":"width:400px;height:100px;"},"children":[""]},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]}];
		/* Order Form */
		templates[3] = [{"tag":"label","attributes":{"for":"FirstName","style":"float:left;width:140px;"},"children":["First Name:"]},{"tag":"input","attributes":{"type":"text","name":"FirstName","id":"FirstName","value":"","maxlength":"","style":"width:200px;"}},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"for":"LastName","style":"float:left;width:140px;"},"children":["Last Name:"]},{"tag":"input","attributes":{"type":"text","name":"LastName","id":"LastName","value":"","maxlength":"","style":"width:200px;"}},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"for":"PhoneNumber","style":"float:left;width:140px;"},"children":["Phone Number:"]},{"tag":"input","attributes":{"type":"text","name":"PhoneNumber","id":"PhoneNumber","value":"","maxlength":"","style":"width:200px;"}},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"for":"AddressLineOne","style":"float:left;width:140px;"},"children":["Address Line 1:"]},{"tag":"input","attributes":{"type":"text","name":"AddressLineOne","id":"AddressLineOne","value":"","maxlength":"","style":"width:200px;"}},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"for":"AddressLineTwo","style":"float:left;width:140px;"},"children":["Address Line 2:"]},{"tag":"input","attributes":{"type":"text","name":"AddressLineTwo","id":"AddressLineTwo","value":"","maxlength":"","style":"width:200px;"}},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"for":"City","style":"float:left;width:140px;"},"children":["City:"]},{"tag":"input","attributes":{"type":"text","name":"City","id":"City","value":"","maxlength":"","style":"width:200px;"}},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"for":"StateProvince","style":"float:left;width:140px;"},"children":["State/Province:"]},{"tag":"input","attributes":{"type":"text","name":"StateProvince ","id":"StateProvince ","value":"","maxlength":"","style":"width:200px;"}},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"for":"Country","style":"float:left;width:140px;"},"children":["Country:"]},{"tag":"input","attributes":{"type":"text","name":"Country","id":"Country","value":"","maxlength":"","style":"width:200px;"}},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"for":"ZipPostalCode","style":"float:left;width:140px;"},"children":["Zip/Postal Code:"]},{"tag":"input","attributes":{"type":"text","name":"ZipPostalCode","id":"ZipPostalCode","value":"","maxlength":"","style":"width:200px;"}},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"for":"FirstItemNumber","style":"float:left;width:140px;"},"children":["1. Item Number:"]},{"tag":"input","attributes":{"type":"text","name":"FirstItemNumber","id":"FirstItemNumber","value":"","maxlength":"","style":"width:200px;"}},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"for":"FirstQuantity","style":"float:left;width:140px;"},"children":["1. Quantity:"]},{"tag":"input","attributes":{"type":"text","name":"FirstQuantity","id":"FirstQuantity","value":"","maxlength":"","style":"width:200px;"}},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"for":"SecondItemNumber","style":"float:left;width:140px;"},"children":["2. Item Number:"]},{"tag":"input","attributes":{"type":"text","name":"SecondItemNumber","id":"SecondItemNumber","value":"","maxlength":"","style":"width:200px;"}},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"for":"SecondQuantity","style":"float:left;width:140px;"},"children":["2. Quantity:"]},{"tag":"input","attributes":{"type":"text","name":"SecondQuantity","id":"SecondQuantity","value":"","maxlength":"","style":"width:200px;"}},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"for":"SpecialDeliveryInstructions","style":"float:left;width:140px;"},"children":["Delivery Instructions:"]},{"tag":"textarea","attributes":{"name":"SpecialDeliveryInstructions","id":"SpecialDeliveryInstructions","maxlength":"","style":"width:200px;height:100px;"},"children":[""]},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"for":"OtherComments","style":"float:left;width:140px;"},"children":["Other Comments:"]},{"tag":"textarea","attributes":{"name":"OtherComments","id":"OtherComments","maxlength":"","style":"width:200px;height:100px;"},"children":[""]},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"div","attributes":{"style":"clear:left;height:10px;"},"children":[" "]}];
		/* Review Form */
		templates[4] = [{"tag":"label","attributes":{"for":"NameFirstLast","style":"float:left;width:140px;"},"children":["Name (First and Last):"]},{"tag":"input","attributes":{"type":"text","name":"NameFirstLast","id":"NameFirstLast","value":"","maxlength":"","style":"width:200px;"}},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"for":"replyemail","style":"float:left;width:140px;"},"children":["E-Mail Address:"]},{"tag":"input","attributes":{"type":"text","name":"replyemail","id":"replyemail","value":"","maxlength":"","style":"width:200px;"}},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"for":"YourAge","style":"float:left;width:140px;"},"children":["Your Age:"]},{"tag":"input","attributes":{"type":"text","name":"YourAge","id":"YourAge","value":"","maxlength":"","style":"width:200px;"}},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"for":"YourLocation","style":"float:left;width:140px;"},"children":["Your Location:"]},{"tag":"input","attributes":{"type":"text","name":"YourLocation","id":"YourLocation","value":"","maxlength":"","style":"width:200px;"}},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"for":"WhatDidYouReview","style":"display:block;margin-bottom:5px;"},"children":["What Did You Review?"]},{"tag":"textarea","attributes":{"name":"WhatDidYouReview","id":"WhatDidYouReview","maxlength":"","style":"width:400px;height:50px;"},"children":[""]},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"for":"YourReview","style":"display:block;margin-bottom:5px;"},"children":["Your Review:"]},{"tag":"textarea","attributes":{"name":"YourReview","id":"YourReview","maxlength":"","style":"width:400px;height:100px;"},"children":[""]},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"style":"float:left;width:140px;","for":"YourReviewRating"},"children":["Your Review Rating:"]},{"tag":"select","attributes":{"name":"YourReviewRating","id":"YourReviewRating"},"children":[{"tag":"option","attributes":{"value":"1"},"children":["1"]},{"tag":"option","attributes":{"value":"2"},"children":["2"]},{"tag":"option","attributes":{"value":"3"},"children":["3"]},{"tag":"option","attributes":{"value":"4"},"children":["4"]},{"tag":"option","attributes":{"value":"5"},"children":["5"]},{"tag":"option","attributes":{"value":"6"},"children":["6"]},{"tag":"option","attributes":{"value":"7"},"children":["7"]},{"tag":"option","attributes":{"value":"8"},"children":["8"]},{"tag":"option","attributes":{"value":"9"},"children":["9"]},{"tag":"option","attributes":{"value":"10"},"children":["10"]}]},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"for":"ReviewSignature","style":"float:left;width:140px;"},"children":["Review Signature:"]},{"tag":"input","attributes":{"type":"text","name":"ReviewSignature","id":"ReviewSignature","value":"","maxlength":"","style":"width:200px;"}},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]}];
		/* Web Survey Form */
		templates[5] = [{"tag":"label","attributes":{"for":"Name","style":"float:left;width:140px;"},"children":["Name:"]},{"tag":"input","attributes":{"type":"text","name":"Name","id":"Name","value":"","maxlength":"","style":"width:200px;"}},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"for":"Location","style":"float:left;width:140px;"},"children":["Location:"]},{"tag":"input","attributes":{"type":"text","name":"Location","id":"Location","value":"","maxlength":"","style":"width:200px;"}},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"for":"LookingFor","style":"display:block;margin-bottom:5px;"},"children":["What were you looking for on our Web site?"]},{"tag":"textarea","attributes":{"name":"LookingFor","id":"LookingFor","maxlength":"","style":"width:400px;height:50px;"},"children":[""]},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"style":"display:block;margin-bottom:5px;"},"children":["Did you find everything you were looking for? (5=Exactly, 1=Not At All)"]},{"tag":"span","attributes":{"name":"FindLookingFor"},"children":[{"tag":"input","attributes":{"type":"radio","name":"FindLookingFor","id":"FindLookingFor1radioOption","value":"1","style":"vertical-align: middle;border:0px;background-color:transparent"},"children":[{"tag":"label","attributes":{"for":"FindLookingFor1radioOption"},"children":["1"]}]},{"tag":"input","attributes":{"type":"radio","name":"FindLookingFor","id":"FindLookingFor2radioOption","value":"2","style":"vertical-align: middle;border:0px;background-color:transparent"},"children":[{"tag":"label","attributes":{"for":"FindLookingFor2radioOption"},"children":["2"]}]},{"tag":"input","attributes":{"type":"radio","name":"FindLookingFor","id":"FindLookingFor3radioOption","value":"3","style":"vertical-align: middle;border:0px;background-color:transparent","checked":"checked"},"children":[{"tag":"label","attributes":{"for":"FindLookingFor3radioOption"},"children":["3"]}]},{"tag":"input","attributes":{"type":"radio","name":"FindLookingFor","id":"FindLookingFor4radioOption","value":"4","style":"vertical-align: middle;border:0px;background-color:transparent"},"children":[{"tag":"label","attributes":{"for":"FindLookingFor4radioOption"},"children":["4"]}]},{"tag":"input","attributes":{"type":"radio","name":"FindLookingFor","id":"FindLookingFor5radioOption","value":"5","style":"vertical-align: middle;border:0px;background-color:transparent"},"children":[{"tag":"label","attributes":{"for":"FindLookingFor5radioOption"},"children":["5"]}]}]},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"style":"display:block;margin-bottom:5px;"},"children":["How useful was the information you found? (5=Very Useful, 1=Not At All)"]},{"tag":"span","attributes":{"name":"Usefulinformation"},"children":[{"tag":"input","attributes":{"type":"radio","name":"Usefulinformation","id":"Usefulinformation1radioOption","value":"1","style":"vertical-align: middle;border:0px;background-color:transparent"},"children":[{"tag":"label","attributes":{"for":"Usefulinformation1radioOption"},"children":["1"]}]},{"tag":"input","attributes":{"type":"radio","name":"Usefulinformation","id":"Usefulinformation2radioOption","value":"2","style":"vertical-align: middle;border:0px;background-color:transparent"},"children":[{"tag":"label","attributes":{"for":"Usefulinformation2radioOption"},"children":["2"]}]},{"tag":"input","attributes":{"type":"radio","name":"Usefulinformation","id":"Usefulinformation3radioOption","value":"3","style":"vertical-align: middle;border:0px;background-color:transparent","checked":"checked"},"children":[{"tag":"label","attributes":{"for":"Usefulinformation3radioOption"},"children":["3"]}]},{"tag":"input","attributes":{"type":"radio","name":"Usefulinformation","id":"Usefulinformation4radioOption","value":"4","style":"vertical-align: middle;border:0px;background-color:transparent"},"children":[{"tag":"label","attributes":{"for":"Usefulinformation4radioOption"},"children":["4"]}]},{"tag":"input","attributes":{"type":"radio","name":"Usefulinformation","id":"Usefulinformation5radioOption","value":"5","style":"vertical-align: middle;border:0px;background-color:transparent"},"children":[{"tag":"label","attributes":{"for":"Usefulinformation5radioOption"},"children":["5"]}]}]},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"style":"display:block;margin-bottom:5px;"},"children":["Did you find our site easy to use? (5=Easy To use, 1=Very Difficult)"]},{"tag":"span","attributes":{"name":"SiteNavagation"},"children":[{"tag":"input","attributes":{"type":"radio","name":"SiteNavagation","id":"SiteNavagation1radioOption","value":"1","style":"vertical-align: middle;border:0px;background-color:transparent"},"children":[{"tag":"label","attributes":{"for":"SiteNavagation1radioOption"},"children":["1"]}]},{"tag":"input","attributes":{"type":"radio","name":"SiteNavagation","id":"SiteNavagation2radioOption","value":"2","style":"vertical-align: middle;border:0px;background-color:transparent"},"children":[{"tag":"label","attributes":{"for":"SiteNavagation2radioOption"},"children":["2"]}]},{"tag":"input","attributes":{"type":"radio","name":"SiteNavagation","id":"SiteNavagation3radioOption","value":"3","style":"vertical-align: middle;border:0px;background-color:transparent","checked":"checked"},"children":[{"tag":"label","attributes":{"for":"SiteNavagation3radioOption"},"children":["3"]}]},{"tag":"input","attributes":{"type":"radio","name":"SiteNavagation","id":"SiteNavagation4radioOption","value":"4","style":"vertical-align: middle;border:0px;background-color:transparent"},"children":[{"tag":"label","attributes":{"for":"SiteNavagation4radioOption"},"children":["4"]}]},{"tag":"input","attributes":{"type":"radio","name":"SiteNavagation","id":"SiteNavagation5radioOption","value":"5","style":"vertical-align: middle;border:0px;background-color:transparent"},"children":[{"tag":"label","attributes":{"for":"SiteNavagation5radioOption"},"children":["5"]}]}]},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"style":"display:block;margin-bottom:5px;"},"children":["How would you rate our site overall? (5=Perfect, 1=Needs a lot of Improvement)"]},{"tag":"span","attributes":{"name":"Site Rating"},"children":[{"tag":"input","attributes":{"type":"radio","name":"Site Rating","id":"Site Rating1radioOption","value":"1","style":"vertical-align: middle;border:0px;background-color:transparent"},"children":[{"tag":"label","attributes":{"for":"Site Rating1radioOption"},"children":["1"]}]},{"tag":"input","attributes":{"type":"radio","name":"Site Rating","id":"Site Rating2radioOption","value":"2","style":"vertical-align: middle;border:0px;background-color:transparent"},"children":[{"tag":"label","attributes":{"for":"Site Rating2radioOption"},"children":["2"]}]},{"tag":"input","attributes":{"type":"radio","name":"Site Rating","id":"Site Rating3radioOption","value":"3","style":"vertical-align: middle;border:0px;background-color:transparent","checked":"checked"},"children":[{"tag":"label","attributes":{"for":"Site Rating3radioOption"},"children":["3"]}]},{"tag":"input","attributes":{"type":"radio","name":"Site Rating","id":"Site Rating4radioOption","value":"4","style":"vertical-align: middle;border:0px;background-color:transparent"},"children":[{"tag":"label","attributes":{"for":"Site Rating4radioOption"},"children":["4"]}]},{"tag":"input","attributes":{"type":"radio","name":"Site Rating","id":"Site Rating5radioOption","value":"5","style":"vertical-align: middle;border:0px;background-color:transparent"},"children":[{"tag":"label","attributes":{"for":"Site Rating5radioOption"},"children":["5"]}]}]},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"style":"float:left;width:140px;","for":"WillYouBeBack"},"children":["Will You Be Back?"]},{"tag":"select","attributes":{"name":"WillYouBeBack","id":"WillYouBeBack"},"children":[{"tag":"option","attributes":{"value":"Yes"},"children":["Yes"]},{"tag":"option","attributes":{"value":"Undecided","selected":"selected"},"children":["Undecided"]},{"tag":"option","attributes":{"value":"No"},"children":["No"]}]},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]},{"tag":"label","attributes":{"for":"Comments","style":"display:block;margin-bottom:5px;"},"children":["Please provide additional information or comments:"]},{"tag":"textarea","attributes":{"name":"Comments","id":"Comments","maxlength":"","style":"width:400px;height:100px;"},"children":[""]},{"tag":"div","attributes":{"style":"clear:left;height:20px;"},"children":[" "]}];
		/* Blank Form */
		templates[6] = [];
		if(typeof(templates[tID])=="object")
		{	
			theForm = templates[tID];
			templateName = template_names[tID];
			if(myFormTitle) { templateName = myFormTitle; }
			renderer.render(theForm);
			this.updateManager();
			this.createCode();
			this.formData(':|:'+templateName+':|:');
			if(this.checkBrowser('safari'))
			{
				(theForm!='') ? Tab('previewWrapper'):Tab('buildWrapper');
			}
			else
			{
				(theForm!='') ? document.location.href='#3':document.location.href='#2';
			}
		}
		else
		{
			alert('Could not load the selected template.  Please try another');
		}
	}
	this.loadDB = function(formid)
	{
		if(formid)
		{
			myFormTitle 	= '';
			tabbing 	= true;
			var url 	= 'builderajax.php';
			var pars 	= 'formid=' + formid;
			var target	= 'savedForms';
			var myAjax	= new Ajax.Updater(target, url, {method: 'post', parameters: pars, evalScripts: true, onComplete: this.loadSaved});
			this.Message('Loading It..');
		}
		else
		{
			alert('Sorry, could not load the selected form.  Please try again.');
		}
		return false;
	}
	this.deleteForm = function(formid)
	{
		if(formid)
		{
			var url = 'builderajax_deleteform.php';
			var pars = 'formid=' + formid;
			var target = 'actionWrapper';
			var myAjax = new Ajax.Updater(target, url, {method: 'post', parameters: pars, evalScripts: true});
			this.Message('Deleting Form..');
			
		}
		else
		{
			alert('There is no form to delete');
		}
	}
	this.renameFormDB = function(formid,fTitle)
	{
		if(formid)
		{
			var url = 'builderajax_renameform.php';
			var pars = 'formid=' + formid + '&ftitle= ' + fTitle;
			var target = 'actionWrapper';
			var myAjax = new Ajax.Updater(target, url, {method: 'post', parameters: pars, evalScripts: true});
			this.Message('Renaming Form..');
		}
	}
	this.loadSaved = function()
	{
		var thisForm = $('savedForms').innerHTML;
		thisForm = thisForm.replace(/<script*>*<\/script>/i, '', thisForm);
		theForm = eval(thisForm);
		renderer.render(theForm);
	}
	this.prepSave = function()
	{
		if(typeof(formid)!="undefined")
		{
			var url 	= 'builderajax_saveddata.php';
			var pars 	= 'formid=' + formid;
			var target	= 'saveData';
			var myAjax	= new Ajax.Updater(target, url, {method: 'get', parameters: pars, onComplete: this.formData});
		}
	}
	this.formData = function(passedData)
	{
		//formid 	= $('loadDB').saved.value;
		/*if(formid)
		{*/
			if(typeof(passedData)=="object")
			{
				var saveData = $('saveData').innerHTML;
			}
			else
			{
				var saveData = passedData;
			}
			
			saveData = saveData.split(":|:");
			templateName = saveData[1];
			if(myFormTitle) { templateName = myFormTitle; }
			formbuilder.Message('<strong>' + saveData[1] + '</strong> has been successfully loaded.');
			if(saveData)
			{
				$('enameLabel').innerHTML = 'Currently Editing:';
				$('eformName').value = saveData[1];
				$('eformID').value = saveData[0];
				if(saveData[2])
				{
					$('lastModified').innerHTML = '<strong style="float:left;width:130px;">Last Modified: </strong>' + saveData[2];
					$('lastModified').style.display = 'block';
					$('saveFormButton').value = 'update form';
				}
				else
				{
					$('lastModified').style.display = 'none';
					$('saveFormButton').value = 'save form';
				}
				tabbing=true;
			/*}*/
			}
			formbuilder.updateManager();
			formbuilder.createCode();
		
	}
	this.saveForm = function()
	{
		if($('eformName').value=='')
		{
			alert('You must specify a name for your form');
			return false;
		}
		if($('eformID').value!= '')
		{
			var url = 'builderajax_updateform.php';
			var pars = 'formid=' + $('eformID').value + '&formname=' + $('eformName').value + '&builderobject=' + escape(theForm.toJSONString());
			var target = 'actionWrapper';
			var myAjax = new Ajax.Updater(target, url, {method: 'post', parameters: pars, onComplete: this.saveDone});
		}
		else
		{
			if(theForm=='')
			{
				alert('You have not added any elements to your new form.  Please add at least one element before you attempt to save');
			}
			else
			{
				var url = 'builderajax_saveform.php';
				var pars = 'formid=' + $('eformID').value + '&formname=' + $('eformName').value + '&builderobject=' + escape(theForm.toJSONString());
				var target = 'actionWrapper';
				var myAjax = new Ajax.Updater(target, url, {method: 'post', parameters: pars, onComplete: this.saveDone});
			}
		}
	}
	
	this.saveDone = function()
	{
		formbuilder.updateManager();
		$('actionWrapper').style.display='block';
		fader = setTimeout("formbuilder.fadeMessage()", 1500);
		if(this.checkBrowser('safari'))
		{
			Tab('formsWrapper');
		}
		else
		{
			window.location.href='#1';
		}
		savedFormBeforeUnload = true;
	}
}
