/*
try {
    window.$ = window.jQuery = require('jquery');
    console.info('van jQuery');
} catch (e) {
    console.error('nincs jQuery');
}
*/

/**
 * Usage
 * $('a.selected').ajaxlink({});
 *
 * @param {Object} options
 */
(function($){

    var opts;

//-----------------------------------------------
    $.fn.ajaxlink = function(options)
    {
// build main options
        opts = $.extend({}, $.fn.ajaxlink.defaults, options);

        return this.each(function()
        {
            var target=opts.target;
            var inserttype=opts.inserttype;
            var data=opts.data;
            var ajaxtype=opts.ajaxtype;
            var beforepost=opts.beforepost;
            var afterpost=opts.afterpost;
            var self=this;

            var href=$(this).attr('href');

            var data_target=$(this).data('target');

            if(data_target) target=data_target;

            if( $(this).data('not_ajax')==true ) return;


            //Bind------
            $(this).unbind('click.ajaxlink');

            $(this).bind('click.ajaxlink', function(event)
            {
                event.preventDefault();

                if(href=='#' || href=='') return;

                beforepost(this,self);

                $.ajax({
                    async: true,
                    type: ajaxtype,
                    url: href,
                    data: data,
                    dataType: "html",
                    cache: false,
                    success: function(result)
                    {
                        switch(inserttype)
                        {
                            case 'innerhtml' : $(target).html(result); break;
                            case 'append' : $(target).append(result); break;
                            case 'replace' : $(target).replaceWith(result); break;
                            case 'after' : $(target).after(result); break;
                            case 'before' : $(target).before(result); break;
                        }

                        afterpost(result, self);
                    }
                });

            });

        });

    };
//-----------------------------------------------
    $.fn.ajaxlink.defaults =
        {
            target		: 'body',
            inserttype	: 'innerhtml', // [innerhtml, append, replace, after, before]
            ajaxtype	: 'POST', //[GET, POST]
            data		: {},
            beforepost		: function () {},
            afterpost		: function () {}
        };


})(jQuery);
