Function.prototype.bind_ctx = function (scope) {
    var fn = this;
    return function () {
        return fn.apply(scope, arguments);
    };
};

function function_exists(function_name) {    // Return TRUE if the given function has been defined
    if (typeof function_name == 'string') {
        return (typeof window[function_name] == 'function');
    } else {
        return (function_name instanceof Function);
    }
}

/**
 * Log message. Use console.log if method exists, otherwise use message function
 * @param obj
 */
function log(obj) {
    if (window.console !== undefined)
        console.log(obj);
    else
        message(obj);
}

process_json_response = function(json) {
    if (json.result) {
        if (json.remove)
            $(json.remove).remove();

        message(json.message);
    }
    else
        notification(json.message);
    log(json.message);
};

//add postJSON method to jquery
jQuery.extend({
    postJSON : function(url, data, callback) {
        callback = callback || process_json_response;
        $.ajax({
            data: data,
            url: url,
            type: "POST",
            dataType: "json",
            success: callback
        });

    }
});

function load_overlay(selector) {
    var overlay = $(selector);

    overlay.overlay({
        top: "center",
        load: true,

        // some mask tweaks suitable for modal dialogs
        mask: {
            color: '#666',
            loadSpeed: 200,
            opacity: 0.9
        },
        onClose: function () {
        }
    }).load();

    return overlay;
}

/**
 * Show text in overlay
 * @param text
 * @param time
 */
message = function(text, time) {
    time = time || 5000;

    $(".overlay.message").overlay({
        top: "center",
        load: true,
        onLoad: function(event) {
            var overlay = this;
            setTimeout(function() {
                overlay.close();
            }, time);
        }
    }).load();

    $(".overlay.message .message").html(text);
};


/**
 * Show html in the overlay
 * @param html
 * @param id
 */
overlay_html = function(html, id) {

    //$("body").append(html);

    elem = $(html).appendTo('body');

    if (id)
        var overlay = $("#" + id);
    else
        var overlay = elem;


    overlay.overlay({
        top: "center",
        load: true,

        // some mask tweaks suitable for modal dialogs
        mask: {
            color: '#666',
            loadSpeed: 200,
            opacity: 0.9
        },
        onClose: function () {
            overlay.remove();
        }
    }).load();
};

/**
 * Show overlay with message and two buttons (yes/no).
 * Make ajax request when button clicked.
 * @param message Text to show up in overlay message
 * @param url ajax url
 * @param data ajax data
 * @param callback ajax success callback
 * @param ajax_on_no send ajax request if No button clicked
 */
overlay_yesno = function (message, url, data, callback, ajax_on_no) {
    var overlay = $("#yesno");
    ajax_on_no = ajax_on_no || false;
    overlay.overlay({
        top: "center",
        load: true,

        // some mask tweaks suitable for modal dialogs
        mask: {
            color: '#666',
            loadSpeed: 200,
            opacity: 0.9
        },
        onClose: function () {
        }
    }).load();

    if (url) {
        $("button", overlay).click(function () {
            var yesno = $(this).text() == 'Yes' ? true : '';

            if (!yesno && !ajax_on_no)
                return false;

            var yesno_data = {'yesno':yesno};

            if (data)
                $.extend(data, yesno_data);
            else data = yesno_data;

            $.getJSON(url, data, function (response) {
                callback(response, yesno);
            });
        });
    }

    $(".message", overlay).html(message);

};


function overlay_form_with_message(title, url, data, callback) {
    var overlay = load_overlay('#message-form');


    var input = $("input[type='submit']", overlay);
    //unbind previous handlers assigned in this function
    input.unbind('click');
    input.click(function () {
        url = url + '?message=' + $('textarea', overlay).val();
        $.getJSON(url, data, function (response) {
            callback(response);
        });
    });


    $(".title", overlay).html(title);
}

function saved() {
    $("#saved").slideDown("fast").delay(1000).slideUp('fast');
}


function viewProfile($item) {
    $.get($item.attr('data-profile-url'), function (data) {
        overlay_html(data);
    });

    return false;
}

/**
 * Show notification at the top of screen
 * @param message
 */
notification = function(message) {
    var notification = $("#notification");

    if (!notification.length) {
        notification = $('<div id = "notification"/>');
        $(document.body).append(notification);
    }

    notification.text(message);
    notification.bind('click', function() {
        $(this).slideUp(200);
    });

    notification.slideDown("slow");
    setTimeout(function() {
        notification.slideUp(200)
    }, 7000);
};

function str_replace(search, replace, subject) {    // Replace all occurrences of the search string with the replacement string
    //
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni

    if (!(replace instanceof Array)) {
        replace = new Array(replace);
        if (search instanceof Array) {//If search	is an array and replace	is a string, then this replacement string is used for every value of search
            while (search.length > replace.length) {
                replace[replace.length] = replace[0];
            }
        }
    }

    if (!(search instanceof Array))search = new Array(search);
    while (search.length > replace.length) {//If replace	has fewer values than search , then an empty string is used for the rest of replacement values
        replace[replace.length] = '';
    }

    if (subject instanceof Array) {//If subject is an array, then the search and replace is performed with every entry of subject , and the return value is an array as well.
        for (k in subject) {
            subject[k] = str_replace(search, replace, subject[k]);
        }
        return subject;
    }

    for (var k = 0; k < search.length; k++) {
        var i = subject.indexOf(search[k]);
        while (i > -1) {
            subject = subject.replace(search[k], replace[k]);
            i = subject.indexOf(search[k], i);
        }
    }

    return subject;

}


(function($) {

    $.fn.bar = function(options) {
        var opts = $.extend({}, $.fn.bar.defaults, options);
        return this.each(function() {
            $this = $(this);
            var o = $.meta ? $.extend({}, opts, $this.data()) : opts;

            $this.click(function(e) {
                if (!$('.jbar').length) {
                    timeout = setTimeout('$.fn.bar.removebar()', o.time);
                    var _message_span = $(document.createElement('span')).addClass('jbar-content').html(o.message);
                    _message_span.css({"color" : o.color});
                    var _wrap_bar;
                    (o.position == 'bottom') ?
                            _wrap_bar = $(document.createElement('div')).addClass('jbar jbar-bottom') :
                            _wrap_bar = $(document.createElement('div')).addClass('jbar jbar-top');

                    _wrap_bar.css({"background-color"     : o.background_color});
                    if (o.removebutton) {
                        var _remove_cross = $(document.createElement('a')).addClass('jbar-cross');
                        _remove_cross.click(function(e) {
                            $.fn.bar.removebar();
                        })
                    }
                    else {
                        _wrap_bar.css({"cursor"    : "pointer"});
                        _wrap_bar.click(function(e) {
                            $.fn.bar.removebar();
                        })
                    }
                    _wrap_bar.append(_message_span).append(_remove_cross).hide().insertBefore($('.content')).fadeIn('fast');
                }
            })


        });
    };
    var timeout;
    $.fn.bar.removebar = function(txt) {
        if ($('.jbar').length) {
            clearTimeout(timeout);
            $('.jbar').fadeOut('fast', function() {
                $(this).remove();
            });
        }
    };
    $.fn.bar.defaults = {
        background_color     : '#FFFFFF',
        color                 : '#000',
        position             : 'top',
        removebutton         : true,
        time                 : 5000
    };

})(jQuery);


// menu items alignment
(function($) {
    $.fn.align = function() {
        var elements_width = 0;
        var children = $(this).children();
        var children_first = children.first();
        var children_last = children.last();
        children.each(function () {
            elements_width += $(this).outerWidth(true);
        });
        var diff = parseInt(($(this).width() - elements_width) / (children.length));


        children.not(":first").not(":last").each(function () {
            $(this).width($(this).width() + diff);
        });


        children_first.css('padding-right', parseInt(children_first.css('padding-right')) + diff - 1);
        children_last.css('padding-left', parseInt(children_last.css('padding-left')) + diff);


    }
}(jQuery));
