$(function() {
		
		var name = $("#offer_name"),
			phone = $("#offer_phone"),
			email = $("#offer_email"),
			typ = $("#offer_typ"),
			pow = $("#offer_pow"),
			price = $("#offer_price"),
			city = $("#offer_city"),
			desc = $("#offer_desc"),
			allFields = $([]).add(name).add(phone).add(pow).add(price).add(city),
			tips = $("#validateTips");

		function updateTips(t) {
			tips.text(t).effect("highlight",{},1500);
		}

		function checkLength(o,n,min,max) {

			if ( o.val().length > max || o.val().length < min ) {
				o.addClass('ui-state-error');
				updateTips("Dopuszczalna liczba znaków w przedzialne: "+min+" - "+max+".");
				return false;
			} else {
				return true;
			}

		}

		function checkRegexp(o,regexp,n) {

			if ( !( regexp.test( o.val() ) ) ) {
				o.addClass('ui-state-error');
				updateTips(n);
				return false;
			} else {
				return true;
			}

		}
		
		$("#dialog").dialog({
			bgiframe: true,
			autoOpen: false,
			width: 500,
			height: 425,
			modal: true,
			buttons: {
				'Wyślij': function() {
					var bValid = true;
					allFields.removeClass('ui-state-error');

					bValid = bValid && checkLength(name,"imię i nazwisko",3,16);
					bValid = bValid && checkLength(phone,"telefon",8,16);
					bValid = bValid && checkLength(pow,"powierzchnia",1,16);
					bValid = bValid && checkLength(price,"cena",1,16);
					bValid = bValid && checkLength(city,"miasto",2,80);
					
					if (bValid) {
						formSend();
						$(this).dialog('close');
						$('#thanks_dialog').dialog('open');
					}
				},
				'Anuluj': function() {
					$(this).dialog('close');
				}
			},
			close: function() {
				allFields.val('').removeClass('ui-state-error');
			}
		});
		
		
		
		$('#dialog_link').click(
			function() { $('#dialog').dialog('open'); }
		).hover(
			function(){ $(this).addClass("ui-state-hover"); },
			function(){ $(this).removeClass("ui-state-hover"); }
		);

		
		function formSend() {
			$.ajax({
				type: "POST",
				url: "class/send_mail.php",
				data: "form_name=form_offer&name="+name.val()+"&email="+email.val()+"&phone="+phone.val()+"&typ="+typ.val()+"&pow="+pow.val()+"&price="+price.val()+"&city="+city.val()+"&desc="+desc.val(),
				async: false,
				
				success: function(msg){
					//
				}
			});
		};
		
		
		$("#thanks_dialog").dialog({
			bgiframe: true,
			modal: true,
			autoOpen: false,
			buttons: {
				Ok: function() {
					$(this).dialog('close');
				}
			}
		});
		
});