// Retrieve the initial data
function temporary() {
	attributesArray.length = 0;
	$('.attributes').each(function() {
		var attributesData = {},
			$selectType = $('.dataType').data().type;

		// Capture "attributes-body" within the input[type = "text"] val
		$(this).find('.attributes-body').find('input[type="text"]').each(function(i) {
			var $type = $(this).data().type;
			attributesData[$type] = $(this).val();
		});

		// Capture "attributes-body" within the input[type = "radio"] checked
		$(this).find('.attributes-body').find('input[type="radio"]').each(function(i) {
			var $type = $(this).data().type;
			attributesData[$type] = $(this).prop("checked");
		});

		// Capture "attributes-body" within the dataType selected
		$(this).find('.attributes-body').find('.dataType').children("option:selected").each(function () {
			attributesData[$selectType] = {};
			attributesData[$selectType].index = $(this).index();
			attributesData[$selectType].name = $(this).attr('ref');
			if($(this).attr('ref') == 'typeB' || $(this).attr('ref') == 'typeE' || $(this).attr('ref') == 'typeF') {
				attributesData[$selectType].option = [];
			}
		});

		// Capture "field-type" within the input[type = "text"] val
		$(this).find('.field-type').find('input[type="text"]').each(function(i) {
			var $type = $(this).data().type;
			if(!$type.match('option_lang')) {
				attributesData[$selectType][$type] = $(this).val();
			}
		});

		$(this).find('.field-type .add-target').find('.input-append').each(function() {
			var append = []
			$(this).children('input[type="text"]').each(function() {
				var val = $(this).val();
				append.push(val);
			});
			attributesData[$selectType].option.push(append);
		})

		// Capture "field-type" within the input[type = "checkbox"] checked
		$(this).find('.field-type').find('input[type="checkbox"]').each(function() {
			var $type = $(this).data().type;
			attributesData[$selectType][$type] = $(this).prop("checked");
		});

		// Capture "field-type" within the input[type = "radio"] checked
		$(this).find('.field-type').find('input[type="radio"]').each(function() {
			var $type = $(this).data().type;
			attributesData[$selectType][$type] = $(this).prop("checked");
		});

		// Capture "field-type" within the dataType selected
		$(this).find('.field-type').find('select').children("option:selected").each(function () {
			attributesData[$selectType].dateFormat = $(this).index();
		});

		attributesArray.push(attributesData);
	});
};

// Determine the Append input length
function inputAppendLength() {
	$('.add-target').each(function(i) {
		if($(this).children('.input-append:not(:hidden)').length == 1 || $(this).children('.input-append').length == 1) {
			$(this).children('.input-append').each(function() {
				if($(this).children('div').hasClass('tab-content')) {
					var btnLength = $(this).children('.btn').length;
					$(this).find('.btn').eq(btnLength-2).addClass('last');
					$(this).find('.remove-input').addClass('hide');
				} else {
					var mediumLength = $(this).children('.input-medium').length;
					$(this).children('.input-medium').eq(mediumLength-1).addClass('last');
					$(this).children('.remove-input').addClass('hide');
				}
			});
		} else {
			$(this).children('.input-append').each(function() {
				if($(this).children('div').hasClass('tab-content')) {
					$(this).find('.btn').removeClass('last');
					$(this).find('.remove-input').removeClass('hide');
				} else {
					$(this).children('.input-medium').removeClass('last');
					$(this).children('.remove-input').removeClass('hide');
				}
			});
		}
	});
};

// Role Attribute Template Data
function setData(l, type, ol) {
	var fields = $('#info').length ? "info[attribute_fields]" : $('#sub_role').length ? "sub_role[attribute_fields]" : "role[attribute_fields]",
		data = {
			_add_more:				["add_more_"			+l, fields+"["+l+"]["+type+"][add_more]"],
			_calendar:				["calendar_"			+l, fields+"["+l+"]["+type+"][calendar]"],
			_cross_lang:			["cross_lang_"			+l, fields+"["+l+"]["+type+"][cross_lang]"],
			_disabled:				["disabled_"			+l, fields+"["+l+"][disabled]"],
			_format:				["format_"				+l, fields+"["+l+"]["+type+"][format]"],
			_initial:				["initial_"				+l, fields+"["+l+"]["+type+"][initial]"],
			_is_range:				["is_range_"			+l, fields+"["+l+"]["+type+"][is_range]"],
			_key:					["key_"					+l, fields+"["+l+"][key]"],
			_markup:				fields+"["+l+"][markup]",
			_option_list:			["option_list_"+l+"_"+ol, fields+"["+l+"]["+type+"][option_list]["+ol+"]", "option_list_"+ol],
			_placeholder:			["placeholder_"			+l, fields+"["+l+"]["+type+"][placeholder]"],
			_title_translations:	["title_translations_"	+l, fields+"["+l+"][title_translations]"],
			_to_delete:				["to_delete_"			+l, fields+"["+l+"][to_delete]"],
			_to_search:				["to_search_"			+l, fields+"["+l+"][to_search]"],
			_to_show:				["to_show_"			    +l, fields+"["+l+"][to_show]"],
		};
	return data;
}

// Get Default Address Form
function getAddressForm(trigger, element, decide) {
	if(decide) {
		addressVal.length = addressArray.length = 0;
		var addressAllVal = [];
		var inputNameArray = [];
		trigger.closest('.input-append').find('.tab-pane').each(function() {
			var adderssText = $(this).children('input[type="text"]').val(),
				addersshidden = '',
				addressData = {},
				inputName = [];
			$(this).children('input:not(:first)').each(function(j) {
				var name = $(this).attr('name'),
					val = $(this).val();
				addersshidden += val;
				addressData[name] = val;
				inputName.push(name);
			});
			addressArray.push(addressData);
			addressAllVal.push(adderssText);
			inputNameArray.push(inputName);
			if(adderssText != addersshidden) {
				addressVal.push(false);
			} else {
				addressVal.push(true);
			}
		});
		element.find('.tab-pane').each(function(i) {
			$(this).find('textarea, input[type="text"]').each(function(j) {
				$(this).attr('name',inputNameArray[i][j]);
			});
			if(addressVal[i]) {
				$(this).find('textarea, input[type="text"]').each(function(j) {
					$(this).val(addressArray[i][$(this).attr('name')]);
				});
			} else {
				$(this).find('textarea').val(addressAllVal[i]);
				$(this).find('input[type="text"]').each(function(j) {
					$(this).val('');
				});
			}
		});
	};
	element.off('show');
};

// Return Address Form
function returnAddressForm(element, decide) {
	if(decide) {
		addressArray.length = 0;
		element.find('.tab-pane').each(function(i) {
			var addressData = {};
			$(this).find('textarea, input[type="text"]').each(function(j) {
				var name = $(this).attr('name'),
					val = $(this).val();
				addressData[name] = val;
			});
			addressArray.push(addressData);
		});
		$.map(addressInputId, function(n, i) {
			var v = '';
			$('#'+n).find('input[type="hidden"]').each(function() {
				$(this).val(addressArray[i][$(this).attr('name')]);
				v += addressArray[i][$(this).attr('name')]
			});
			$('#'+n).find('input[type="text"]').each(function() {
				$(this).val(v);
			});
		});
	};
	returnDecide = false;
};

$(function() {
	appendIndex = null;
	if($('#user-forms').length) {
		addressVal = [];
		addressArray = [];
		addressInputId = [];
		roleType = null;
		returnDecide = false;
		$('.attributes').each(function() {
			if($(this).find('.toggle-check').attr('value') == "true") {
				$(this).addClass('disabled').children('.attributes-body').hide();
			}
		});
		$('.returnDecide').on(clickEvent, function() {
			returnDecide = true;
		})
		$('#address-field').on('hidden', function () {
			$('.btn[data-toggle="modal"]').removeClass('active').blur();
			$(this).find('.nav-tabs > li').removeClass('active').eq(0).addClass('active');
			$(this).find('.tab-content > .tab-pane').removeClass('active in').eq(0).addClass('active in');
			$(this).on('show', getAddressForm(null, $(this), false));
			returnAddressForm($(this), returnDecide)
		});
		$('.control-group').delegate('.btn[data-toggle="modal"]', 'click', function() {
			var $trigger = $(this);
			addressInputId.length = 0;
			$(this).closest('.input-append').find('.tab-pane').each(function() {
				addressInputId.push($(this).attr('id'));
			});
			$('#address-field').on('show', getAddressForm($trigger, $('#address-field'), true));
		});
		$('#user-forms').delegate('.togglebox, .delete, .trigger, .remove-input', clickEvent, function(event) {
			if($(this).hasClass('togglebox')) {
				if($(this).hasClass('disable')) {
					$(this).find('.toggle-check')
						   .attr('value', 'false')
						   .closest('.attributes')
						   .removeClass('disabled')
						   .children('.attributes-body')
						   .fadeIn(300);
				} else {
					$(this).find('.toggle-check')
						   .attr('value', 'true')
						   .closest('.attributes')
						   .addClass('disabled')
						   .children('.attributes-body')
						   .fadeOut(300);
				}
				$(this).toggleClass('disable');
			};
			if($(this).hasClass('remove-input')) {
				$(this).closest('.input-append').fadeOut(300, function() {
					$(this).remove();
					inputAppendLength();
				});
			};
			if($(this).hasClass('trigger')) {
				appendIndex = $(this).closest('.controls').find('.input-append').length;
				nameNumber = $(this).closest('.controls').find('.input-append:eq(0)').find('input').eq(0).attr('name');
				nameNumber = nameNumber.match(/[^[\D\]]+(?=])/g)[0];
				roleType = $(this).data('roles')
				if($(this).hasClass('textInput')) {
					$("#template-text").tmpl().appendTo($(this).closest('.controls').find('.add-target'));
				} else if ($(this).hasClass('textLengInput')) {
					$("#template-text-language").tmpl().appendTo($(this).closest('.controls').find('.add-target'));
				} else if ($(this).hasClass('address')) {
					$("#template-address").tmpl().appendTo($(this).closest('.controls').find('.add-target'));
				} 
				inputAppendLength();
			};
			event.preventDefault();
		});
		inputAppendLength();
	} else {
		attributesArray = [];
		attributesHeaderLength = null;
		templateType = null;
		attributeIndex = null;
		if($('.add-target').length) {
			inputAppendLength();
		}
		if(!$('.attributes').length) {
			$('#attributes-area').addClass('clickHere');
		} else {
			temporary();
		};

		$('.add-attributes').on(clickEvent, function() {
			if($('#attributes-area').hasClass('clickHere')) {
				$('#attributes-area').removeClass('clickHere');
			};
		    attributesHeaderLength = $('.attributes:not(:hidden)').length+1;
		    attributesLength = $('#attributes-area .attributes').length;
		    $("#template-attributes").tmpl(setData(attributesLength, templateType, appendIndex)).appendTo( "#attributes-area" );
		    $('.toggle-check').togglebox();
		});



		$('.attributes.default').each(function(i) {
			$(this).children('.field-type').not('.default').hide();
			$(this).find('input[type="text"]').on('keyup', function() {
				$(this).trigger("checking");
			});
			$(this).find('input[type="radio"], input[type="checkbox"], select').change(function() {
				$(this).trigger("checking");
			});
			$(this).delegate('input[type="text"], input[type="radio"], input[type="checkbox"], select', 'checking', function(e) {
				var e = e.target.type,
					$data = $(this).data().type;
				switch(e) {
					case 'text':
						var val = $(this).val();
						if(!$(this).closest('.field-type').length) {
							$data = attributesArray[i][$data];
						} else if(!$(this).closest('.add-target').length) {
							$data = attributesArray[i].select[$data];
						} else {
							appendIndex = $(this).parent('.input-append').index()
							optionIndex = $(this).index()
							$data = attributesArray[i].select.option[appendIndex][optionIndex];
						}
						if(val != $data) {
							$(this).closest('.attributes').find('.reply').removeClass('hide');
						}
						break;
					case 'radio':
						var checked = $(this).prop("checked");
						$data = attributesArray[i][$data];
						if(checked != $data) {
							$(this).closest('.attributes').find('.reply').removeClass('hide');
						}
						break;
					case 'checkbox':
						var checked = $(this).prop("checked");
						$data = attributesArray[i].select[$data];
						if(checked != $data) {
							$(this).closest('.attributes').find('.reply').removeClass('hide');
						}
						break;
					case 'select-one':
						var ref,
							$data = attributesArray[i].select.name;
						$(this).children("option:selected").each(function() {
							ref = $(this).attr('ref');
						});
						if(ref != $data) {
							$(this).closest('.attributes').find('.reply').removeClass('hide');
						}
						break;
				};
			});
			$(this).delegate('.reply', clickEvent, function() {
				var $bodyText = $(this).parent('.attributes-header').siblings('.attributes-body').find('input[type="text"]'),
					$bodyRadio = $(this).parent('.attributes-header').siblings('.attributes-body').find('input[type="radio"]'),
					$bodySelected = $(this).parent('.attributes-header').siblings('.attributes-body').find('.dataType').children("option"),
					$fieldTypeO = $(this).parent('.attributes-header').siblings('.field-type.default'),
					$fieldTypeN = $(this).parent('.attributes-header').siblings('.field-type').not('.default');
				$bodyText.each(function() {
					var $type = $(this).data().type;
					$(this).val(attributesArray[i][$type]);
				});
				$bodyRadio.each(function() {
					var $type = $(this).data().type;
					$(this).prop("checked", attributesArray[i][$type])
				});
				$fieldTypeO.find('input[type="text"]').each(function() {
					var $type = $(this).data().type;
					if(!$type.match('option_lang')) {
						$(this).val(attributesArray[i].select[$type]);
					}
				});
				$fieldTypeO.find('.add-target').find('.input-append').each(function(k) {
					$(this).children('input[type="text"]').each(function(j) {
						$(this).val(attributesArray[i].select.option[k][j]);
						// var val = $(this).val();
						// append.push(val);
					});
				})
				$fieldTypeO.find('input[type="checkbox"], input[type="radio"]').each(function() {
					var $type = $(this).data().type;
					$(this).prop("checked", attributesArray[i].select[$type]);
				});
				$fieldTypeO.find('select').children("option").eq(attributesArray[i].select.dateFormat).prop('selected',true);
				$bodySelected.eq(attributesArray[i].select.index).prop('selected',true);
				$fieldTypeO.show();
				$fieldTypeN.empty().hide();
				$(this).addClass('hide')
				return false
			})
		});
		$('#attributes-area').delegate('.togglebox, .delete, .trigger, .remove-input', clickEvent, function(event) {
			if($(this).hasClass('togglebox')) {
				if($(this).hasClass('disable')) {
					$(this).find('.toggle-check')
						   .attr('value', 'false')
						   .closest('.attributes')
						   .removeClass('disabled')
						   .find('input, select')
						   .removeAttr('disabled')
						   .end('.attributes')
						   .find('.btn-group .btn')
						   .removeClass('disabled')
						   .end().find('.attribute_field_disabled').attr('value', 'false');
					if($(this).closest('.attributes').find('.dataType').children("option:selected").attr('ref')) {
						$(this).closest('.attributes').find('.field-type').addClass('in').find('.control-group').delay(150).fadeIn(300);
					}
				} else {
					$(this).find('.toggle-check')
						   .attr('value', 'true')
						   .closest('.attributes')
						   .addClass('disabled')
						   .find('.attributes-body input, .attributes-body select')
						   .attr({'disabled': 'disabled'})
						   .end('.attributes')
						   .find('.btn-group .btn')
						   .addClass('disabled')
						   .end().find('.attribute_field_disabled').attr('value', 'true')
						   .end().find('.field-type .control-group').fadeOut(300, function() {
						    	$(this).parent('.field-type').removeClass('in');
						   });
				}
				$(this).toggleClass('disable');
			};
			if($(this).hasClass('delete')) {
				$(this).closest('.attributes').fadeOut(300, function() {
					$('.attributes:not(:hidden)').each(function(i) {
						$(this).find('.attributes-header h4 span').text(i+1);
					});
					attributesHeaderLength = $('.attributes:not(:hidden)').length+1;
					if(!$('.attributes:not(:hidden)').length) {
						$('#attributes-area').addClass('clickHere');
					};
				}).find('.attribute_field_to_delete').attr('value', 'true');;
			};
			if($(this).hasClass('trigger')) {
				// appendIndex = $(this).closest('.controls').find('.input-append').length;
				appendIndex = $(this).closest('.controls').find('.input-append:last-child').children('input:first-child').attr('name');
				// appendIndex = appendIndex.split("][");
				// appendIndex = parseInt(appendIndex[appendIndex.length-2])+1;
				appendIndex = parseInt(appendIndex.match(/[^[\D\]]+(?=])/g)[1])+1;
				console.log(appendIndex)
				attributeIndex = $(this).closest('.attributes').index();
				templateType = $(this).closest('.attributes').find('.dataType').children("option:selected").attr('ref');
				$("#template-input-append").tmpl(setData(attributeIndex, templateType, appendIndex)).appendTo($(this).closest('.controls').find('.add-target'));
				inputAppendLength();
			};
			if($(this).hasClass('remove-input')) {
				$(this).parent('.input-append').fadeOut(300, function() {
					$(this).remove()
					inputAppendLength();
				});

			}
			event.preventDefault();
		});
		$('#attributes-area').delegate('.dataType', 'change', function() {
	        $(this).children("option:selected").each(function () {
	        	var target = $(this).closest('.attributes').find('.field-type').not('.default');
	    		attributeIndex = $(this).closest('.attributes').index();
	        	appendIndex = 0
	        	// $(this).closest('.attributes').find('.add-target').find('.input-append').length;
	        	if($(this).closest('.attributes').hasClass('default')){
	        		var i = $(this).closest('.attributes').index()
	        		if($(this).attr('ref') == attributesArray[i].select.name) {
	        			$(this).closest('.attributes').find('.field-type.default').show()
	        			target.empty().hide();
	        		} else {
	        			$(this).closest('.attributes').find('.field-type.default').hide()
			        	if($(this).attr('ref')) {
			        		templateType = $(this).attr('ref');
				        	target.removeAttr('class').addClass('field-type fade in ' + templateType).empty();
				        	$("#template-type").tmpl(setData(attributeIndex, templateType, appendIndex)).appendTo(target);
				        	if(templateType == 'typeB' || templateType == 'typeE' || templateType == 'typeF') {
				        		inputAppendLength();
				        	}
			        	} else {
			        		target.removeAttr('class').addClass('field-type fade')
			        		target.empty();
			        	};
			        	target.show();
	        		}
	        	} else {
		        	if($(this).attr('ref')) {
		        		templateType = $(this).attr('ref');
			        	target.removeAttr('class').addClass('field-type fade in ' + templateType).empty();
			        	$("#template-type").tmpl(setData(attributeIndex, templateType, appendIndex)).appendTo(target);
			        	if(templateType == 'typeB' || templateType == 'typeE' || templateType == 'typeF') {
			        		inputAppendLength();
			        	}
		        	} else {
		        		target.removeAttr('class').addClass('field-type fade')
		        		target.empty();
		        	};
	        	}
	        });
		});
	}
});