/*
giobi.com 2011-04-ilye
*/
(function($) {
	$.fn.validate = function(options) {
		debug(this);
		//var opts = $.extend({}, $.fn.share.defaults, options);

		$.extend($.ui.dialog.prototype.options, {
			modal: true,
			resizable: false,
			draggable: false,
			buttons: {
				OK: function() {
					$( this ).dialog( "close" );
				}
			}
		});
		
		return this.each(function() {
			t = $(this);
			
			t.find('.required').siblings('label').append(' <em>*</em>');
			
			$('form .error').live('change', function() {
				$(this).removeClass('error');
			});
			
			//t.find('input[type="submit"]').click(function() { $(this).replaceWith('<img src="/img/loader.gif" />'); });

			t.submit(function() {

				valid = true;
				t.find('.required').each(function() {
					$t = $(this);
					val = $(this).val();
					if (val == '') {
						$t.addClass('error');
						valid = false;
					}
				});
				
				if (!valid) {
					//alert(t.find('.error-required').html());
					t.find('.error-required').clone().dialog({modal: true});
				}
				
				if (valid && t.find('input.email').length) {
					$mail = $('.email');
					if (!validmail($mail.val())) {
						valid = false;
						$mail.addClass('error');
						t.find('.error-email').dialog({modal: true});
					}
				}
		
				if (valid && t.find('input.privacy').length) {
					$p = t.find('input.privacy');
					if (!$p.attr('checked')) {
						valid = false;
						$p.parent().addClass('error');
						t.find('.error-privacy').clone().dialog({modal: true});
					}
				}
				
				if (valid && t.find('input.password2').length) {
					if (t.find('.password2').val() != t.find('input[name="password"]').val()) {
						valid = false;
						t.find('.error-password').clone().dialog({modal: true});
					}
				}
		
				if (valid) {
					//t.append('<img src="/img/loader.gif" />');
					t.children().fadeOut();
					t.find('input[type="submit"]').button('disable');
					t.find('.success-sent').clone().dialog();
					$.post(t.attr('action'), t.serialize(), function(data) {
						//t.find('.success-valid').fadeIn().siblings().hide();
						//t.append('<div class="alert">' + data + '</div>').find('.alert').dialog();
						t.append(data);
					});
				}
				
				return false;
			});
		});


	};

	$.fn.validmail = function(options) {
		var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
		return pattern.test( $(this).html() );
	};
	
	function debug($obj) {
		if (window.console && window.console.log) window.console.log('[validate] count: ' + $obj.size());
	};	
	/*
	$.fn.share.defaults = {
		fb: '<a href="fb">Facebook</a>',
		email: '<a href="mailto:insert address"></a>'
	};
	*/
})(jQuery);

$('form.validate').validate();
