(function() {
	'use strict';

	window.dataDrivenForm = window.dataDrivenForm || {};

	dataDrivenForm.formElementHTMLFactory = function (type, name, title) {
		if (!title || !title.length) {
			title = name;
		}
		var topPart = '<div><label><span>' + title + ':</span><br />';
		var bottomPart = '</label></div>';
		if (type === 'text') {
			return topPart +
				'<input type="text" maxlength="200" name="' + name + '" />' +
				bottomPart;
		} else if (type === 'email') {
			return topPart +
				'<input type="email" required name="' + name + '" />' +
				bottomPart;
		} else if (type === 'number') {
			return topPart +
				'<input type="number" min="0" max="2147483647" name="' + name + '" />' +
				bottomPart;
		} else if (type === 'date') {
			return topPart +
				'<input type="date" min="1900-01-01" name="' + name + '" />' +
				bottomPart;
		} else if (type === 'textarea') {
			return topPart +
				'<textarea cols="30" rows="3" maxlength="800" name="' + name + '" />' +
				bottomPart;
		} else if (type === 'checkbox') {
			return '<div><label><span>' + title + ':</span>' +
				'<input type="checkbox" name="' + name + '" />' +
				'</label></div>';
		} else if (type === 'notice') {
			return '<p>' + name + '</p>';
		}  else if (type === 'button') {
			return '<button name="' + name + '">' + title + '!</button>';
		}
	};

	dataDrivenForm.init = function() {
		for (var i = 0; i < dataDrivenForm.parts.length; i++) {
			var part = dataDrivenForm.parts[i];
			var elementHTML = dataDrivenForm.formElementHTMLFactory(part.type, part.name, part.title);
			// Sprawdzenie, czy wynik to wartość null, undefined lub pusty łańcuch
			if (elementHTML && elementHTML.length) {
				$('form').append(elementHTML);
			}
		}
	};
	$(document).ready(dataDrivenForm.init);

	dataDrivenForm.parts = [{
		type: 'text',
		name: 'firstname',
		title: 'Imię'
	}, {
		type: 'text',
		name: 'lastname',
		title: 'Nazwisko'
	}, {
		type: 'email',
		name: 'email',
		title: 'Adres e-mail'
	}, {
		type: 'date',
		name: 'birthdate',
		title: 'Data urodzenia'
	}, {
		type: 'number',
		name: 'experience',
		title: 'Doświadczenie (w latach)'
	}, {
		type: 'textarea',
		name: 'summary',
		title: 'Podsumowanie'
	}, {
		type: 'checkbox',
		name: 'receivenotifications',
		title: 'Otrzymywanie wiadomości e-mail z powiadomieniami'
	}, {
		type: 'notice',
		name: 'Korzystając z formularza, akceptujesz warunki użytkowania'
	}, {
		type: 'button',
		name: 'Zapisz'
	}, {
		type: 'button',
		name: 'Wyślij'
	}];

})();
