/**
 * jQuery Form Builder Plugin
 * Copyright (c) 2009 Mike Botsko, Botsko.net LLC (http://www.botsko.net)
 * http://www.botsko.net/blog/2009/04/jquery-form-builder-plugin/
 * Originally designed for AspenMSM, a CMS product from Trellis Development
 * Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * Copyright notice and license must remain intact for legal use
 *
 * Forked by AppThemes on 09/09/2011
 */
(function ($) {

	$.fn.formbuilder = function (options) {

		var frmb_id = 'frmb-' + $('ul[id^=frmb-]').length++;
		return this.each(function() {
			var ul_obj = $(this).append('<ul id="' + frmb_id + '" class="frmb"></ul>').find('ul');
			var field = '';
			var field_type = '';
			var last_id = 1;
			var help;
			// Add a unique class to the current element
			$(ul_obj).addClass(frmb_id);

			var appValidate = function(e) {
				$('label.error').remove();
				$('.frmb input[type=text]').each(function() {
					var valid = true;
					$(this).css({backgroundColor:'#fff'});
					if ( $(this).val() == '' ) {
						$(this).css({backgroundColor:'#ffdada'});
						$(this).parent().append('<label for="'+ $(this).attr('id') +'" class="error">'+ validateL10n.required +'</label>');
						valid = false;
					}
					if ( ! valid ) {
						e.preventDefault();
					}
				});
			};


			// Create form control select box and add into the editor
			$(function() {

				body  = '<a href="#" data-type="input_text" class="button">' + l10n.text + '</a>';
				body += '<a href="#" data-type="textarea" class="button">' + l10n.textarea + '</a>';
				body += '<a href="#" data-type="checkbox" class="button">' + l10n.checkboxes + '</a>';
				body += '<a href="#" data-type="radio" class="button">' + l10n.radio + '</a>';
				body += '<a href="#" data-type="select" class="button">' + l10n.select + '</a>';
				body += '<a href="#" data-type="file" class="button">' + l10n.file + '</a>';

				var box_id = frmb_id + '-control-box';
				
				var box_content = '<div class="toolbar">';

				// only show toggle link when we've got fields
				if (last_id > 1 )
					box_content += '<a href="#" id="toggle-all">' + l10n.collapse_all + '</a>';

				box_content += '<div id="' + box_id + '"  class="button-wrap">' + body + '</div>';
				box_content += '</div><!-- .toolbar -->';

				$(ul_obj).before(box_content);

				$('#post').submit(function(e) {
					$('#va_form').val( $(ul_obj).serializeFormList({ prepend: 'va_form' }) );
					$('.frmb input[type=text]').on('input focusout', function(e) {appValidate(e);});
					appValidate(e);
				});

				$('.button-wrap > .button' ).click(function(e) {
					appendNewField( $(this).data('type') );
					$(this).blur();
					
					frm = '#frm-' + (last_id - 1) + '-item';

					// fade in new field with green background color
					$(frm).css( {backgroundColor:'#ceb'} ).fadeIn(300, function() {
						$(this).animate({backgroundColor: '#fff'}, 1000);
						$(this).find('.frm-group input:text').first().focus();
					});

					// This solves the scrollTo dependency
					$('html, body').animate({
						scrollTop: $(frm).offset().top
					}, 300);

					e.preventDefault();
				});

			});



			// main function to build each form field group
			var appendNewField = function(type, values, options, required, field_id) {

				id = last_id;
				if (typeof (values) === 'undefined')
					values = '';

				q = '';

				if (typeof (options) !== 'undefined') {
					switch (type) {
						case 'checkbox':
						case 'radio':
						case 'select':
							q = options[0];
						break;
						default:
							q = values;
						break;
					}
				}

				field = '<div class="frm-group">';
				field += '<label>' + l10n.label + '</label>';
				field += '<input type="text" name="title" value="' + q + '" data-field-id="' + field_id + '" />'
				field += '</div><!-- .frm-group -->';
				field += '<div class="frm-group">';


				// some fields have extra elements
				switch (type) {
					case 'input_text':
						appendTitle = l10n.text;
						break;
					case 'textarea':
						appendTitle = l10n.textarea;
						break;
					case 'checkbox':
						appendCheckboxGroup(values);
						appendTitle = l10n.checkbox_group;
						break;
					case 'radio':
						appendRadioGroup(values);
						appendTitle = l10n.radio_group;
						break;
					case 'select':
						appendSelectList(values, options);
						appendTitle = l10n.select;
						break;
					case 'file':
						appendFileUpload(values, options);
						appendTitle = l10n.file;
						break;
				}

				field += '</div><!-- .frm-group -->';
				help = '';

				// add the new field
				appendFieldLi(type, appendTitle, field, required, help);
			}


			// input type="file"
			var appendFileUpload = function(values, options) {

				if (typeof (options) === 'undefined')
					options = 'pdf';
	
				field += '<label class="options">' + l10n.file_extensions + '</label>';
				field += '<div class="fields">';
				field += '<input name="file-upload-ext-' + id + '" type="text" value="' + options + '" />';
				field += '<div class="field-tip">' + l10n.file_tip; + '</div>';
				field += '</div><!-- .fields -->';
			};


			// adds a checkbox element
			var appendCheckboxGroup = function(values) {

				field += '<label class="options">' + l10n.select_options + '</label>';
				field += '<div class="fields">';
				if (typeof (values) === 'object') {
					for (i = 0; i < values.length; i++)
						field += checkboxFieldHtml(values[i]);
				} else {
					field += checkboxFieldHtml('');
				}
				field += '</div><!-- .fields -->';
			};


			// Checkbox field html, since there may be multiple
			var checkboxFieldHtml = function(values) {
				var checked = false;
				var value = '';

				if (typeof (values) === 'object') {
					value = values[0];
					checked = ( values[1] === 'false' || values[1] === 'undefined' ) ? false : true;
				}
				field = '';
				field += '<div class="option-row">';
				field += '<input type="checkbox" tabindex="-1"' + (checked ? ' checked="checked"' : '') + ' />';
				field += '<input type="text" value="' + value + '" />';
				field += '<a href="#" class="add add_ck" tabindex="-1"><span class="dashicons dashicons-plus"></span></a>';
				field += '<a href="#" class="remove" tabindex="-1"><span class="dashicons dashicons-no"></span></a>';
				field += '</div>';
				return field;
			};


			// adds a radio element
			var appendRadioGroup = function(values) {

				field += '<label class="options">' + l10n.select_options + '</label>';
				field += '<div class="fields">';
				if (typeof (values) === 'object') {
					for (i = 0; i < values.length; i++)
						field += radioFieldHtml(values[i], 'frm-' + last_id + '-fld');
				} else {
					field += radioFieldHtml('', 'frm-' + last_id + '-fld');
				}
				field += '</div><!-- .fields -->';
			};


			// radio field html, since there may be multiple
			var radioFieldHtml = function(values, name) {
				var checked = false;
				var value = '';
				if (typeof (values) === 'object') {
					value = values[0];
					checked = ( values[1] === 'false' || values[1] === 'undefined' ) ? false : true;
				}
				field = '';
				field += '<div class="option-row">';
				field += '<input type="radio" tabindex="-1"' + (checked ? ' checked="checked"' : '') + ' name="radio_' + name + '" />';
				field += '<input type="text" value="' + value + '" />';
				field += '<a href="#" class="add add_rd" tabindex="-1"><span class="dashicons dashicons-plus"></span></a>';
				field += '<a href="#" class="remove" tabindex="-1"><span class="dashicons dashicons-no"></span></a>';
				field += '</div>';
				return field;
			};


			// adds a select/option element
			var appendSelectList = function(values, options) {
				var multiple = false;

				if (typeof (options) === 'object')
					multiple = options[1] === 'true' ? true : false;

				field += '<label class="options">' + l10n.select_options + '</label>';
				field += '<div class="fields">';
				if (typeof (values) === 'object') {
					for (i = 0; i < values.length; i++) {
						field += selectFieldHtml(values[i], multiple);
					}
				} else {
					field += selectFieldHtml('', multiple);
				}
			};


			// Select field html, since there may be multiple
			var selectFieldHtml = function(values, multiple) {
				if (multiple)
					return checkboxFieldHtml(values);
				else
					return radioFieldHtml(values);
			};


			// Appends the new field markup to the editor
			var appendFieldLi = function(type, title, field_html, required, help) {
				required = required === 'checked' ? true : false;

				li  = '<li id="frm-' + last_id + '-item" class="postbox" data-field-type="' + type + '">';
				li += '<div class="handlediv"><br></div>';	
				li += '<h3>' + title + '</h3>';
				li += '<div class="frm-holder">';
				li += '<div class="frm-elements">';
				li += '<div class="frm-group">';
				li += '<label>' + l10n.required + '</label>';
				li += '<input class="required" type="checkbox" value="1" name="required-' + last_id + '" id="required-' + last_id + '"' + (required ? ' checked="checked"' : '') + ' />';
				li += '</div><!-- .frm-group -->';
				li += field;
				li += '<a href="#" class="delete" tabindex="-1" title="' + l10n.remove + '"><span class="dashicons dashicons-dismiss"></span></a>';
				li += '</div><!-- .frm-elements -->';
				li += '</div><!-- .frm-holder -->';
				li += '</li>';
				$(ul_obj).append(li);
				$('#frm-' + last_id + '-item').hide();
				$('#frm-' + last_id + '-item').show();
				last_id++;
			};


			// handle field delete rows
			$('.postbox').on('click', 'a.remove', function(e) {
				var i = $(this).closest('.fields');
				// must have at least one field
				if ( i.children().length <= 1 )
					return false;
				$(this).parent('div').remove();
				e.preventDefault();
			});


			// toggle all boxes
			$('#app-form-builder-div').on('click', '#toggle-all', function(e) {
				$(this).text($(this).text() === l10n.collapse_all ? l10n.expand_all : l10n.collapse_all);
				$('div.frm-holder').toggle();
				$('li.postbox').toggleClass('closed');
				e.preventDefault();
			});


			// handle field display/hide
			$('.frmb').on('click', '.handlediv', function(e) {
				$(this).toggleClass('closed');
				$(this).siblings('.frm-holder').toggle();
				e.preventDefault();
			});


			// handle delete field
			$('.frmb').on('click', 'a.delete', function(e) {
				if (confirm($(this).attr('title'))) {
					$(this).closest('li').css( {backgroundColor:'#FFAAAA'} ).fadeOut(350, function(){
						$(this).remove();
					});
				}
				e.preventDefault();
			});


			// add new checkbox field
			$('.frmb').on('click', '.add_ck', function(e) {
				$(this).parent().after(checkboxFieldHtml());
				e.preventDefault();
			});


			// add new select option field
			$('.frmb').on('click', '.add_opt', function(e) {
				$(this).parent().after(selectFieldHtml('', false));
				e.preventDefault();
			});


			// add new radio field
			$('.frmb').on('click', '.add_rd', function(e) {
				$(this).parent().after(radioFieldHtml(false, $(this).parents('.frm-holder').attr('id')));
				e.preventDefault();
			});


			// Json parser to build the form builder
			var fromJson = function(json) {
					var values = '';
					var options = false;
					var required = false;
					// Parse json
					$(json).each(function () {
						// checkbox type
						if (this.cssClass === 'checkbox') {
							options = [this.title];
							values = [];
							$.each(this.values, function() {
								values.push([this.value, this.baseline]);
							});
						}
						// radio type
						else if (this.cssClass === 'radio') {
							options = [this.title];
							values = [];
							$.each(this.values, function() {
								values.push([this.value, this.baseline]);
							});
						}
						// select type
						else if (this.cssClass === 'select') {
							options = [this.title, this.multiple];
							values = [];
							$.each(this.values, function() {
								values.push([this.value, this.baseline]);
							});
						}
						// file type
						else if (this.cssClass === 'file') {
							options = [this.extensions];
							values = [this.values];
						}
						else {
							values = [this.values];
						}
						appendNewField(this.cssClass, values, options, this.required, this.id);
					});
				};

				fromJson( jQuery.parseJSON( $('#va_form').val() ) );
		});
	};
})(jQuery);


/**
 * jQuery Form Builder List Serialization Plugin
 * Copyright (c) 2009 Mike Botsko, Botsko.net LLC (http://www.botsko.net)
 * Originally designed for AspenMSM, a CMS product from Trellis Development
 * Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * Copyright notice and license must remain intact for legal use
 * Modified from the serialize list plugin
 * http://www.botsko.net/blog/2009/01/jquery_serialize_list_plugin/
 */
(function($) {
	$.fn.serializeFormList = function(options) {
		// Extend the configuration options with user-provided
		var defaults = {
			prepend: 'ul',
			is_child: false,
			attributes: ['data-field-type']
		};
		var opts = $.extend(defaults, options);
		if (!opts.is_child) {
			opts.prepend = '&' + opts.prepend;
		}
		var serialStr = '';
		// Begin the core plugin
		this.each(function() {
			var ul_obj = this;
			var li_count = 0;
			var c = 1;
			$(this).children().each(function() {
				for (att = 0; att < opts.attributes.length; att++) {
					var key = (opts.attributes[att] === 'data-field-type' ? 'cssClass' : opts.attributes[att]);
					serialStr += opts.prepend + '[' + li_count + '][' + key + ']=' + encodeURIComponent($(this).attr(opts.attributes[att]));
					// append the form field values
					if (opts.attributes[att] === 'data-field-type') {
						serialStr += opts.prepend + '[' + li_count + '][id]=' + encodeURIComponent($('#' + $(this).attr('id') + ' input[type=text]').data('field-id'));
						serialStr += opts.prepend + '[' + li_count + '][required]=' + encodeURIComponent($('#' + $(this).attr('id') + ' input.required').attr('checked'));
						switch ($(this).attr(opts.attributes[att])) {
						case 'input_text':
							serialStr += opts.prepend + '[' + li_count + '][values]=' + encodeURIComponent($('#' + $(this).attr('id') + ' input[type=text]').val());
							break;
						case 'textarea':
							serialStr += opts.prepend + '[' + li_count + '][values]=' + encodeURIComponent($('#' + $(this).attr('id') + ' input[type=text]').val());
							break;
						case 'file':
							serialStr += opts.prepend + '[' + li_count + '][values]=' + encodeURIComponent($('#' + $(this).attr('id') + ' input[type=text]').val());
							serialStr += opts.prepend + '[' + li_count + '][extensions]=' + encodeURIComponent($('input[name^=file-upload-ext]', this).val());
							break;
						case 'checkbox':
							c = 1;
							$('#' + $(this).attr('id') + ' input[type=text]').each(function () {
								if ($(this).attr('name') === 'title') {
									serialStr += opts.prepend + '[' + li_count + '][title]=' + encodeURIComponent($(this).val());
								}
								else {
									serialStr += opts.prepend + '[' + li_count + '][values][' + c + '][value]=' + encodeURIComponent($(this).val());
									serialStr += opts.prepend + '[' + li_count + '][values][' + c + '][baseline]=' + $(this).prev().attr('checked');
								}
								c++;
							});
							break;
						case 'radio':
							c = 1;
							$('#' + $(this).attr('id') + ' input[type=text]').each(function () {
								if ($(this).attr('name') === 'title') {
									serialStr += opts.prepend + '[' + li_count + '][title]=' + encodeURIComponent($(this).val());
								}
								else {
									serialStr += opts.prepend + '[' + li_count + '][values][' + c + '][value]=' + encodeURIComponent($(this).val());
									serialStr += opts.prepend + '[' + li_count + '][values][' + c + '][baseline]=' + $(this).prev().attr('checked');
								}
								c++;
							});
							break;
						case 'select':
							c = 1;
							serialStr += opts.prepend + '[' + li_count + '][multiple]=' + $('#' + $(this).attr('id') + ' input[name=multiple]').attr('checked');
							$('#' + $(this).attr('id') + ' input[type=text]').each(function () {
								if ($(this).attr('name') === 'title') {
									serialStr += opts.prepend + '[' + li_count + '][title]=' + encodeURIComponent($(this).val());
								}
								else {
									serialStr += opts.prepend + '[' + li_count + '][values][' + c + '][value]=' + encodeURIComponent($(this).val());
									serialStr += opts.prepend + '[' + li_count + '][values][' + c + '][baseline]=' + $(this).prev().attr('checked');
								}
								c++;
							});
							break;
						}
					}
				}
				li_count++;
			});
		});
		return (serialStr);
	};
})(jQuery);
