/**
 * 
 */
 

(function($, window) {
	var fieldCounter = 0; 
	
	$.fn.closest = function(sel) {
		var elm = $(this);
		do {
			elm = elm.parent();
		} while(!elm.is(sel) && !elm.is('body'));
		
		if(elm.is('body')) {
			return $([]);
		}
		return elm;
	};
	
	function getLabel(entity) {
		var elm = $(entity).closest('.form-field').prev('.form-label');
		if(elm.length) {
			return $.trim(elm.text());
		} else {
			elm = $(entity).closest('.form-entry').find('h2');
			if(elm.length) {
				return $.trim(elm.text());
			} else {
				elm = $(entity).closest('.form-field').find('.form-label').eq(0);
				if(elm.length) {
					return $.trim(elm.text());
				}
			}
		}
		
		return '';
	}
	
	
	$(function() {
		$(document.forms).each(function(i, form) {
			$(form).find('input, select, textarea').each(function(j, entity) {
				var label;
				fieldCounter++;
				if(entity.type === 'hidden') {
					return;
				}
				if(entity.id) {
					label = $('label[for="'+entity.id+'"]').text();
					switch(entity.nodeName) {
						case 'SELECT':
							$(entity).attr({
								wt_name: $.trim(label)
							}).find('option').each(function(k, opt) {
								$(opt).attr({
									wt_value: $(opt).text()
								});
							});
							break;
						case 'TEXTAREA':
							$(entity).attr({
								wt_name: $.trim(label)
							})
							break;
						case 'INPUT':
							switch(entity.type) {
								case 'text':
									$(entity).attr({
										wt_name: $.trim(label)
									});
									break;
								case 'checkbox':
									
									$(entity).attr({
										wt_value: $.trim(label),
										wt_name: $.trim(getLabel(entity))
									});
									break;
								case 'radio':
									if($(entity).closest('td').length) {
										var td = $(entity).closest('td');
										var tr = td.parent();
										var idx = $('td', tr).index(td[0]);
										var th = tr.closest('table').find('tr:first').find('th').eq(idx);
										
										$(entity).attr({
											wt_name: $.trim(label),
											wt_value: $.trim(th.find('label').text())
										});
									} else {
										$(entity).attr({
											wt_value: $.trim(label),
											wt_name: $.trim(getLabel(entity))
										});
									}
									break;
								case 'file':
									$(entity).attr({
										wt_name: $.trim(label.replace(/\s/g, " ").replace(/ +/g, " "))
									});
									break;
								default: 
									// like password for example
									break;
							}
							break
					}
				}
			});
		});
	});
}(jQuery, window));

