( function ($) { 
    $(document).ready(function(){
        
        function api( data, rfn ) {
            $.ajax({
                url: cms.api,
                type: 'POST',
                data: data,
                success: function(rdata){
                    if ((rdata.substr(0,1) == '{') || (rdata.substr(0,1) == '[')) rdata = JSON.parse(rdata);
                    if (rfn) {
                        rfn(rdata);
                    }
                },
                error: function(xhr, ajaxOptions, thrownError){
                    if (xhr.status == 0) { rfn({result:'timeout'}); }
                }
            });
        }


        /* Notifications */
        function notify( message, classes, msec ) {
            var el = $('<div class="'+classes+'">'+message+'</div>');
            $('.log-info-box').prepend(el);
            if ( msec )
            setTimeout(function(){
                $(el).fadeOut(msec, function(){
                    $(el).remove();
                });
            }, msec);
        }

        /* Translate function */

        function __( str, context = 'update.mod.php' ) {
            if (!cms) return str;
            if (!cms.locale) return str;
            if (!cms.lang[context]) return str;
            if (!cms.lang[context][cms.locale][str]) return str;
            return cms.lang[context][cms.locale][str];
        }

        $("[data-cms-update]").click(function(){
            var fn = $(this).attr("data-fn");
            var data = {
                fn: fn
            }
            api(data, function(r){
                if (r.result == 'timeout') {
                    notify( __("Connection lost"), 'info-error', 10000 );
                } else if (r.info_text) {
                    notify( r.info_text, r.info_class, r.info_time );
                    if ( r.answer != null ) {
                        $("[data-"+data.fn+"-answer]").html( r.answer );
                    }
                    if ( r.reload ) {
                        window.location.reload(true);
                    }
                }
            });
        });

        if ( window.location.hostname.match(/\.coffee-cms\.com/) ) {
            $(".info.developers_only").removeClass("developers_only");
        }

    }); 
})( jQuery );