/**
 * @author      Łukasz Kazimierz Bandzarewicz <lukasz.bandzarewicz@bluepaprica.com>
 * @version     0.1
 * @copyright   Copyright (C) 2007 Agencja Interaktywna Blue Paprica
 * 					  			   Maciej Pałubicki. All rights reserved.
 */
$(document).ready(function() {
	// wait for the DOM to be loaded

    // prepare Options Object
    var options = {

    	// dataType: 'json',

        beforeSubmit: function() {
        	$('#submit_button').attr('disabled', 'disabled');
        },

        success: function(response) {
        	// handle json response

        	// data = eval(response);

        	data = '';
        	try {
        		data = response.parseJSON();
        	}
        	catch (err) {
        		alert(response);
        		$('#submit_button').attr('disabled', '');
        	}

            if (data.success) {
            	// success

				// clear all error messages
				$('.errors').hide('slow');
				$('.note').hide('slow');
				$('.note').empty();
				$('label').removeClass('error');

            	blueFormOnSuccess(data);
            }
            else {
            	// server side validation errors

				if (data.exception) {		// if exception occurs
					alert(data.exception);
				}
				else {

					if (!$('.errors :hidden').length) {							// if error message is not visible
						$('.errors').show('slow');
					}

					$('.note').each(function() {								// for each notes
						var p = $('#' + this.id);								// get note
						var field = this.id.substring('error_'.length);			// get field name
						var messages = data.messages[field];					// get messages assined to the field
						if (messages) {											// if field has massages
							$('label[@for='+field+']').addClass('error');		// hightlight field label

							var text = '';
							var text2 = ''; // Opera and IE6 hack

							// show the values stored
							for (var key in messages) {

								if (key == 'toJSONString') continue;

								text += messages[key] + '<br/>';
								text2 += messages[key];
							}

//							for (var i = 0; i < messages.length; i++) {			// assembly messages
//								text += messages[i] + '<br/>';
//								text2 += messages[i];
//							}

							if (p.text() != text2) {							// if messages has been changed
								p.hide();
							}

							p.html(text);										// append the message
							p.show('slow');										// show the message

						}
						else {													// if field pass the validation
							$('label[@for='+field+']').removeClass('error');	// remove label hightligh
							p.hide('slow');
							p.empty();											// hide error messages
						}
					});
				}

            }

            $('#submit_button').attr('disabled', '');
        }

    };

    // pass options to ajaxForm
    $('.blueForm').ajaxForm(options);

});
