$(document).ready(function() {
	
	try{ // dlaczego zwykłe undefined nie działa?
		if (wysiwygFields != undefined) {
			for (var i in wysiwygFields) {
				//CKEDITOR.replace(wysiwygFields[i]);
				$('#'+wysiwygFields[i]).ckeditor();
			}
			
			$('#ajax-form').submit(function() {
				for (var i in wysiwygFields) {
					//eval('var ins = CKEDITOR.instances.'+wysiwygFields[i]+';');
					//$('#'+wysiwygFields[i]).val(ins.getData());
					var ins = $('#'+wysiwygFields[i]).ckeditorGet();
					ins.updateElement();
				}
				return true;
			});
		}
	} catch(e) {}
	
	var fieldsPrefix = 'f_';
	$('#ajax').val('1');
	
	$('#ajax-form').ajaxForm({
		dataType: 'xml',
		
		beforeSubmit: function() {
			$('#ajax-form input[type=submit]').attr('disabled', 'disabled')
				.after('<span class="submit-loading" />');
		},
		
		success: function(responseXML) { 
			//alert($(responseXML).text());
			
			var type = $('type', responseXML).text();
			
			if (type == 'errors') {
				var errors = new Array();
				
				$('error', responseXML).each(function (i) {
					errors[$(this).attr('field')] = '<div class="error">' + $(this).text() + '</div>';
				});
				
				// przesunięcie do pierwszego
				var first = undefined;
				
				$('*[id^=error_'+fieldsPrefix+']').each(function (i) {
					var el = $(this);
					var fieldID = el.attr('id');
					fieldID = fieldID.substr(('error_'+fieldsPrefix).length, fieldID.length);
					var input = $('#'+ fieldsPrefix + fieldID);
					
					if (errors[fieldID] != undefined) {
						el.css('opacity', 0);
						el.html(errors[fieldID]);
						el.animate({opacity:1}, 1000);
						input.addClass('error-field');
						
						if (first == undefined) {
							first = input;
						}
					} else {
						el.fadeOut('normal', function(){
							el.html('');
							el.fadeIn();
						});
						input.removeClass('error-field');
					}
				});
				
				$('body').scrollTop(first.offset().top - 20);
				
			} else if (type == 'success') {
				if ($('redirect', responseXML).text() == 'true') {
					document.location = $('url', responseXML).text();
				} else {
					$('#ajax-form').fadeOut('normal', function() {
						$(this).html('<div class="msg-ok">' + $('message', responseXML).text() + '</div>').fadeIn('normal');
					});
				}
			} else if (type == 'info') {
				alert($('message', responseXML).text());
			}
			$('#ajax-form input[type=submit]').removeAttr('disabled');
			$('#ajax-form .submit-loading').remove();
		},
		
		error: function(x, e) {
			if (x.status==0) {
				alert(i18n('error 0'));
			} else if (x.status==404) {
				alert(i18n('error 404'));
			} else if (x.status==500) {
				alert(i18n('error 500'));
			} else if (e=='parsererror') {
				alert(i18n('error parsererror'));
			} else if (e=='timeout') {
				alert(i18n('error timeout'));
			} else {
				alert(i18n('error unknown'));
			}
			$('#ajax-form input[type=submit]').removeAttr('disabled');
			$('#ajax-form .submit-loading').remove();
		}
	});
});

