jQuery(function($) {
	$('.dv').defaultValue();
	$('form').submit(function() {
		$(this).find('.dv.empty').val('');
	});
	$('.move.to[rel]').each(function() {
		$(this).prependTo( $(this).attr('rel') );
		$(this).removeClass('move to');
	});
	$('a.video[href]').video();
	$('.multiplicable[rel]').each(function() {
		var $self = $(this);
		var $count = $( $(this).attr('rel') );
		$count.change(function() {
			var n = parseInt( $(this).val() ); if (isNaN(n)) return;

			var $instances = $self.find('.instance');
			var k = n - 1; if (k < 0) k = 0;
			var $for_removal = $instances.eq(k).nextAll().andSelf();

/*			var backup = $self.data('backup') || {};
			$for_removal.find(':input').each(function() {
				backup[$(this).attr('name')] = $(this).val();
			});
			$self.data('backup', backup);
*/

			$for_removal.remove();

			var $tpl = $self.find('[rel=template]'), $nu;
			if (n > $instances.size()) for (var i = $instances.size(); i < (n - 1); i++) {
				$nu = $tpl.clone();
				$nu.removeAttr('rel');
				$nu.addClass('instance').find(':input').each(function() {
					$(this).val('');
					$(this).attr('id', $(this).attr('id') + '_' + i );
/*					if (undefined !== backup[$(this).attr('name')])
						$(this).val( backup[$(this).attr('name')] ); */
				});
				$nu.find('label[for]').each(function() {
					$(this).attr('for', $(this).attr('for') + '_' + i );
				});
				$nu.find('span.error').remove();
				$nu.insertAfter( $tpl );
			}
		}).change();
	});
	$('#financial-forecasts').each(function() {
		var $self = $(this);
		$self.find('input').change(function() {
			$self.find('tbody > tr').each(function() {
				var elems = $(this).find('input.numeric');
//				console.log(elems);
				var $r = $(this).find('.result .const');
				var r = parseInt(elems.eq(0).val()) - parseInt(elems.eq(1).val());
//				console.log(r);
				if (isNaN(r)) r = '&mdash;';
				$r.html( r );
			});
		});
	});
	$.nyroModalSettings({minHeight: 100});
	$('.modal').nyroModal();
	var h = window.location.hash;
	if (h && h.length > 1 && $(h).filter(':not(:visible)').size())
		$( $(h).attr('rel') ).click();
});
