(function ($) {
    $.fn.contactForm = function (options) {
        var opts = $.extend({
        }, options);

        $(this).each(function () {

            var title = $(this).attr('title'), name = $(this).attr('id');

            $('<a href="" id="open-'+name+'" class="openContactForm">'+title+'</a>').insertBefore($(this));

            $(':submit', $(this)).button();

            $(this).dialog({
                autoOpen: false,
                modal: true,
                height: 400, width: 480,
                close: function () {
                    $('#'+name)[0].reset();
                    $('#'+name).find('ul.errors').remove();
                }
            });

        });

        $('.openContactForm').click(function (e) {
            e.preventDefault();

            $('#'+$(this).attr('id').substr(5)).dialog('open');
        });

        $(this).submit(function (e) {
            e.preventDefault();

            var id = this.id, submit = 'submit' + id;

            $.ajax({
                url: window.location.pathname, //'/projektanci-wnetrz.html',
                type: "POST",
                data: $('#'+id).serialize(),
                beforeSend: function () {
                    $(':submit', '#'+id).replaceWith('<img src="/images/develo/ajax.gif" alt"proszę czekać" class="loading" />');
                },
                success: function(data, textStatus, XMLHttpRequest) {
                    var $form = $(data).find('#'+id);

                    if ($form.size()) {
                        $('#'+id).html($form.html());

                        $(':submit', '#'+id).button();

                        return;
                    }

                    var $info = $(data).find('h2.contactMsg');

                    $('#'+id).dialog('close');

                    $('<div>'+$info.html()+'</div>').appendTo('body').dialog({
                        resizable: false,
                        height:140,
                        modal: true,
                        buttons: {
                            'Zamknij': function() {
                                $(this).dialog('close');
                            }
                        }
                    });
                }
            });
        });

    }
})(jQuery);


$(function () {
    $('form.contactForm.ajax').contactForm();
});

