$(function() {

	/**
	 * Aktuellen Hash abholen.
	 */ 
	$.ajax({
		url: '/?module=captcha_image&gethash=' + last_formname + '&r=' + (1 + parseInt(Math.random() * 10000)),
		method: 'GET',
		dataType: 'text',
		success: function(hash) {
			if(hash == 'unknown formname') {
				return false;
			}
			
			var captcha_image = $('.captcha_image_' + last_formname);
		
			// Formular aktualisieren
			$('.captcha_hash', captcha_image.parent()).val(hash);
			
			var inputField = $('input.result', captcha_image.parent());
			var newInputName = inputField.attr('name').replace(/optical_captcha_\[HASH\]/, 'optical_captcha_'  + hash);
			inputField.attr('name', newInputName);
			inputField.attr('id', newInputName);
		
			// Bild aktualisieren
			var image_tag = captcha_image.html();
			image_tag = image_tag.replace(/hash=\[HASH\]/, 'hash=' + hash);
			$('img', captcha_image).replaceWith(image_tag);				
		}
	});	
	
	$('.reload_captcha').bind('click', function() {
		
		var captcha_image = $('.captcha_image', $(this).parent());
		
		/**
		 * Captcha Reloaden
		 */
		$.ajax({
			url: '/?module=captcha_image&reload=1&hash=' + $('.captcha_hash', captcha_image.parent()).val() + '&r=' + (1 + parseInt(Math.random() * 10000)),
			method: 'GET',
			dataType: 'text',
			success: function(newHash) {
			
				if(newHash == 'unknown hash') {
					return false;
				}
			
				// Formular aktualisieren
				$('.captcha_hash', captcha_image.parent()).val(newHash);
				
				var inputField = $('input.result', captcha_image.parent());
				var newInputName = inputField.attr('name').replace(/optical_captcha_[a-f0-9]+/, 'optical_captcha_'  + newHash);
				inputField.attr('id', newInputName);
				inputField.attr('name', newInputName);
			
				// Bild aktualisieren
				var image_tag = captcha_image.html();
				image_tag = image_tag.replace(/hash=[a-f0-9]+/, 'hash=' + newHash);
				$('img', captcha_image).replaceWith(image_tag);
			}
		});

		
	});		
});
