$.fn.loaders_init = function()
    {
        $(this).each (
            function (i, k) {
//                var self = this;
                var self = curr_loader = $(k);

                curr_loader.data({refresh : function () {
                        params = $(self).data('params');
                        if (params == undefined)
                            {
                                try
                                {
                                    eval ('params = ' + curr_loader.html().trim());
                                }
                                catch(ex)
                                {
                                    params = {};
                                }
                            }

//                    curr_loader.append( $('<div></div>').addClass('loader_spinner')  );
                    curr_loader.addClass('loading');

                    curr_loader.refresh = function() {
                        this;
                    }

                    com_name = curr_loader.attr('id');
                    getUrl = params.url === undefined
                                ? langUrl + '/' + com_name + '/ajax'
                                : params.url;
                    
                    if (params.url === '')
                        {
                            // consider as postponed loading
                            return params;
                        }
                    
                    delete params.url;
                    $.get(
                        getUrl,
                        params,
                        function(data)
                        {
                            self.html(data);
                            var cb = typeof tab_onload == 'undefined' ? undefined : tab_onload;
                            self.removeClass('loading').fadeIn( cb );
                        }
                    );
                    return params;
                }});

                curr_loader.data('params', curr_loader.data().refresh());
            }
        );
    }

function show_message (text, type)
{

    message = $('<div></div>');
    switch(type)
    {
        case 'error':
            className = 'alert';
            break;
        case 'info':
        default:
            className = 'info';
    }
    message.addClass(className);
    message.html(text);
    message.click( function()
        {
            $(this).remove();
        });

    $('html, body').animate({scrollTop: message.offset().top}, 100);

    msg_placeholder = $('#page_message_placeholder');
    msg_placeholder.children().remove();
    msg_placeholder.append( message );
}

$.validateEmail = function(email)
{
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(email);
}

$.fn.editurnable = function (editable_element_id) {
    this.each(function () {
        var me = $(this);
        var editButton = $('<img>')
                            .attr('src', '/images/communicate/doc_openedit_icon.png')
                            .addClass('edit_tick');
        me.prepend( editButton );
        me.addClass('editurnable');
        me.hover(function () {
            $(this).addClass('hovered');
        }, function () {
            $(this).removeClass('hovered');
        });
        if (editable_element_id === undefined)
            {
                editable_element_id = me.prop('id').replace('view', 'edit');
            }
        editable_element = $('#' + editable_element_id);        
        editButton.click(function () {
            me.hide();
            editable_element.show();
        })
    });
}

String.prototype.format = function() {
  var args = arguments;
  return this.replace(/{(\d+)}/g, function(match, number) { 
    return typeof args[number] != 'undefined'
      ? args[number]
      : '{' + number + '}'
    ;
  });
};

$.parseRaphael = function( raph )
{
    var items;
    if (raph.type != 'set')
        {
            items = [raph];
        }
    else
        {
            items = raph.items;
        }
        
    var jq = $();
    for (i in items)
        {
            jq = jq.add(items[i][0]);
        }
    return jq;
}

$.fn.hinty = function ( msg, tooltip_params ) {
    $(this).each (function () {
        var elem = $(this);
//        var pos = elem.offset();
//        var helpelem = $('<div>').addClass('hinty');
//        var width = pos.left + elem[0].offsetWidth + 5;
//        var top = pos.top ;
        var default_params =
        {
            track : false,
            showURL : false,
            bodyHandler : function() {
                                return nl2br(msg);
                            }
        }
        var params = $.extend(default_params, tooltip_params);
        elem.tooltip( params );
//                .css({
//                    left: width + 'px',
//                    top: top + 'px'
//                })
//                .appendTo('body');
//        helpelem.mouseenter(function () {
//            helpelem.stop().css('opacity', 1).hide().show();
//        });
//        elem.mouseenter(function () {
//            helpelem.stop().css('opacity', 1).hide().show();
//        });
//        helpelem.mouseleave(function () {
//            helpelem.fadeOut();
//        });
//        elem.mouseleave(function () {
//            helpelem.fadeOut();
//        });
    //    helpelem.mouseenter(function () {
    //            helpelem.show();
    //        });
    });
    return this;
}

$.fn.proForm = function ( callback )
{
    var callback = callback;
    this.each(function () {
        var form = $(this);
        var prof_spinner = $('<span>').addClass('spinner').hide();
        form.find('input:submit').after( prof_spinner );
        form.submit(function() {
            prof_spinner.show();
        $.post( form.attr('action')/*.replace('en/', 'index_dev.php/en/')*/, form.serialize(), function (data) {
                    if (data){
                        var json = true;
                        // response isn't always json
                        try
                        {
                            eval('data = ' + data);
                        }
                        catch(e){
                            json = false;
                        }
                        if ($.yii)
                        {
                            $.yii.page_infobox ? $.yii.page_infobox.hide() : 0;
                            $.yii.page_alertbox ? $.yii.page_alertbox.hide() : 0;
                        }
                        if (json)
                            {
                                if (data.status == 'ok'){
                                    (data.info != undefined) ? $.yii.page_infobox.text(data.info).show() : null;
                                    (data.note != undefined) ? $.yii.page_alertbox.html(data.note.join('<br>')).show() : null;
                                    callback ? callback(data) : null;
                                }else{
                                    (data.error != undefined) ? $.yii.page_alertbox.html(data.error.join('<br>')).show() : null;
                                }
                            }
                        else
                            {
                                callback ? callback(data) : null;
                            }
                    }
                    prof_spinner.hide();
            } );
            return false;
        });
    });
}

$.fn.setDefaults = function(){
    this.each(function(){
        var form = $(this);
        
        $(form.selector + ' ' + 'input').each(function(){
            $(this).attr('value', $(this).val());
        });
        
        $(form.selector + ' ' + 'select').each(function(){
            var currentValue = $(this).val();
            $(this).find('option').each(function(){
                ($(this).val() == currentValue) ? $(this).attr('selected', 'selected') : $(this).removeAttr('selected');
            });
        });
        
        $(form.selector + ' ' + 'textarea').each(function(){
            $(this).text($(this).val());
        });
    });
}

$.fn.overflowed = function () {
    this.each(function () {
        var th = $(this);
        if (this.scrollHeight > this.clientHeight || this.scrollWidth > this.clientWidth)
            {
                th.hinty(th.text());
            }
    })
}

function nl2br (str, is_xhtml) {
    var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}

function randomString(L){
        var s= '';
        var randomchar=function(){
            var n= Math.floor(Math.random()*62);
            if(n<10) return n; //1-10
            if(n<36) return String.fromCharCode(n+55); //A-Z
            return String.fromCharCode(n+61); //a-z
        }
        while(s.length< L) s+= randomchar();
        return s;
    }

function checksum(s)
{
        var i;
        var chk = 0x12345678;

        for (i = 0; i < s.length; i++) {
        chk += (s.charCodeAt(i) * (i+1));
        }

        return chk;
}

// play

$(
    function () {
        
        $('._loaders').loaders_init();
        $(window).blur(function () {
            $.window_focused = false;
        });
        $(window).focus(function () {
            $.window_focused = true;
        });
    }
);
    
/**
 * Assigns hint to user roles, that describes meaning of the role
 */
(function($){
    $.fn.roleHint = function(role)
    {    
        if ( role )
            this.hinty(roleHints[role]);

        return this;
    }
})(jQuery);

