/**
 * AJAX Nette Framwork plugin for jQuery
 *
 * @copyright   Copyright (c) 2009 Jan Marek; a few adjustments by Martin Vseticka
 * @license     MIT
 * @link        http://nettephp.com/cs/extras/jquery-ajax
 * @version     0.22
 */

jQuery.extend({
    nette: {
        updateSnippet: function (id, html) {
            $("#" + id).html(html);
        //$.dump($("#" + id).html());
        },

        success: function (payload) {
            // redirect
            if (payload.redirect) {
                window.location.href = payload.redirect;
                return;
            }

            // snippets
            if (payload.snippets) {
                for (var i in payload.snippets) {
                    jQuery.nette.updateSnippet(i, payload.snippets[i]);
                }
            }
        },

        ajaxCall: function (href, event, callback) {

            $.get(href, function (payload) {
                $.nette.success(payload);
                if (typeof(callback) != 'undefined') { callback('success', payload); }
            })
            .error(function(xhr, status, error) {
                console.log("An AJAX error occured: " + status + "\nError: " + error);
                if (typeof(callback) != 'undefined') { callback('error', error); }
            });

            if (typeof(event) == 'undefined' || event == null) {
                $("#ajax-spinner").show();
            } else {
                // show spinner at a given position
                $("#ajax-spinner").show().css({
                    position: "absolute",
                    left: event.pageX + 20,
                    top: event.pageY + 40
                });
            }
        }

    }
});

jQuery.ajaxSetup({
    success: jQuery.nette.success,
    dataType: "json"
});

$(function () {
    $('<div id="ajax-spinner"></div>').appendTo("body").ajaxStop(function () {
        $(this).hide().css({
            position: "fixed",
            left: "50%",
            top: "50%"
        });
    }).hide();
});


$("a.ajax").live("click", function (event) {
    event.preventDefault();

    jQuery.nette.ajaxCall(this.href, event);
});




