$(document).ready(function(){
var constRad="Radio buttons";
var constChk="Checkbox";
var constDDL="Select/drop-down list";
var constEmail="Email address";
var constUrl="URL/Web address";
var constTel="Telephone number";
var constSearch="Search field";
var constSlider="Slider/Range control";
var constNumber="Number/Spinner control";
var constDate="Date picker";
var constMonth="Date picker (month)";
var constWeek="Date picker (week)";
var constTime="Time picker";
var constDateTime="Date + time picker";
var constDateTimeLocal="Date + time picker (local)";
var constColor="Color picker";
var usesHTML5=false;
var html5ElementsUsedCount=0;
var strHTML5JsFallback="";
var usesHTML5email = false;
var usesHTML5url = false;
var usesHTML5tel = false;
var usesHTML5search = false;
var usesHTML5range = false;
var usesHTML5number = false;
var usesHTML5date = false;
var usesHTML5datetime = false;
var usesHTML5datetimeLocal = false;
var usesHTML5month = false;
var usesHTML5week = false;
var usesHTML5color = false;

var uniqueInputID=0;
var strGeneratedMarkup="";
var thisType="";
var thisFieldName="";
var thisFieldOptions="";
var radName = 0;
var thisFieldNameJunkRemoved = "";
var inputName="";
var inputId="";
var requiredField = false;
var createAriaLabelledBy = false;
var requiredFieldInd = "";
var strClassReqd = "";
var ariaLabelName = "";
var ariaLabelNamedBy = "";
var strTitle="";
$("#QFstep2,#QFstep3,#QFstep4").hide();
$("#QFbtnStep1").click(function(){
	if ($("#QFallFormFields").val().length==0) {
		alert("Oops, you need to enter some fields here first ...");
	}
	else {
		// $("#QFstep1").slideUp("fast");
		// $("#QFstep2").slideDown("fast");
		$("#QFstep1").hide();
		$("#QFstep2").show();
		var arrAllFields = $("#QFallFormFields").val().split("\n");
		var loopLength = arrAllFields.length;
		$("#QFformInputRows").html("").append("<div><input id=\"QFmarkAllReqd\" type=\"checkbox\"> <label for=\"QFmarkAllReqd\">Mark all fields as required</label></div>");
		$("#QFmarkAllReqd").click(function(){
			$("input.QFchkboxReq").click();
		});
		for (i=0; i<loopLength; i++) {
			var thisRow = arrAllFields[i];
			if (thisRow.length > 1) {
				$("#QFformInputRows").append("<div class=\"QFformRow\"><input class=\"QFhdnFieldName\" type=\"hidden\" value=\"" + arrAllFields[i] + "\"><input class=\"QFhdnFieldOptions\" type=\"hidden\" value=\"\"><label for=\"input" + (i+1) + "Type\"> " + arrAllFields[i] + "</label><select id=\"input" + (i+1) + "Type\"><option value=\"text\">Text input</option><option value=\"password\">Password</option><option value=\"textarea\">Text area</option><option value=\"select\">" + constDDL + "</option><option value=\"checkbox\">" + constChk + "</option><option value=\"radio\">" + constRad + "</option><optgroup label=\"Experimental HTML5 input types\"><option value=\"email\">" + constEmail + "</option><option value=\"url\">" + constUrl + "</option><option value=\"tel\">" + constTel + "</option><option value=\"search\">" + constSearch + "</option><option value=\"range\">" + constSlider + "</option><option value=\"number\">" + constNumber + "</option><option value=\"date\">" + constDate + "</option><option value=\"month\">" + constMonth + "</option><option value=\"week\">" + constWeek + "</option><option value=\"time\">" + constTime + "</option><option value=\"datetime\">" + constDateTime + "</option><option value=\"datetime-local\">" + constDateTimeLocal + "</option><option value=\"color\">" + constColor + "</option></optgroup></select><span class=\"QFchkReq\"><input type=\"checkbox\" class=\"QFchkboxReq\" id=\"req_" + (i+1) + "\" value=\"req\"><label for=\"req_" + (i+1) + "\">Required field?</label></span><div class=\"QFinputOptions\" id=\"input" + (i+1) + "Options\"></div></div>");
			}
		}
		$("#QFformInputRows select").change(function(){
				$(this).next().next().hide();
				var selected = $(this).val();
				if (selected=="select") {
					$(this).next().next().html("<label>Please enter <code>select</code> list values here (one line per option):</label><br><textarea></textarea>\n");
				}
				else if (selected=="radio") {
					$(this).next().next().html("<label>Please enter <code>radio</code> button values here (one line per radio):</label><br><textarea></textarea>\n");
				}
				else if ((selected=="email")||(selected=="url")||(selected=="tel")||(selected=="search")||(selected=="range")||(selected=="number")||(selected=="date")||(selected=="color")) {
					//$(this).next().next().html("HTML5\n");
					if ((selected=="range")||(selected=="number")) {
						$(this).next().next().html("<div><label for=\"" + $(this).attr("id") + "_min" + "\">Lower figure</label><input class=\"minval\" id=\"" + $(this).attr("id") + "_min" + "\"></div><div><label for=\"" + $(this).attr("id") + "_max" + "\">Upper figure</label><input class=\"maxval\" id=\"" + $(this).attr("id") + "_max" + "\"></div><div><label for=\"" + $(this).attr("id") + "_step" + "\">Step</label><input class=\"stepval\" id=\"" + $(this).attr("id") + "_step" + "\"></div><div><label for=\"" + $(this).attr("id") + "_def" + "\">Default value</label><input class=\"defval\" id=\"" + $(this).attr("id") + "_def" + "\"></div>\n");
					}
					else {
						$(this).next().next().html("");
					}
					if (selected=="email") {
					}
					if (selected=="url") {
					}
					if (selected=="tel") {
					}
					if (selected=="search") {
					}
					if (selected=="date") {
					}
					if (selected=="color") {
					}
				}
				else {
					$(this).next().next().html("");
				}
				$(this).next().next().slideDown('medium');
			})
	}
});
$("#QFbtnStep2").click(function(){
	var emptySelectOrRadios = false;
	$("div.QFinputOptions textarea").each(function(){
		if ($(this).val().length==0) {
			$(this).css("border","2px solid red");
			emptySelectOrRadios = true;
		}
	});
	if (emptySelectOrRadios) {
		alert("Oops, you've missed some radio or select options");
	}
	else {
		// $("#QFstep2").slideUp("fast");
		// $("#QFstep3").slideDown("fast");
		$("#QFstep2").hide();
		$("#QFstep3").show();
	}
});
$("#QFbtnStep3").click(function(){
	$("#QFformInputRows .QFformRow .QFinputOptions textarea").each(function(){
		$(this).parent().parent().find("input.QFhdnFieldOptions").val($(this).val());
	});
	// $("#QFstep3").slideUp("fast");
	// $("#QFstep4").slideDown("fast");
	$("#QFstep3").hide();
	$("#QFstep4").show();

	var syntax = $("input[name=QFradMarkupSyntax']:checked").val();
	var formMethod = $("input[name=QFradFormMethod']:checked").val();
	var formAction = $("#QFformAction").val();
	var formNameId = $("#QFformNameId").val();
	var tagEnd="";
	var createIdFromFieldName = false;
	var addFormControlPrefixes = false;
	var reqHelpText = $("#QFrequiredFieldHelpText").val();
	if ($("input[name=QFchkLabelsFromNames]:checked").val()=="on") {
		createIdFromFieldName = true;
	}
	if ($("input[name=QFchkAriaLabelledBy]:checked").val()=="on") {
		createAriaLabelledBy = true;
	}
	if ($("input[name=QFchkPrefixFormNames]:checked").val()=="on") {
		addFormControlPrefixes = true;
	}
	if (syntax=="XHTML") {tagEnd=" /";}
				
	strGeneratedMarkup="";
	strGeneratedMarkup+="<form";
	if (formAction.length>0) {
		strGeneratedMarkup+=" action=\"" + formAction + "\"";
	}
	strGeneratedMarkup+=" method=\"" + formMethod + "\"";
	if (formNameId.length>0)
	{
		if (syntax=="HTML") {
			strGeneratedMarkup+=" name=\"" + formNameId + "\"";
		}
		if (syntax=="XHTML") {
			strGeneratedMarkup+=" id=\"" + formNameId + "\"";
		}
	}
	strGeneratedMarkup+=">\n";
	$("div.QFformRow").each(function(){
		requiredField = false;
		if ($(this).children("span").children("input:checked").val()=="req") {
			requiredField = true;
		}
		thisType = $(this).children("select").val();
		thisFieldName = $(this).children("input.QFhdnFieldName").val();
		thisFieldNameJunkRemoved = thisFieldName.replace(/[\s\,\.\'\"\\\/()*&@!~`;:|=+]/g,'');
		thisFieldOptions = $(this).children("input.QFhdnFieldOptions").val();
		uniqueInputID++;
		strGeneratedMarkup+="<div class=\"row";
		if (requiredField) {
			strGeneratedMarkup+=" requiredRow";
			strClassReqd = " class=\"required\"";
		}
		else {
			strClassReqd = "";
		}
		strGeneratedMarkup+="\"";
		strGeneratedMarkup+=">\n";

		if (createIdFromFieldName) {
			inputName=thisFieldNameJunkRemoved;
			inputId=thisFieldNameJunkRemoved;
		}
		else {
			inputName = "FormCtrl" + "_" + uniqueInputID;
			inputId = "FormCtrl" + "_" + uniqueInputID
		}
		if (createAriaLabelledBy)
		{
			ariaLabelName=" id=\"" + inputId + "-ariaLabel\"";
			ariaLabelNamedBy=" aria-labelledby=\"" + inputId + "-ariaLabel\"";
		}
		if (addFormControlPrefixes) {
			if (thisType=="radio") {
				inputName = "rad_" + inputName;
				inputId = "rad_" + inputId;
			}
			if (thisType=="checkbox") {
				inputName = "chk_" + inputName;
				inputId = "chk_" + inputId;
			}
			if (thisType=="text") {
				inputName = "txt_" + inputName;
				inputId = "txt_" + inputId;
			}
			if (thisType=="password") {
				inputName = "pwd_" + inputName;
				inputId = "pwd_" + inputId;
			}
			if (thisType=="textarea") {
				inputName = "txtarea_" + inputName;
				inputId = "txtarea_" + inputId;
			}
			if (thisType=="select") {
				inputName = "sel_" + inputName;
				inputId = "sel_" + inputId;
			}
			if (thisType=="range") {
				inputName = "sldr_" + inputName;
				inputId = "sldr_" + inputId;
			}
		}

		if (thisType=="radio") {
			strGeneratedMarkup+="\t<fieldset>\n";
			strGeneratedMarkup+="\t\t<legend>" + thisFieldName + "</legend>\n";
			if (thisFieldOptions.length>0) {
				thisFieldOptions = thisFieldOptions.split("\n");
				for (l=0; l<thisFieldOptions.length; l++) {
					 if (requiredField) {
					 	strTitle=" title=\"" + thisFieldOptions[l] + ". " + reqHelpText + "\"";
					 }
					radName++;
					strGeneratedMarkup+="\t\t<span>";
					inputId = inputName + "_" + radName;
					strGeneratedMarkup+="<input value=\"" + thisFieldOptions[l] + "\" id=\"" + inputId + "\" name=\"" + inputName + "\" type=\"" + thisType + "\"" + ariaLabelNamedBy + strClassReqd + strTitle + tagEnd + "> ";
					strGeneratedMarkup+="<label for=\"" + inputId + "\"" + ariaLabelName + ">";
					strGeneratedMarkup+=thisFieldOptions[l];
					strGeneratedMarkup+="</label>";
					strGeneratedMarkup+="</span>\n ";
				}
			}
			strGeneratedMarkup+="\t</fieldset>\n";
		}

		if ((thisType=="text")||(thisType=="password")||(thisType=="textarea")||(thisType=="select")) {
		 if (requiredField) {
		 	strTitle=" title=\"" + thisFieldName + ". " + reqHelpText + "\"";
		 	}
		else {
		 	strTitle="";
		}	
		}

		if (thisType=="checkbox") {
			strGeneratedMarkup+="\t<input id=\"" + inputId + "\" name=\"" + inputName + "\" type=\"" + thisType + "\"" + ariaLabelNamedBy + strClassReqd + strTitle + tagEnd + ">\n";
			strGeneratedMarkup+="\t<span>";
			strGeneratedMarkup+="<label for=\"" + inputId + "\"" + ariaLabelName + ">";
			strGeneratedMarkup+=thisFieldName;
			strGeneratedMarkup+="</label>";
			strGeneratedMarkup+="</span>\n";
		}


		if ((thisType!="checkbox")&&(thisType!="radio")) {
			strGeneratedMarkup+="\t<label for=\"" + inputId + "\"" + ariaLabelName + ">";
			strGeneratedMarkup+=thisFieldName;
			strGeneratedMarkup+="</label>\n";
		}
//		if ((thisType=="text")||(thisType=="password")||(thisType=="email")||(thisType=="url")||(thisType=="tel")||(thisType=="search")||(thisType=="number")||(thisType=="date")||(thisType=="color")) {
		if ((thisType=="text")||(thisType=="password")||(thisType=="email")||(thisType=="url")||(thisType=="tel")||(thisType=="search")||(thisType=="date")||(thisType=="month")||(thisType=="week")||(thisType=="time")||(thisType=="datetime")||(thisType=="datetime-local")||(thisType=="color")) {
			strGeneratedMarkup+="\t<input id=\"" + inputId + "\" name=\"" + inputName + "\" type=\"" + thisType + "\"" + ariaLabelNamedBy + strClassReqd + strTitle + tagEnd + ">\n";
		}
		if ((thisType=="range")||(thisType=="number")||(thisType=="email")||(thisType=="url")||(thisType=="tel")||(thisType=="search")||(thisType=="date")||(thisType=="month")||(thisType=="week")||(thisType=="time")||(thisType=="datetime")||(thisType=="datetime-local")||(thisType=="color"))
		{
			html5ElementsUsedCount++;
		}
		else
		{
		}
		if ((thisType=="range")||(thisType=="number")) {
			var minVal = $(this).find("input.minval").val();
			var maxVal = $(this).find("input.maxval").val();
			var stepVal = $(this).find("input.stepval").val();
			var defVal = $(this).find("input.defval").val();
			if (minVal!="") {minVal=" min=\"" + minVal + "\"";}
			if (maxVal!="") {maxVal=" max=\"" + maxVal + "\"";}
			if (stepVal!="") {stepVal=" step=\"" + stepVal + "\"";}
			if (defVal!="") {defVal=" value=\"" + defVal + "\"";}
			strGeneratedMarkup+="\t<input id=\"" + inputId + "\" name=\"" + inputName + "\" type=\"" + thisType + "\"" + ariaLabelNamedBy + strClassReqd + strTitle + minVal + maxVal + stepVal + defVal + tagEnd + ">\n";
		}
		if (thisType=="textarea") {
			strGeneratedMarkup+="\t<textarea id=\"" + inputId + "\" name=\"" + inputName + "\" cols=\"20\" rows=\"3\"" + ariaLabelNamedBy + strClassReqd + strTitle + "></textarea>\n";
		}
		if (thisType=="select") {
			strGeneratedMarkup+="\t<select id=\"" + inputId + "\" name=\"" + inputName + "\"" + ariaLabelNamedBy + strClassReqd + strTitle + ">\n";
			if (thisFieldOptions.length>0) {
				thisFieldOptions = thisFieldOptions.split("\n");
				for (l=0; l<thisFieldOptions.length; l++) {
					strGeneratedMarkup+="\t\t<option value=\"" + thisFieldOptions[l] + "\">";
					strGeneratedMarkup+=thisFieldOptions[l];
					strGeneratedMarkup+="</option>\n";
				}
			}
			strGeneratedMarkup+="\t</select>\n";
		}
		strGeneratedMarkup+="</div>\n";
		
		if (thisType=="email") {usesHTML5email=true;}
		if (thisType=="url") {usesHTML5url=true;}
		if (thisType=="tel") {usesHTML5tel=true;}
		if (thisType=="search") {usesHTML5search=true;}
		if (thisType=="range") {usesHTML5range=true;}
		if (thisType=="number") {usesHTML5number=true;}
		if (thisType=="date") {usesHTML5date=true;}
		if (thisType=="datetime") {usesHTML5datetime=true;}
		if (thisType=="datetime-local") {usesHTML5datetimeLocal=true;}
		if (thisType=="month") {usesHTML5month=true;}
		if (thisType=="week") {usesHTML5week=true;}
		if (thisType=="color") {usesHTML5color=true;}
	});
	var strSubmit = $("#QFformSubmitButton").val();
	if (strSubmit=="") {strSubmit="Submit form"}
	strGeneratedMarkup+="<div class=\"row\">\n";
	strGeneratedMarkup+="<input type=\"submit\" value=\"" + strSubmit + "\"" + tagEnd + ">\n";
	strGeneratedMarkup+="</div>\n";
	strGeneratedMarkup+="</form>\n";
	$("#QFgeneratedMarkup").val(strGeneratedMarkup);
	$("#QFgeneratedMarkup").focus(function(){
		$(this).select();
	});
	strHTML5JsFallback="";
	if (html5ElementsUsedCount>0) {
		strHTML5JsFallback += "&lt;script&gt;\n";
		strHTML5JsFallback += "function elementSupportsAttribute(element,attribute) {\n";
		strHTML5JsFallback += " var testEl = document.createElement(element);\n";
		strHTML5JsFallback += " testEl.setAttribute('type',attribute);\n";
		strHTML5JsFallback += " if (testEl.type==\"text\") {\n";
		strHTML5JsFallback += "  return false;\n";
		strHTML5JsFallback += " } else {\n";
		strHTML5JsFallback += "  return true;\n";
		strHTML5JsFallback += " }\n";
		strHTML5JsFallback += "}\n";
		strHTML5JsFallback += "\n";
		if (usesHTML5email)
		{
			strHTML5JsFallback += "if (!elementSupportsAttribute('input','email')) {\n";
			strHTML5JsFallback += "\/\/ Write custom email validation here\n";
			strHTML5JsFallback += "}\n";
		}
		if (usesHTML5url)
		{
			strHTML5JsFallback += "if (!elementSupportsAttribute('input','url')) {\n";
			strHTML5JsFallback += "\/\/ Write custom url validation here.\n";
			strHTML5JsFallback += "}\n";
		}
		if (usesHTML5tel)
		{
			strHTML5JsFallback += "if (!elementSupportsAttribute('input','tel')) {\n";
			strHTML5JsFallback += "\/\/ Write custom telephone number validation here.\n";
			strHTML5JsFallback += "}\n";
		}
		if (usesHTML5search)
		{
			strHTML5JsFallback += "if (!elementSupportsAttribute('input','search')) {\n";
			strHTML5JsFallback += "\/\/ JavaScript fallback for search functionality goes here.\n";
			strHTML5JsFallback += "}\n";
		}
		if (usesHTML5range)
		{
			strHTML5JsFallback += "if (!elementSupportsAttribute('input','range')) {\n";
			strHTML5JsFallback += "\/\/ JavaScript for custom slider/range control goes here.\n";
			strHTML5JsFallback += "}\n";
		}
		if (usesHTML5number)
		{
			strHTML5JsFallback += "if (!elementSupportsAttribute('input','number')) {\n";
			strHTML5JsFallback += "\/\/ JavaScript fallback for number/spinner control goes here.\n";
			strHTML5JsFallback += "}\n";
		}
		if (usesHTML5date)
		{
			strHTML5JsFallback += "if (!elementSupportsAttribute('input','date')) {\n";
			strHTML5JsFallback += "\/\/ JavaScript fallback for date picker.\n";
			strHTML5JsFallback += "}\n";
		}
		if (usesHTML5datetime)
		{
			strHTML5JsFallback += "if (!elementSupportsAttribute('input','datetime')) {\n";
			strHTML5JsFallback += "\/\/ JavaScript fallback for date (datetime) picker.\n";
			strHTML5JsFallback += "}\n";
		}
		if (usesHTML5datetimeLocal)
		{
			strHTML5JsFallback += "if (!elementSupportsAttribute('input','datetime-local')) {\n";
			strHTML5JsFallback += "\/\/ JavaScript fallback for date (datetime-local) picker.\n";
			strHTML5JsFallback += "}\n";
		}
		if (usesHTML5month)
		{
			strHTML5JsFallback += "if (!elementSupportsAttribute('input','month')) {\n";
			strHTML5JsFallback += "\/\/ JavaScript fallback for date (month) picker.\n";
			strHTML5JsFallback += "}\n";
		}
		if (usesHTML5week)
		{
			strHTML5JsFallback += "if (!elementSupportsAttribute('input','week')) {\n";
			strHTML5JsFallback += "\/\/ JavaScript fallback for date (week) picker.\n";
			strHTML5JsFallback += "}\n";
		}
		if (usesHTML5color)
		{
			strHTML5JsFallback += "if (!elementSupportsAttribute('input','color')) {\n";
			strHTML5JsFallback += "\/\/ JavaScript fallback for color picker tool goes here.\n";
			strHTML5JsFallback += "}\n";
		}

		strHTML5JsFallback += "&lt;\/script&gt;";
		$("#html5Warning").remove();
		$("#QFgeneratedMarkup").before("<div id=\"html5Warning\"><p><strong>Warning</strong>: You've chosen some HTML 5 form elements. Be aware that support for these is *very* sketchy at this time. Most browsers will simply treat them as <code>input type=\"text\"</code>.</p><p>You might want to provide a JavaScript alternative for browsers that do not support these HTML 5 form types (<a href=\"#\">view script example</a>)</p><div id=\"html5Script\"><p>This script is adapted from Jeremy Keith's example script used in <a href=\"http://books.alistapart.com/product/html5-for-web-designers\">HTML5 for Web Designers</a></p><code><pre>" + strHTML5JsFallback + "</pre></code></div></div>");
		$("#html5Script").hide();
		$("#html5Warning a:first").toggle(function(){$("#html5Script").show()},function(){$("#html5Script").hide()});
	}
	else {
		$("#html5Warning").remove();
		strHTML5JsFallback="";
	}
});
$("#QFbtnStep4").click(function(){
	$("#QFstep1").show();
	$("#QFstep1 textarea").val("");
	$("#QFstep2,#QFstep3,#QFstep4").hide();
	$("#QFformInputRows").html("");
});

$("#QFbtnStep2_back").click(function(){
	// $("#QFstep2").slideUp("fast");
	// $("#QFstep1").slideDown("fast");
	$("#QFstep2").hide();
	$("#QFstep1").show();
})
$("#QFbtnStep3_back").click(function(){
	// $("#QFstep3").slideUp("fast");
	// $("#QFstep2").slideDown("fast");
	$("#QFstep3").hide();
	$("#QFstep2").show();
	html5ElementsUsedCount=0;
})
$("#QFbtnStep4_back").click(function(){
	// $("#QFstep4").slideUp("fast");
	// $("#QFstep3").slideDown("fast");
	$("#QFstep4").hide();
	$("#QFstep3").show();
})
	$("#QFrevealCSS").click(function(){
		$("#QFgeneratedCss").slideToggle("fast").focus(function(){$("#QFgeneratedCss").select();});
		return false;
	})
	var showPreamble = true;
	$("#QFallFormFields").focus(function(){
		if (showPreamble) {
			$("#QFallFormFields").text("");
			showPreamble = false;
		}
	})
	// $("#QFbtnStep1").click();
	// $("#input1Type option:nth-child(5)").attr("selected","selected");
	// $("#input1Type").change();
	// $("#QFbtnStep2").click();
	// $("#QFbtnStep3").click();
});