/**
 *  Create new event DOMChanged fired by some jquery DOM Manipulations
 **/
(function(_append, _appendTo, _after, _insertAfter, _before, _insertBefore) {
    $.fn.append = function() {
        this.trigger({
            type: 'DOMChanged',
            newnode: arguments[0]
        });
        var ret =  _append.apply(this, arguments);
        this.trigger({
            type: 'afterDOMChanged',
            newnode: arguments[0]
        });
        return ret;
    };
    $.fn.appendTo = function() {
        this.trigger({
            type: 'DOMChanged',
            newnode: this
        });
        var ret =  _appendTo.apply(this, arguments);
        this.trigger({
            type: 'afterDOMChanged',
            newnode: arguments[0]
        });
        return ret;
    };
    $.fn.after = function() {
        this.trigger({
             type: 'DOMChanged',
             newnode: arguments[0]
         });
        var ret =  _after.apply(this, arguments);
        this.trigger({
            type: 'afterDOMChanged',
            newnode: arguments[0]
        });
        return ret;
    };
    $.fn._insertAfter = function() {
        this.trigger({
             type: 'DOMChanged',
             newnode: arguments[0]
         });
        var ret =  _insertAfter.apply(this, arguments);
        this.trigger({
            type: 'afterDOMChanged',
            newnode: arguments[0]
        });
        return ret;
    };
    $.fn._before = function() {
        this.trigger({
             type: 'DOMChanged',
             newnode: arguments[0]
         });
        var ret =  _before.apply(this, arguments);
        this.trigger({
            type: 'afterDOMChanged',
            newnode: arguments[0]
        });
        return ret;
    };
    $.fn._insertBefore = function() {
        this.trigger({
             type: 'DOMChanged',
             newnode: arguments[0]
         });
        var ret =  _insertBefore.apply(this, arguments);
        this.trigger({
            type: 'afterDOMChanged',
            newnode: arguments[0]
        });
        return ret;
    };
    // and so forth

}($.fn.append, $.fn.appendTo, $.fn.after, $.fn.insertAfter, $.fn.before, $.fn.insertBefore));/**
 * File that should bootstrap NMP functions
 *
 * @author Jan Juricek <jan@nameee.com>
 */

//$.ajaxSetup({
//    dataType: 'json',
//    type: 'POST',
//    scriptCharset: 'utf-8',
//    contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
//});

$(function(){
    /**
     * Detect IE 7
     */
    var ie = false,
        ie7 = false;
    if($.browser.msie){
        ie = true;
        if ($.browser.version<8) {
            ie7 = true;
            $('body').addClass('ie ie7');
        } else if($.browser.version == 8) {
            $('body').addClass('ie8');
        }
    }

    /**
     * Bind click event for accountMenu
     */
    $('#myacclink').click(function(){
        $(this).toggleClass('Open');
    });

    /**
     * Bind a click event to all the links in the header part
     */
    var dropDownLinks = $('#DD').find('li');

    if (dropDownLinks.length > 0) {
        if (ie7) {
            var elems = '#w *';
        }

        $.each(dropDownLinks, function(i, el){
            $(el).click(
                function(e){
                    if (ie7){
                        // IE 7 z-index hack
                        $(elems).css('z-index',-1);
                    }

                    e.stopPropagation();
                }
            );
        });

        /**
         * Dropdown hidding
         */
        $('html').click(function(){
            dropDownLinks.filter('.active').removeClass('active');
            if (ie7) {
                // IE 7 z-index hack
                $(elems).css('z-index',10);
            }
        });
    }

});/**
 * js/nmp/translation.js
 *
 * This file is considered confidential in terms of the signed NDA.
 *  Any form of access of unauthorized personel is strictly prohibited.
 *
 * @author Svatopluk Svec <svatopluk.svec@webcorp.cz>
 * @copyright 2011 Nameee.com, a.s.
 * @package translation
 */

function lm( ident, sum )
{
    if( typeof( lmp ) == 'undefined' )
        return ident;
    if( typeof( lmp[ ident ] ) == 'undefined' )
        return ident;
    var ret = '';
    if( typeof( sum ) == 'undefined' )
    {
        ret = lmp[ ident ][0];
    }
    else
    {
        ret = lmp[ ident ][ plural( sum ) ]
        if( typeof( ret ) == 'undefined' )
            ret = lmp[ ident ][0]; //problem pri pluralu : navrat vychozi hodnoty
    }
    if( !( typeof( ret ) != 'undefined' && ret != '' ) )
        return ident;
    return ret;
}

var Nameee = Nameee || {};

Nameee.activity = {
    defaultActivityTimeout: 1000 * 60 * 5,
    _timestamp: new Date(),
    _timeout: 0,
    _listeners: {inactive: [], active: []},
    _is_active: false,
    
    setTimeout: function(timeout) {
        // Set up inactive time
        var init = (this._timeout == 0);
        this._timeout = timeout;
        if (init) {
            this._timestamp = new Date().getTime() + timeout;
            this._is_active = true;
            window.setTimeout(this._inactivate, timeout+50);

            // Set event handlers
            doc = $(document);
            doc.click(function() { Nameee.activity._activate(); });
            doc.dblclick(function() { Nameee.activity._activate(); });
            doc.mousemove(function() { Nameee.activity._activate(); });
            doc.mouseenter(function() { Nameee.activity._activate(); });
            doc.scroll(function() { Nameee.activity._activate(); });
            doc.keydown(function() { Nameee.activity._activate(); });
        }
    },
    
    isActive: function() {
        return this._is_active ? (this._timestamp - new Date().getTime()) : false;
    },

    addEventListener: function(type, listener, recurring) {
        recurring = recurring || false;
        if (!Nameee.activity._timeout) { return false; }
        if (Nameee.activity._listeners[type]) {
//console.log('adding event listener to type '+ type +', listener = '+ listener );
            Nameee.activity._listeners[type].push({callback: listener, recurring: recurring});
            return listener;
        }
    },
    
    removeEventListener: function(type, listener) {
        if (Nameee.activity._listeners[type]) {
            var listener_index;
            Nameee.activity._listeners[type].forEach(function(item, index) {
                if (item.callback == listener) {
                    listener_index = index;
                }
            });
            if (listener_index != undefined) {
                delete(Nameee.activity._listeners[type][listener_index]);
            }
        }
    },

    _activate: function() {
        var now = new Date().getTime();

        if (blink == 1) {
            blink = 0;
            document.title = titleOld;
            };

        this._timestamp = now + this._timeout;
        if (!this._is_active || now < this._timeout) {
            this._is_active = true;
            listeners = [];
            if (this._listeners.active) {
                this._listeners.active.forEach(function(listener) {
                    listener.callback.call();
                    if (listener.recurring) { listeners.push(listener); }
                });
            }
            this._listeners.active = listeners;
            setTimeout(Nameee.activity._inactivate, Nameee.activity._timestamp - now + 50);
        }
    },
    
    _inactivate: function() {
        var now = new Date().getTime();
        if (now < Nameee.activity._timestamp) {
            setTimeout(Nameee.activity._inactivate, Nameee.activity._timestamp - now + 50);
            return;
        }
        Nameee.activity._is_active = false;
        listeners = [];
        if (Nameee.activity._listeners && Nameee.activity._listeners.inactive) {
            Nameee.activity._listeners.inactive.forEach(function(listener) {
                listener.callback.call();
                if (listener.recurring) { listeners.push(listener); }
            });
        }
        Nameee.activity._listeners.inactive = listeners;
    }
};var Nameee = Nameee || {};

Nameee.ads = {
    hideFieldByType: function(el, imageTypeConstant)
    {
        // skryti formularovych casti na zaklade typu reklamy
        if ( imageTypeConstant == $(el).val() )
        {
            $('#js_ads_text').hide();
        }
        else
        {
            $('#js_ads_text').show();
        }
    },
    
    hideCampaignTime: function(el, textTypeConstant)
    {
        // skryti bloku pro nastaveni casu kampane

        if ( textTypeConstant == $(el).val() )
        {
            $('#js_ads_campaignTime').hide();
        }
        else
        { 
            $('#js_ads_campaignTime').show();
        }        
    },

    /**
     * AJAX nacteni dalsi stranky reklam
     */
    loadNextPageCampaignSearchAdmin: function(domId, url, nextToken)
    {
        $.ajax({
            type: 'POST',
            url: url,
            data: $('#ads-admin-search').serialize() + '&nextToken=' + encodeURIComponent(nextToken),
            beforeSend: function(){
                Nameee.loader.begin('#' + domId, false);
            },
            success: function(msg){
                $('#' + domId).after(msg).remove();
            }
        });

        return false;
    },

    /**
     * AJAX nacteni dalsi stranky reklam
     */
    loadNextPageCampaign: function(domId, url, nextToken)
    {
        $.ajax({
            type: 'POST',
            url: url,
            data: {
                nextToken: nextToken
            },
            beforeSend: function(){
                Nameee.loader.begin('#' + domId, false);
            },
            success: function(msg){
                $('#' + domId).after(msg).remove();
            }
        });

        return false;
    },

    /**
     * AJAX nacteni dalsi stranky dennich statistik
     */
    loadNextPageDay: function(domId, url, itemName, nextToken)
    {
        $.ajax({
            type: 'POST',
            url: url,
            data: {
                itemName: itemName,
                nextToken: nextToken   
            },
            beforeSend: function(){
                Nameee.loader.begin('#' + domId, false);
            },
            success: function(msg){
                $('#' + domId).after(msg).remove();
                drawChart();
            }
        });

        return false;
    },

    deleteAd: function(el, url, itemName)
    {
        var item = $(el).parent();
        $.ajax({
            type: 'POST',
            url:  url,
            data: {
                itemName: itemName
            },
            beforeSend: function(){
                Nameee.loader.begin(item, true);
            },
            success: function(msg){
                if ( 0 == msg.length ){item.parent().remove();}else{item.html(msg);}
            }
        });

        return false;
    }
};var Nameee = Nameee || {};

/**
 * Nameee.ajaxDialog
 * Opens a given page within a modal dialog. Dialog may change parent window's location.
 * Multiple dialogs may be opened, closed in LIFO order.
 */
 /* Todo: Set height of iframe via js */
Nameee.ajaxDialog = {
    _isDirty: false,

    open: function (id, url, options) {
        // Drop z-index of any already-open dialog and overlay by 10
        parent.$('.ui-dialog, .ui-widget-overlay').each(function(i, el) {
            el = $(el);
            el.css('z-index', el.css('z-index')-10);
        });

        options = options || {};
        // Set defaults
        options.width = options.width || 540;
        options.title = options.title || '';

//        options.position

        if ($('#dialog-'+id).size()) {
            $('#dialog-'+id).dialog('option', options);
            $('#dialog-'+id).dialog('open');
        } else {

            options.closeText = '';

            options.modal = true;
            options.beforeClose = function(event, ui) {
                // If multiple dialogs open, check this is the top one
                var z = parent.$('#'+event.target.id).parents('.ui-dialog').css('z-index');
                if (z < 1000) {
                    return false;
                }
                return true;
            };
            options.close = function() {
                $(this).undelegate();
                $(this).remove();
                // Increase other dialogs and overlays by 10
                parent.$('.ui-dialog, .ui-widget-overlay').each(function(i, el) {
                    el = $(el);
                    el.css('z-index', parseInt(el.css('z-index'), 10)+10);
                });
            };

            var html = $(''
                +   '<div id="dialog-'+id+'" class="UI-Dialog">'
                +       '<div class="Content Loading">'
                +           '<img src="/img/loading.gif" alt="Loading, please wait." />'
                +       '</div>'
                +   '</div>'
            );

            options.position = ['center',100];

            html.dialog(options);

            if (options.ajax != false) {
                $.get(url, function(data) {
                    $('#dialog-'+id).html(data);
                });
            } else {
                Nameee.ajaxDialog.openSimple(id, url, options);
            }
        }
    },

    openSimple: function (id, content, options) {

        // Buttons
        var button_html = '';
        if (options.buttons) {
            var button, button_class;
            button_html = '<div class="Buttons">';
            $(options.buttons).each(function(index, element) {
                button = '<a href="#" data-offset="' + index + '">' + this.text + '</a>';
                button_class = this.buttonClass ? ' class="' + this.buttonClass + '"' : '';
                button_html += ''
                    +   '<div' + button_class + '>'
                    +       '<div>'
                    +           button
                    +       '</div>'
                    +   '</div>'
                ;
            });
            button_html += '</div>';

            delete options.buttons;
        } else {
            button_html = ''
                +   '<div class="Buttons">'
                +       '<div class="UI-Button Sec">'
                +           '<div>'
                +               '<a href="#" onclick="$(this).closest(\'.UI-Dialog\').dialog(\'close\');">'
                +                   lm('Close')
                +               '</a>'
                +           '</div>'
                +       '</div>'
                +   '</div>'
            ;
        }

        var $dialog = $('#dialog-'+id);

        $dialog.html(null);
        $('<div>', {
           'class': 'Top',
           html: $('<h2>', {
               text: options.title
           })
        }).appendTo($dialog);

        $('<div>', {
            'class': 'Content',
            css: {'padding':'5px 10px'},
            html: content
        }).appendTo($dialog);

        $('<div>', {
            'class': 'Bottom',
            html: button_html
        }).appendTo($dialog);
    },

    close: function (id) {
        var dialog = (parent ? parent.$('#dialog-'+id) : $('#dialog-'+id));
        dialog.dialog('close');
    },

    redirect: function (url) {
        document.location = url;
    },

    updateValue: function (id, value) {
        $('#'+id).val(value);
    }
};
var Nameee = Nameee || {};

/**
 * Nameee.autocomplete
 * Allows autocomplete from array or url, and multiple items to be selected using sortable lists
 */

Nameee.autocomplete = {

    _tempTerm: null,
    _addLabel: lm('Add '),
    _imaginaryInput: false, //was imaginary input selected while in addurl mode without url?

    parseLabelVal : function( val )
    {
        if( Nameee.autocomplete._imaginaryInput )
        {
            val = val.substring( Nameee.autocomplete._addLabel.length+1); //i s uvozovkou
            val = val.substr(0, val.length-1);
        }
        return val;
    },

    init: function (id, autocomplete_url, addnewitem_url, sortable, removable, selectHandler ) {
        //sanity
        sortable = ( typeof(sortable) != 'undefined' && sortable == true );
        removable = ( typeof(removable) != 'undefined' && removable == true );

        this.opened = false;
        this.tempTerm = '';

        var options = {
            source: autocomplete_url,
            open: function(event, ui) {
                //make while open - only once
                if( !this.opened )
                {
                    this.opened = true;
                    if (typeof $('#' + id).style != 'undefined') {
                        additionalWidth = parseInt($('#' + id).style.paddingLeft) + parseInt($('#' + id).style.paddingRight);
                    } else {
                        additionalWidth = '';
                    }
                    var width = $('#'+id).width() + additionalWidth;
                    var list = $('#'+id+'-auto-list').width(width).addClass('text whisper').attr('id', id+'-auto-list');
                    list.wrap('<div class="form-profile" id="'+id+'-auto-form"><div class="input-help" /></div>');
                }
            },
            close: function(event, ui) {
                var tmpAutocomplete = $('#'+id+'-auto-list').removeClass('text whisper');

            /*
                //this happened to disable all next select() on first select()
                $('#'+id+'-auto-form').remove();
                tmpAutocomplete.appendTo('body');
                /**/
            }
        };

        if (addnewitem_url) {
            // Add callback to url source to allow for 'add' option on empty results
            //either to propagate to db, or only to form (propagate will be done later)
            options.source = function( request, response ) {
                if (self.xhr) {
                    self.xhr.abort();
                }
                //workaround for utf-8 encoding, but not good decoding inside ajax request
                Nameee.autocomplete._tempTerm = request.term;
                Nameee.autocomplete._imaginaryInput = false;
                self.xhr = $.ajax({
                    url: autocomplete_url,
                    data: request,
                    success: function( data, status, xhr ) {
                        //                             var term = this.data.split('=')[1];
                        //                             term = unescape( term );
                        var jsondata  =  JSON.parse( data );
                        if( jsondata.length < 1 )
                        {
                            jsondata.push({
                                label: Nameee.autocomplete._addLabel +'"' + Nameee.autocomplete._tempTerm + '"',
                                value: 0
                            });
                            Nameee.autocomplete._imaginaryInput = true;
                        }
                        if ( xhr === self.xhr ) {
                            response( jsondata );
                        }
                        self.xhr = null;
                    },
                    error: function( xhr ) {
                        if ( xhr === self.xhr ) {
                            response( [] );
                        }
                        self.xhr = null;
                    }
                });
            };

            if( typeof( addnewitem_url ) == 'string' )
            {
                // Sortable-specific options
                options.select = function(event, ui) {
                    //console.log('je select, val = '+ ui.item.value );
                    event.preventDefault();
                    if (!$('#'+id+'-add #'+ui.item.value).length) {
                        if (ui.item.value == 0) {
                            Nameee.autocomplete._imaginaryInput = false;
                            $.ajax({
                                url: addnewitem_url,
                                data: {
                                    term: this.value
                                },
                                success: function( data, status, xhr ) {
                                    Nameee.autocomplete._addToList(id, JSON.parse(xhr.responseText));
                                },
                                error: function( data, status, xhr )
                                {
                                    alert( lm('There was a problem during processing of your request, try again later, please'));
                                }
                            });
                        } else {
                            Nameee.autocomplete._addToList(id, ui.item);
                        }
                    }
                    $(this).val('');
                };
            }
            else
            {
                // Sortable-specific options
                options.select = function(event, ui) {
                    //console.log('je select, val = '+ ui.item.value );
                    event.preventDefault();
                    Nameee.autocomplete._addToList(id, ui.item);
                };
            }

        }

        if (sortable) {
            // Initialise sortable lists to dragdrop items between add and remove lists
            if( removable )
            {
                Nameee.sortable.init(id,'add','remove');
                Nameee.sortable.init(id,'remove','add');
            }

            // Sortable-specific options
            options.select = function(event, ui) {
                //console.log('je select, val = '+ ui.item.value );
                event.preventDefault();
                if (!$('#'+id+'-add #'+ui.item.value).length) {
                    Nameee.autocomplete._addToList(id, ui.item);
                }
                $(this).val('');
            };
            //no other value manipulation
            options.focus = function(event, ui) {
                event.preventDefault();
            };
        } else {
            // Non-sortable-specific options
            options.focus = function(event, ui) {
                event.preventDefault();
                //if it is after imaginary add new value:
                $(this).val( Nameee.autocomplete.parseLabelVal(ui.item.label));
            };
            options.select = function(event, ui) {
                event.preventDefault();
                var label = Nameee.autocomplete.parseLabelVal(ui.item.label);
                $(this).val( label );
                $( '#'+ id +'-label').val( label ); //prevent user change of inc label, complexfield support
                $( '#'+ id +'-value').val( ui.item.value );
            };
            //custom handler, called while user select autocomplete item from offer list
            if( selectHandler != null )
            {
                options.select = selectHandler;
            }
        }

        // Initialise autocomplete
        $('#'+id).autocomplete(options);
        $('#'+id).autocomplete('widget').attr('id', id+'-auto-list');
        // Override standard filter to only match start of string when using array source
        $.ui.autocomplete.filter = function(array, term) {
            var matcher = new RegExp('^' + $.ui.autocomplete.escapeRegex(term), "i" );
            return $.grep( array, function(value) {
                return matcher.test( value.label || value.value || value );
            });
        };

        if ( sortable && removable ) {
            // Event handlers for showing/hiding delete list
            $('#'+id+'-add').bind('sortstart', function() {
                if ($('#'+id+'-remove').hasClass('hidden')) {
                    $('#'+id+'-more-remove').removeClass('hidden');
                    $('#'+id+'-more-remove').droppable({
                        accept: '#'+id+'-add a',
                        hoverClass: "ui-state-highlight",
                        drop: function( event, ui ) {
                            ui.draggable.hide( 'fast', function() {
                                $( this ).appendTo($('#'+id+'-remove')).show('fast');
                                //console.log('calling sortable._update(add) ');
                                Nameee.sortable._update($('#'+id+'-add'), id+'-add', id);
                                $('#'+id+'-more').text('show more (' + $('#'+id+'-remove').children().length + ')');
                            });
                        }
                    });
                }
            });
            $('#'+id+'-add').bind('sortstop', function() {
                if ($('#'+id+'-remove').hasClass('hidden')) {
                    $('#'+id+'-more-remove').addClass('hidden');
                }
            });
            $('#'+id+'-more').click(function(e) {
                e.preventDefault();
                var remove = $('#'+id+'-remove');
                if (remove.hasClass('hidden')) {
                    remove.removeClass('hidden');
                    $(this).text('hide more');
                } else {
                    remove.addClass('hidden');
                    $(this).text( lm('show more ')+ '(' + remove.children().length + ')');
                }
            });
        }
    },

    remove: function( domobj, id )
    {
        //clear one member from list (either add or remove list)
        var remobj = $(domobj).parent().parent().parent(); //proste smazani a update datove prezentace seznamu
        var list = remobj.parent();
        var listType = list.attr('id').substr( id.length + 1 );
        remobj.remove();
        Nameee.sortable._update( list, id, listType );
    },

    _addToList: function(id, item) {
        var list = $('#'+id+'-add');
        //duplicity check, for add and remove lists
        if( item.value != 0 )
        {
            if( list.parent().find('div[name=ac_'+ item.value +']').size() > 0 )
                return false;
        }
        var list_item = $('<a title="" class="link-box lb-h18 lb-noimg" href="#"><span class="right lb-fs11"><span class="ico">'+item.label+'</span></span></a>');
        list_item = $( '<div name="ac_'+ item.value +'" class="UI-RoundBlock Blue"><div class="Top"><div class="Bottom"><span name="ilabel">'+ item.label  +'</span> <a style="float:right;" onclick="return Nameee.autocomplete.remove(this,\''+ id +'\');" title="remove" class="link-box lb-h18 lb-noimg" href="javascript:void(0);">&nbsp;x&nbsp;</a></div></div></div>' );

        list.append(list_item.attr('id', id+'-'+item.value));
        list.sortable('refresh');
        Nameee.sortable._update(list, id, 'add' );
    }
};var Nameee = Nameee || {};

/**
 * Namee.calendar
 * Opens a date-picker based on a specified trigger and updates input with selected date
 * Calendar is based on date picker here: http://keith-wood.name/datepick.html
 * Full reference for options is available here: http://keith-wood.name/datepickRef.html
 *
 * Defaults: type = 'text'
             options = {
                        defaultDate: [value of field(s)],
                        yearRange: 'c-10:c+10' // Currently selected date +/- 10 years (updated on date change). Formats: absolute year, '-10'/'+10' years from current year
                       }
 */
Nameee.calendar = {
    init: function (id, type, options) {
        if (!type) {type = 'text';}

        options = options || {};
        
        var dateFormat = 'd.m.yyyy';
        var altField = '#'+id+'_date_int';
        var intFormat = 'yyyy-mm-dd';

        var fields, day, month, year, alt, defaultDate;
        switch (type) {
            case 'text':
                options.altField = altField;
                options.altFormat = intFormat;
                options.dateFormat = dateFormat;
                options.defaultDate = $('#'+id).val();
                options.selectDefaultDate = true;
                localDate = $.datepick.formatDate(dateFormat, $.datepick.parseDate(intFormat, $(altField).val()));
                $('#'+id).val(localDate);
                
                fields = [$('#'+id)];
                break;
            case 'multi':
                alt = $(altField);
                day = $('#'+id+'_d');
                month = $('#'+id+'_m');
                year = $('#'+id+'_y');
                // Set options & default date
                options.offset = day.offset();
                options.dateFormat = intFormat;
                defaultDate = new Date(year.val(), month.val()-1, day.val());
                options.defaultDate = defaultDate;
                // Update text boxes on choosing date
                options.onSelect = function(dates) {
                    day.val(dates.length ? dates[0].getDate() : '');
                    month.val(dates.length ? dates[0].getMonth() + 1 : '');
                    year.val(dates.length ? dates[0].getFullYear() : '');
                    alt.val($.datepick.formatDate(intFormat, dates[0]));
                };
                // Validate and update calendar when fields change or blur
                $.each([day, month, year], function() {
                    this.change(function(e) {
                        var newDate = new Date(year.val(), parseInt(month.val(), 10)-1, day.val());
                        alt.datepick('setDate', newDate);
                        alt.val($.datepick.formatDate(intFormat, newDate));
                    });
                    this.blur(function() {
                        var newDate = new Date(year.val(), parseInt(month.val(), 10)-1, day.val());
                        if (!(parseInt(day.val(), 10) == parseInt(newDate.getDate(), 10) &&
                                parseInt(month.val(), 10) == parseInt(newDate.getMonth(), 10)+1 &&
                                parseInt(year.val(), 10) == parseInt(newDate.getFullYear(), 10))) {
                            $(this).focus();
                        }
                    });
                });
                alt.val($.datepick.formatDate(intFormat, defaultDate));
                fields = [day, month, year];
                break;
            case 'span':
                var span = $('#'+id);
                alt = $(altField);
                // Set options
                options.dateFormat = intFormat;
                defaultDate = $.datepick.parseDate(dateFormat, span.text());
                options.defaultDate = defaultDate;
                // Create a trigger div and position it over date
                var position = 'top:'+span.offset().top+';left:'+span.offset().left+';width:'+span.width()+'px;height:'+span.height()+'px;';
                options.showTrigger = '<div style="position:absolute;z-index=1000;'+position+';cursor:hand;" class="cal-span" />';
                // Update span on choosing date
                options.onSelect = function(dates) {
                    span.text(dates.length ? $.datepick.formatDate(dateFormat, dates[0]) : '');
                };
                alt.val($.datepick.formatDate(intFormat, defaultDate));
                fields = [alt];
                break;
            case 'select':
                alt = $(altField);
                day = $('#'+id+'_d');
                month = $('#'+id+'_m');
                year = $('#'+id+'_y');
                // Set options
                defaultDate = new Date(year.val(), month.val()-1, day.val());
                options.dateFormat = intFormat;
                options.defaultDate = defaultDate;
                options.showTrigger = '<img src="images/calendar.gif" alt="Popup" class="trigger datepick-trigger">';
                // Update selects on choosing date
                options.onSelect = function(dates) {
                    day.val(dates.length ? dates[0].getDate() : ''); 
                    month.val(dates.length ? dates[0].getMonth() + 1 : ''); 
                    year.val(dates.length ? dates[0].getFullYear() : ''); 
                };
                // Validate and update calendar when fields change
                // TODO: Validation
                $.each([day, month, year], function() {
                    this.change(function() {
                        alt.datepick('setDate', new Date(year.val(), parseInt(month.val(), 10)-1, day.val()));
                    });
                });
                alt.val($.datepick.formatDate(intFormat, defaultDate));
                fields = [alt];
                break;
        }
        $.each(fields, function(index, field) {
            field.datepick(options);
        });
    
        // Validate date onchange of date_int field
    }
};var Nameee = Nameee || {};

/**
 * Nameee.closeConfirm
 * Checks for modified form inputs and displays message if user tries to leave the page without submitting
 */
Nameee.closeConfirm = {
    _isDirty: false,
    _isConfirmed: false,

    init: function() {
        // Add set dirty to input onchange
        $('input, textarea, select').change(function() {
            Nameee.closeConfirm._isDirty = true;
        });
        
        $(window).bind('beforeunload', function() {
            Nameee.closeConfirm._isConfirmed = true;
            if (Nameee.closeConfirm._isDirty) {
                return 'You have made changes that have not been saved. If you leave this page, those changes will be lost.';
            }
        });
        
        $(window).bind('unload', function(event) {
            if (Nameee.closeConfirm._isDirty && !Nameee.closeConfirm._isConfirmed) {
                alert('You have made changes that have not been saved.\n' +
                "If you are navigating to a new page, you may be able to use your browser's \"Back\" button to recover your changes.");
            }
        });
        
        $('form').submit(function() {
            $(window).unbind('beforeunload');
        });
    }
};/**
 * JS support for complex fields
 *
 * handlers: beforeaddchunk, afteraddchunk, ondeletechunk, onactivatechunk, onaddchunk
 *
 *
 * @author Svatopluk Svec <svatopluk.svec@webcorp.cz>
 * 
 */

var Nameee = Nameee || {}

Nameee.complexField = {

    init : function( aIdent, removesection )
    {
        //2. init data = render chunks
        $('#'+ aIdent +'_keys').empty();
        Nameee.complexField.initChunks( aIdent, removesection );
    },

    initChunks : function( ident, removesection )
    {
        //console.log( 'starting rendering chunks' );
        var datas = new Array();
        var kdef = Nameee.complexField.getKeyDef(ident);
        var klice = new Object();
        $('#'+ ident +'_data input').each( function(){
            var dys = $(this);
            var aname = dys.attr('name');
            //ident[ameno][index]
            if( aname.indexOf('[') != -1 )
            {
                var ex = aname.split('[');
                var index = ex[2].substring(0,ex[2].length-1); //ident[propname][index][value|label] = val
                var propname = ex[1].substring(0,ex[1].length-1);

                if( typeof( klice[ index ] ) == 'undefined' )
                    klice[ index ] = '';

                if( typeof( kdef[ propname ] ) != 'undefined' )
                {
                    var propsubname = ex[3].substring(0,ex[3].length-1);
                    //console.log( 'doing input '+ aname +' -> index = '+ index +', propname = '+ propname );
                    if( typeof( datas[ index ] ) == 'undefined' )
                        datas[ index ] = new Object();
                    if( typeof( datas[ index ][ propname ] ) == 'undefined' )
                        datas[ index ][ propname ] = new Object();
                    datas[ index ][ propname ][ propsubname ] = dys.val();
                    klice[ index ] += dys.val();
                }
            }
        });
        
        for( var index in klice )
        {
            //opacne. hodnota nas zajima
            $('#'+ ident +'_keys').append( '<span name="'+ klice[index] +'">'+ index +'</span>' );
        }

        //sortable
        Nameee.complexSortable.init( ident, removesection  );

        var o = '';
        for( var idx = 0; idx < datas.length; idx++ )
        {
            //console.log('jedu index '+ idx );
            var ao = Nameee.complexField.renderChunk( ident, datas[ idx ] );
            //console.log('ao je '+ ao );
            Nameee.complexSortable.add(ident, {
                value: idx,
                label: ao
            });
        }
        if( o != ''  )
        {
            $( chunksIdent ).html( o );
        }
    },

    renderChunk : function( ident, adato )
    {
        //        console.log('rendering dato...');
        var chunkTpl = $('#'+ ident +'_chunktemplate').html();
        var tpl = chunkTpl + '';
        for( var propname in adato )
        {
            //            console.log('doing replace propname = '+ propname );
            var lpopis = ( typeof( adato[ propname ]['label'] ) != 'undefined'  ) ? adato[ propname ]['label'] : adato[ propname ]['value'];
            tpl = tpl.replace( '@('+ propname +')', lpopis );
        }
        return tpl;
    },
    
    addChunk : function( ident )
    {
        //        console.log('addchunk for '+ ident );
        //get data from form
        var data = new Object();
        data = Nameee.complexField.getFormData( data, '#'+ ident +'_form input' );
        data = Nameee.complexField.getFormData( data, '#'+ ident +'_form select' );
        data = Nameee.complexField.getFormData( data, '#'+ ident +'_form textarea' );

        //nasazet input fieldy
        var indexObj = $( '#'+ ident +'_index');
        var index = parseInt( indexObj.val() );
        var kdef = Nameee.complexField.getKeyDef(ident);
        var klic = null;
        var aname = null;
        var gname = null;
        for( var ameno in kdef )
        {
            klic += data[ ameno ]['value'];
        }
        if( $('#'+ ident +'_keys span[name='+ klic +']').size() > 0 )
            return false; //primary key uz je, pokousim se pridat to same
        $('#'+ ident +'_keys').append( '<span name="'+ klic +'">'+ index +'</span>' );

        var fname = $('#'+ ident +'_name').val();
        for( var ameno in kdef )
        {
            klic += data[ ameno ]['value'];
            //_label?
            var mLabel = data[ ameno +'__label' ];
            if( typeof( mLabel ) != 'undefined' )
                data[ ameno ]['label'] = mLabel['value'];
            for( var asub in data[ ameno ] )
            {
                aname = fname +'['+ ameno +']['+ index +']['+ asub +']';
                gname = ident +'__'+ index +'__'+ ameno +'__'+ asub;
                var inp = '<input type="hidden" name="'+ aname +'" id="'+ gname +'" value="'+ data[ ameno ][ asub ] +'">';
                $('#'+ ident +'_data').append(inp);
            }
        //index a state
        }

        aname = fname +'[index]['+ index +'][value]';
        gname = ident +'__'+ index +'__index__value';
        $('#'+ ident +'_data').append('<input type="hidden" name="'+ aname +'" id="'+ gname +'" value="'+ index +'">');
        aname = fname +'[status]['+ index +'][value]';
        gname = ident +'__'+ index +'__status__value';
        $('#'+ ident +'_data').append('<input type="hidden" name="'+ aname +'" id="'+ gname +'" value="new">');

        indexObj.val( index + 1 );
        //parse template -> output
        var ao = Nameee.complexField.renderChunk( ident, data);
        //        console.log('ao = '+ ao);
        Nameee.complexSortable.add(ident, {
            value: index, 
            label: ao
        });
    },

    getFormData : function( data, ident )
    {
        $( ident ).each(function()
        {
            var obj = $(this);
            var name = obj.attr('name');
            //select - do label too, (our value is value, not label, but label can be usefull too)
            var val = null;
            var popis = null;

            if( obj.hasClass('ui-autocomplete-input') )
            {
                val = obj.parent().find('#'+name+'-value').val();
                popis = obj.parent().find('#'+name+'-label').val();
            }
            else
            {
                val = obj.val();
                popis = val;
            }
            if( obj.is('select') )
            {
                var selectedElement = obj.get(0);
                popis = selectedElement.options[selectedElement.options.selectedIndex].text; 
            }
            
            
            
            data[ name ] = new Object();
            data[ name ]['value'] = val;
            data[ name ]['label'] = popis; //nepovinne pro pripadny server zpracovac
        //console.log('fmdata name = '+ name +', val = '+ val +', label = '+ popis );
        });
        return data;
    },

    getKeyDef : function( ident )
    {
        var ret = new Object();
        var kdef = $('#'+ ident +'_keydef').val().split(',');
        for( var i = 0; i < kdef.length; i++ )
            ret[ kdef[ i ] ] = true;
        return ret;
    }

};var Nameee = Nameee || {};

/**
 * Nameee.dialog
 * Opens a given page within a modal dialog. Dialog may change parent window's location.
 * Multiple dialogs may be opened, closed in LIFO order.
 */
 /* Todo: Set height of iframe via js */
Nameee.dialog = {
    _isDirty: false,
    
    open: function (id, url, options) {
        // Drop z-index of any already-open dialog and overlay by 10
        parent.$('.ui-dialog, .ui-widget-overlay').each(function(i, el) {
            el = $(el);
            el.css('z-index', el.css('z-index')-10);
        });
        
        options = options || {};
        // Set defaults
        options.width = options.width || 540;
        
        var title = options.title || '';
        delete options.title;

        $dialog = $('#dialog-' + id);

        if ($dialog.size()) {
            $dialog.dialog('option', options);
            $dialog.dialog('open');
        } else {
            var title_class = $.trim('title ' + options.titleClass);
            // Buttons
            var button_html='';

            if (options.buttons) {
                var button, button_class;

                button_html = '<div class="popup-footer forms"><div class="fr">';

                $(options.buttons).each(function(index, element) {
                    button = '<a href="#" data-offset="'+index+'">'+this.text+'</a>';
                    button_class = this.buttonClass ? ' class="'+this.buttonClass+'"' : '';
                    button_html += '<div'+button_class+'><div class="submit-inner">'+button+'</div></div>';
                });

                button_html += '</div></div>';
                var buttons = options.buttons;

                $('body').delegate('#dialog-'+id+' .popup-footer .fr a', 'click', function(e) {
                    var idx = $(this).attr('data-offset');
                    buttons[idx].click.call(this, e);
                });
                
                delete options.buttons;
            }
            
            var html = $('<div id="dialog-'+id+'" class="UI-Dialog">'+
                       '<div class="Top"><h2 class="'+ title_class +'">'+title+'</h2></div>'+
                       '<iframe id="iframe-'+id+'" src="'+url+'" scrollbar="no" marginwidth="0" marginheight="0" hspace="0" ></iframe>'+
                       button_html+
                       '</div>');

            options.closeText = '';
            options.modal = true;

            if (options.closeConfirm) {
                delete options.closeConfirm;
                // Add set dirty to input onchange
                $('iframe', html).load(function() {
                    $('input, textarea, select', this.contentDocument).change(function() {
                        Nameee.dialog._isDirty = true;
                    });

                    html.bind('dialogbeforeclose', function() {
                        if (Nameee.dialog._isDirty) {
                            return confirm('You have made changes that have not been saved. If you leave this page, those changes will be lost.');
                        }
                    });
                });
            }

            options.beforeClose = function(event, ui) {
                // If multiple dialogs open, check this is the top one
                var z = parent.$('#'+event.target.id).parents('.ui-dialog').css('z-index');
                if (z < 1000) {
                    return false;
                }
                return true;
            };
            
            options.close = function() {
                $(this).undelegate();
                $(this).remove();
                // Increase other dialogs and overlays by 10
                parent.$('.ui-dialog, .ui-widget-overlay').each(function(i, el) {
                    el = $(el);
                    el.css('z-index', parseInt(el.css('z-index'), 10)+10);
                });
            };

            options.draggable = false;
            options.resizable = false;

            html.dialog(options);
        }
    },

    close: function (id) {
        var dialog = (parent ? parent.$('#dialog-'+id) : $('#dialog-'+id));
        dialog.dialog('close');
    },
    
    redirect: function (url) {
        document.location = url;
    },

    updateValue: function (id, value) {
        $('#'+id).val(value);
    }
};var Nameee = Nameee || {};

/**
 * Nameee.expanding
 * Expands a textbox as text is entered
 */
Nameee.expanding = {
    init: function($element, maxHeight) {

        if (typeof $element == 'string') {
            $element = $('.' + $element);
        }
        
        $element.one('focus', function() {
                    $(this).css('max-height', maxHeight + 'px')
                           .elastic();
                });
    },

    // init massively
    initMass: function(elements, maxHeight) {

        var length = elements.length;

        for (var i = 0; i < length; i++) {
            var $element = $(elements[i]);
            Nameee.expanding.init($element, maxHeight);
        }
    }

};/*************************************************************************/
/* Extensions for js implementations that are missing required functions */
/*************************************************************************/
if (!Array.prototype.forEach)
{
  Array.prototype.forEach = function(fun)
  {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in t)
        fun.call(thisp, t[i], i, t);
    }
  };
}var Nameee = Nameee || {};

/**
 * Nameee.fuzzyTime
 * Converts a timestamp into a friendly string
 */
Nameee.fuzzyTime = {
    fuzzy: [
        {limit: 0, words: {single: 'About a year ago', plural: 'About [ago] years ago', seconds: 31449600}},
        {limit: 31449600, words: {single: 'About a month ago', plural: 'About [ago] months ago', seconds: 2592000}},// Less than 12 months
        {limit: 2592000, words: {single: 'About a week ago', plural: 'About [ago] weeks ago', seconds: 604800}}, // Less than 4 weeks
        {limit: 604800, words: {single: 'About a day ago', plural: 'About [ago] days ago', seconds: 86400}}, // Less than 7 days
        {limit: 86400, words: {single: 'About an hour ago', plural:'About [ago] hours ago', seconds: 3600}}, // Less than 24 hours
        {limit: 1800, words: 'A few minutes ago'}, // Less than 30 minutes
        {limit: 190, words: 'About a minute ago'}, // Less than 190 seconds
        {limit: 40, words: 'A few seconds ago'} // Less than 40 seconds
    ],

    init: function(el) {
        var $element = $(el),
            timestamp = new Date(el.title * 1000);
            
        if (!isNaN(timestamp.getTime())) {
            $element.attr('title', timestamp.toLocaleDateString() + ' ' + timestamp.toLocaleTimeString());

            Nameee.fuzzyTime._replace(el, timestamp.getTime() / 1000);
        }
    },
        
    _replace: function(el, timestamp) {
        var ago = (Math.round(new Date().getTime() / 1000)) - timestamp;

        var num, phrase, timeout;
        Nameee.fuzzyTime.fuzzy.forEach(function(item) {
            if (ago < (item.limit) || item.limit == 0) {
                timeout = item.limit;
                if (item.words instanceof Object) {
                    num = Math.round(ago/item.words.seconds);
                    if (num > 1) {
                        phrase = lm(item.words.plural, num);
                        phrase = phrase.replace('[ago]', num);
                    } else {
                        phrase = lm(item.words.single);
                    }
                } else {
                    phrase = lm(item.words);
                }
            }
        });

        $(el).text(phrase);

        if (timeout) {
            window.setTimeout(
                function(){
                    Nameee.fuzzyTime._replace(el, timestamp);
                },
                (Math.min(timeout, 3600)*1000)
            );
        }
    },

    initAll: function($elements) {
        if (typeof $elements == 'string') {
            $elements = $('.' + $elements);
        }

        var length = $elements.length;
        for (var i = 0; i < length; i++) {
            Nameee.fuzzyTime.init($elements[i]);
        }
    }
};var Nameee = Nameee || {};

/**
 * Nameee.imageUpdate
 * Uploads an image from an open dialog by submitting the given form, replaces the current image and closes the dialog.
 * 
 * Note: Due to being unable to set the Accept header, the Content-Type header in the response *must* be text/html. If not,
 * FF and IE (at least) will offer the response for download
 */
Nameee.imageUpdate = {
    upload: function (form, dialog, id) {
        var temp = $('#'.form);
        $('#'+form).ajaxSubmit({
            dataType: 'text', // json
            success: function(responseText) {
                // Response is assumed to be html because some browsers force a download on json - am unable to change accept header
                responseText = $.parseJSON(responseText.replace(/^<head><\/head>[\s\S]{0,2}<body>/i,'').replace(/(<\/pre>)?<\/body>$/i,''));
                if (responseText.success) {
                    parent.$('#'+id).attr('src', responseText.url);
                    parent.$('#dialog-'+dialog).dialog('close');
                } else {
                    var error_id = form+'-error';
                    if ($('#'+error_id).size()) {
                        $('#'+error_id).text('An error occurred: '+responseText.message);
                    } else {
                        var error = $('<span id="'+error_id+'"></span>').text('An error occurred: '+responseText.message).addClass('error');
                        error.insertBefore($('#'+form));
                    }
                }
            }
        });
    }
};var Nameee = Nameee || {};

/**
 * Nameee.inlineEdit
 * Allows a value to be edited inline. A callback is called when input loses focus.
 */
Nameee.inlineEdit = {

    saveData: function (element, value, saveUrl, descriptionTitle) {
        var ajaxParams = {
            type: 'POST',
            url: saveUrl,
            data: {text: value}
        };

        $.ajax(ajaxParams);

        if (value.length == 0) {
            value = descriptionTitle;
        }

        element.text(value);

        if (element.text() != descriptionTitle) {
            element.tipsy({gravity: 'w'});
        }
    },

    _onBlur: function (el, edit, callback) {
        var val = edit.val();
        el.css('display', 'inline-block')
          .text(val);
        callback(el, val);
        edit.remove();
    },

    openText: function (id, callback) {
        var $el = $('#' + id);

        if ($('#' + id + '-edit').length > 0) {
            return false;
        }

        $el.css('display', 'none');
        var $input = $('<input>', {
            id: id + '-edit',
            name: id,
            'class': 'UI-Input Text inlineEdit',
            value: $.text($el),
            'blur': function() {
                Nameee.inlineEdit._onBlur($el, $input, callback);
            }
        });

        $el.after($input);
        $('#' + id + '-edit').select().focus();

        return false;
    },
    
    openTextArea: function(id, callback) {
        var $el = $('#' + id);

        if ($('#' + id + '-edit').length > 0) {
            return false;
        }

        $el.css('display', 'none');
        var $textarea = $('<textarea>', {
            id: id + '-edit',
            name: id,
            'class': 'UI-Input Textarea inlineEdit',
            value: jQuery.trim($.text($el)),
            css: {
                top: $el.position().top,
                left: $el.position().left
            },
            'blur': function() {
                Nameee.inlineEdit._onBlur($el, $textarea, callback);
            }
        });

        $el.after($textarea);
        $('#' + id + '-edit').elastic().select().focus();

        return false;
    }
};var Nameee = Nameee || {};

//$(document).ready(function() {
//    Nameee.fuzzyTime.initAll('autotime');
//});

/*************************************************************************/
/* Extensions for js implementations that are missing required functions */
/*************************************************************************/
if (!Array.prototype.forEach)
{
  Array.prototype.forEach = function(fun)
  {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in t)
        fun.call(thisp, t[i], i, t);
    }
  };
};

/* Faux Console by Chris Heilmann http://wait-till-i.com */ 
if(!window.console){
  var console={
      d:{style:''},
      init:function(){
          console.d=document.createElement('div');document.body.appendChild(console.d);
          var a = document.createElement('span');a.innerHTML = '<strong><u>[ NM debug console ]</u></strong>';console.d.appendChild(a);
          a=document.createElement('a');a.href='javascript:console.hide()';a.innerHTML='close';console.d.appendChild(a);
          a=document.createElement('a');a.href='javascript:console.clear();';a.innerHTML='clear';console.d.appendChild(a);
          var id='fauxconsole';
          if(!document.getElementById(id)){console.d.id=id;}console.hide();
       },
       hide:function(){console.d.style.display='none';},
       show:function(){console.d.style.display='block';},
       log:function(o){console.d.innerHTML+='<br/>'+o;console.show();},
       clear:function(){console.d.parentNode.removeChild(console.d);console.init();console.show();},
       /*Simon Willison rules*/
       addLoadEvent:function(func){
           var oldonload=window.onload;if(typeof window.onload!='function'){window.onload=func;}else{window.onload=function(){if(oldonload){oldonload();}func();}};
       }
   };
   console.addLoadEvent(console.init);
}
/**
 * JS support to friend requests etc
 *
 * @author Damian Brhel <damian.brhel@webcorp.cz>
 */

var Nameee = Nameee || {}

Nameee.requests = {
    
    processFriends: function( el, url )
    {
        var user = $(el).parents().filter('li');
        var user = $(user.get(0));
        var userText = $($(user).children('div.MsgCont'));
        
        var block = $(user.parent());
        
        $.ajax({
            type: 'POST',
            url:  url,
            beforeSend: function(){
                Nameee.loader.begin(userText, true);
            },
            success: function(response){
                if ( 0 == response.length ) {
                    user.remove();
                }
                else {
                   response = jQuery.parseJSON(response);
                   userText.html('<p>' + response.message + '</p>');
                   
                   /**
                    * Decrement count
                    */
                   
                   if(response.result == 1) {
                       $counts = $('#DDFri').find('.counts');
                        var actualCount = parseInt($.text($counts));
                        if(actualCount == 1) {
                            $counts.remove();
                        } else {
                            $counts.text(actualCount - 1);
                        }
                   }

                   /**
                    * Remove user
                    */
                   user.delay(1000).fadeOut('slow', function() { 
                       user.remove();
                       if($(block).children().length == 0) {
                           $(block).append('<li><p>' + response.noMoreRequests + '</p></li>').hide().fadeIn('slow');
                       }
                  } );
                }
            }
        });
        
        return false;
    }
};var Nameee = Nameee || {};

/**
 * Nameee.scroll
 * Calls registered functions when page is scrolled to top or bottom
 */
Nameee.scroll = {
    _listeners: {top: [], bottom: [], mid: []},
    _initialised: false,
    addEventListener: function(type, listener, distance, count) {
        if (!Nameee.scroll._initialised) {Nameee.scroll._init();}
        if (Nameee.scroll._listeners[type]) {
            listener = {callback: listener};
            if (count) {listener.count = count; }
            if (type == 'bottom' && distance) {
                listener.distance = distance;
                type = 'mid';
            }
            Nameee.scroll._listeners[type].push(listener);
            return listener;
        }
    },
    
    removeEventListener: function(type, listener) {
        if (Nameee.scroll._listeners[type]) {
            var listener_index;
            Nameee.scroll._listeners[type].forEach(function(item, index) {
                if (item == listener) {
                    listener_index = index;
                }
            });
            if (listener_index == undefined && type == 'bottom') {
                Nameee.scroll._listeners.mid.forEach(function(item, index) {
                    if (item == listener) {
                        listener_index = index;
                    }
                });                
            }
            if (listener_index != undefined) {
                delete(Nameee.scroll._listeners[type][listener_index]);
            }
        }
    },
    
    _init: function() {
        // Initialised to -1 as FF doesn't fire .scroll() if page is not at top when loaded, so will not detect top if direct scrolled
        var currentScrollTop = -1;
        $(window).scroll(function() {
            var listeners = [];
            if (currentScrollTop != $(window).scrollTop()) {
                var delete_listeners = [];
                var type;
                if ($(window).scrollTop() == 0) {
                    listeners = Nameee.scroll._listeners.top;
                    type = 'top';
                } else if ($(window).scrollTop() + $(window).height() == $(document).height()) {
                    listeners = Nameee.scroll._listeners.bottom;
                    type = 'bottom';
                } else {
                    var d;
                    type = 'mid';
                    Nameee.scroll._listeners.mid.forEach(function(item, index) {
                        if (typeof item.count != 'undefined' && item.count == 0) {
                            // Add this here because further down it won't have the right index
                            delete_listeners.push(index);
                        }
                        d = $(document).height() - $(window).height() - item.distance;
                        if (d >= currentScrollTop && d < $(window).scrollTop()) {
                            listeners.push(item);
                        }
                    });
                }
                if (listeners && listeners.length) {
                    listeners.forEach(function(listener, index) {
                        var isDefinedCallback = (
                            typeof listener.callback != 'undefined'
                        );
                        
                        if (isDefinedCallback) {
                            listener.callback.call();
                        }
                        
                        var isDefinedCount = (
                            typeof listener.count != 'undefined'
                        );
                        
                        if (isDefinedCount) {
                            // Mark for removal if run enough times
                            listener.count -= 1;
                            if (listener.count < 1) {
                                delete_listeners.push(index);
                            }
                         }
                    });
                }
                // Delete listeners marked for removal
                $.each(delete_listeners, function(index, item) { delete(Nameee.scroll._listeners[type][item]); });
                currentScrollTop = $(window).scrollTop();
            }
        });
        Nameee.scroll._initialised = true;
    }
};var Nameee = Nameee || {};

/**
 * Nameee.sortable
 * Allows a list to be sorted by drag-and-drop,
 * 
 * if adding item_name and connect_name, sets handlers for dropping items to these containers
 * if item_name is set :
 * store values of members in proprietary format, in one hiddenfield of the name of form variable
 * special chars handling: | -> _|, key=values pairs delimited by ||, " -> \"
 * add and remove parts of sections are delimited by }} ( so, } is coded to _} )
 * 
 */
Nameee.sortable = {

    _serOne: function( arr )
    {
        var ret = '';
        for( var i = 0; i < arr.length; i++ )
        {
            ret += '||'+ arr[i][0] +'='+ arr[i][1];
        }
        if( ret != '' )
            ret = ret.substr(2);
        return ret;
    },

    _serialize: function( arr )
    {
        var ret = Nameee.sortable._serOne( arr['add'] ) +'}}'+ Nameee.sortable._serOne( arr['remove'] );
        return ret;
    },
    _decodeMember: function( serText )
    {
        var ret = new Array();
        if( serText == '' )
            return ret;

        var ex = serText.split('||');
        for( var i = 0; i < ex.length; i++ )
        {
            var sp = ex[i].indexOf('=');
            var value = Nameee.sortable._decode( ex[i].substring(0, sp) );
            var label = Nameee.sortable._decode( ex[i].substr(sp+1) );
            ret[i] = { 0 : value, 1 : label };
        }
    },

    _decodeSections: function( serText )
    {
      if( serText == '' )
      {
          return {'add' : new Array(), 'remove' : new Array() };
      }
      var stex = serText.split('}}');
      //first: add, then remove
      return { 'add' : stex[0], 'remove' : stex[1] };
    },

    init: function (id, item_name, connect_name) {
        
        var containerId = '#'+ id;

        if( item_name != null && item_name != '' )
        {
            var vals = $( containerId +'-value').val();
            if( vals != '' && vals != 0 )
            {
                $( containerId +'-value').val('');
                //initial vals: setting visualisation
                var secs = Nameee.sortable._decodeSections( vals );
                var ex = secs[ item_name ];
                for( var i = 0; i < ex.length; i++ )
                {
                    var item = new Object();
                    item.value = ex[i][0];
                    item.label = ex[i][1];
                    Nameee.autocomplete._addToList(id,item);
                }
            }
            containerId += '-'+ item_name;
        }
        
        var list = $( containerId );
        list.children('a').click(function(e) {
            e.preventDefault();
        });
        var options = {
            placeholder: 'UI-RoundBlock Placeholder',
            forcePlaceholderSize: true,
            update: function() {
                Nameee.sortable._update(list, id, item_name);
            }
        };
        if ( connect_name != null && connect_name != '' ) {
            options.connectWith = '#'+ id +'-'+ connect_name;
        }
        list.sortable(options);
    },

    //update for extended list (value=label)
    //list, fscmembers, add / remove
    _update: function (list, id, item_name ){
        //console.log( 'update() : id = '+ id +', item_name = '+ item_name );
        // Only do if values field exists
        var values = [];
        list.children().each(function (i, el) {
            // Remove base from id to extract item id
            var avalue = el.id.substr(id.length+1);
            if( avalue > 0 )
            {
                values.push( { 0 : avalue, 1 : '' } ); //id is suficcient when selecting from defined list member
//                console.log('pushing '+ avalue +' = nill' );
            }
            else
            {
                //new list member - remember label too
                var alabel = $(el).find('span[name=ilabel]').text();
                alabel = Nameee.sortable._encode(alabel);
                values.push( { 0 : avalue, 1 : alabel } );
//                console.log('pushing '+ avalue +' = '+ alabel );
            }
        });
        if( item_name != '' )
        {
            var selector = '#'+id+'-value';
            //console.log('setting selector ['+ selector +'] = '+ values.join('||') );
            var sv = $(selector);
            
            var secs = Nameee.sortable._decodeSections( sv.val() );
            secs[ item_name ] = value;
            sv.val( Nameee.sortable._serialize( secs ) );
            //console.log( item_name +' values are now: '+ sv.val() );
        }
    },
    _encode: function( text )
    {
      if( text == '' )
        return text;
      text = text.replace(/|/g, '_|' );
      text = text.replace(/}/g, '_}' );
      text = text.replace(/\"/g, '\"' );
      return text;
    },
    _decode: function( text )
    {
      if( text == '' )
        return text;
      text = text.replace(/_|/g, '|' );
      text = text.replace(/_}/g, '}' );
//      text = text.replace(/\\"/g, '"' );
      return text;
    }
};var Nameee = Nameee || {};

/**
 * Nameee.complexsortable
 * Adds support for sortable to complexfield : 
 * sort, transfer between (internal) sections add and remove, 
 * sets flags (state) and order (index) stored data in id_data element
 * v2: storno items are flagged, not moved to sub section
 */
Nameee.complexSortable = {

    statusClasses : 'Blue Grey',
    statusClassEdited : 'Blue',
    statusClassStorno : 'Grey',

    //id: container id, item_name : sortable part name, items : items inside, connect_name : name of second container, (if needed)
    init: function ( id, removesection ) {
        
        if( removesection )
        {
            Nameee.complexSortable.sectionInit( id, '_chunks-std', '_chunks-sub' );
            Nameee.complexSortable.sectionInit( id, '_chunks-sub', '_chunks-std' );
        }
        else
            Nameee.complexSortable.sectionInit( id, '_chunks-std', null );
    
    //test na [] vs __
    /*
    var cmeno = '#'+ id +'_data';
    var ameno = 'kokos[0][index][value]';
    var gmeno = 'kokos__0__index__value';
    $(cmeno).append('<input type="hidden" name="'+ ameno +'" id="'+ ameno +'" value="666">');
    $(cmeno).append('<input type="hidden" name="'+ gmeno +'" id="'+ gmeno +'" value="777">');
    //console.log('ameno val = '+ $('#'+ ameno).val() );
    //console.log('gmeno val = '+ $('#'+ gmeno).val() );
*/
    },
    
    sectionInit : function( id, section_name, connectedsection_name )
    {
        //first container
        var list = $( '#'+ id + section_name );
        list.children('a').click(function(e) {
            e.preventDefault();
        });
        var options = {
            placeholder: 'ui-state-highlight',
            forcePlaceholderSize: true,
            update: function() {
                Nameee.complexSortable._update( id );
            }
        };
        if( connectedsection_name != null )
            options.connectWith = id + connectedsection_name;
        list.sortable( options );//apply standard jq sortable to that obj
    },

    //update for extended list, writes indexes = sort applied to data behind
    _update: function ( id  ){
        // Only do if values field exists: write indexes to hidden fields
        var activeList = $( '#'+ id +'_chunks-std' ); //writes indexes.
        var stornoList = $( '#'+ id +'_chunks-sub' ); //does nothing. state tells it all

        var actIndex = 0;
        activeList.children().each(function (i, el) {
            var aindex = $(el).attr('name').substr( 3 ); //cs
            var asel =  '#'+ id +'__'+ aindex +'__index__value';
            //console.log('set '+ asel +'.value = '+ actIndex );
            $(asel).val(actIndex++); //zmena property index.
        });
    //console.log( 'index of idx 0 member = '+ $('#'+ id +'__0__index__value').val() );
    },

    add: function(id, item) {
        //        console.log('complexsortable: adding item (value='+ item.value +',label='+ item.label +')');
        var list = $('#'+id+'_chunks-std');
        //duplicity check, for add and remove lists
        if( list.parent().find('div[name=cs_'+ item.value +']').size() > 0 )
            return false;
        var list_item = $('<a title="Titulek" class="link-box lb-h18 lb-noimg" href="#"><span class="right lb-fs11"><span class="ico">'+item.label+'</span></span></a>');
        list_item = $( '<div name="cs_'+ item.value +'" class="UI-RoundBlock Blue"><div class="Top"><div class="Bottom"><span name="ilabel">'+ item.label  +'</span> <a style="float:right;" onclick="return Nameee.complexSortable.remove(this,\''+ id +'\');" title="remove" class="link-box lb-h18 lb-noimg" href="javascript:void(0);">&nbsp;x&nbsp;</a></div></div></div>' );

        list.append(list_item.attr('id', id+'_chunkitem-'+item.value));
        list.sortable('refresh');
        Nameee.complexSortable._update( id );
    },

    //v1: remove = move to 'oposite' list
    //v2: remove = set disabled visual type, then maybe move
    remove: function( domobj, id )
    {
        var obj = $(domobj).parent().parent().parent(); //proste smazani a update datove prezentace seznamu

        //state change
        var isStorned = obj.hasClass( Nameee.complexSortable.statusClassStorno );
        var newClass = '';
        var newStatus = '';
        if( isStorned )
        {
            newClass = Nameee.complexSortable.statusClassEdited;
            newStatus = 'edited';
        }
        else
        {
            newClass = Nameee.complexSortable.statusClassStorno;
            newStatus = 'storno';
        }

        //find index for change apply in data

        var index = obj.attr('name').substr(3); //cs_

        //class = visual apply
        obj.removeClass( Nameee.complexSortable.statusClasses).addClass(newClass);

        //data apply
        $('#'+ id +'__'+ index +'__state__value').val(newStatus); //state
        $('#'+ id +'__'+ index +'__index__value').val('-1'); //index=-1 = from outer space..

        var list = obj.parent();
        var listType = list.attr('id').substr( id.length + 8 ); //_chunks-

        //autocheck for removableSection
        var tgtListType = ( listType == 'std' ) ? 'sub' : 'std';
        var tgtlist = $( '#'+ id +'_chunks-'+ tgtListType );

        if( tgtlist.size() > 0 )
        {
            //console.log('inc listtype = '+ listType +', tgt = '+ tgtListType);
            //move it
            obj.appendTo( tgtlist );
        }

        Nameee.complexSortable._update( id );
    },
    
    _encode: function( text )
    {
        if( text == '' )
            return text;
        text = text.replace(/|/g, '_|' );
        text = text.replace(/}/g, '_}' );
        text = text.replace(/\"/g, '\"' );
        return text;
    },

    _decode: function( text )
    {
        if( text == '' )
            return text;
        text = text.replace(/_|/g, '|' );
        text = text.replace(/_}/g, '}' );
        //      text = text.replace(/\\"/g, '"' );
        return text;
    }

};var Nameee = Nameee || {};

/**
 * Nameee.thumbnails
 * Sends given url to a script and calls a callback with the response
 */
Nameee.thumbnails = {
    extract: function (url, script, callbackBeforeSend, callbackSuccess, targetId) {
        $.ajax({
            async: false,
            data: {url: url},
            url: script,
            beforeSend: function(url) {
                if (callbackBeforeSend) {
                    callbackBeforeSend(targetId, url);
                }
            },
            success: function(data) {
                callbackSuccess(targetId, data);
            }
        });
    }
};/**
 * JS support to board module
 *
 * @author Martin Ptacel <ptacek@praguebest.cz>
 */

var Nameee = Nameee || {}

Nameee.board = {

    showFormNewTopic: function( source )
    {
        $('#boardNewTopic').toggle();

        return false;
    }

};/**
 * Support for votes on page
 *
 * @author Jan Hrouza <hrouza@awebsys.cz>
 */

var Nameee = Nameee || {};

Nameee.comments = {
    
    /**
     * Comments textareas are now elastic + sent by enter
     */
    init: function() 
    {
        // AJAX odesilani formulare - vlozeni komentare
        
        $('form.formInsertComment').keypress(function(e) {
            srcTextArea = $('#' + e.target.id);
            var code = (e.keyCode ? e.keyCode : e.which);
            // before propagation
            var commentLength = jQuery.trim(srcTextArea.val()).length;
            
            // just enter
            if(code == 13 && !e.shiftKey) {
                e.preventDefault();
                e.stopPropagation();
                if (commentLength > 0)
                {
                    srcForm = $('#'+e.currentTarget.id);
                    // after the form was sent, preserve it
                    srcArea = $('#'+e.target.id);
                    allForms = $('form.formInsertComment');
                    $.ajax({
                        type: 'POST',
                        url: srcForm.attr('action'),
                        data: srcForm.serialize(),
                        beforeSend: function(){
                            $('textarea[name=commentText]', allForms).attr('disabled', true);
                            $('input[name=submit]', allForms).attr('disabled', true);
                            var srcAreaHeight = srcArea.height();
                            if ( srcAreaHeight < 20 )
                            {
                                srcArea.css('background', 'url(/img/tiny-loading.gif) white 99% 50% no-repeat');
                            }
                            else
                            {
                                srcArea.css('background', 'url(/img/tiny-loading.gif) white 99% 95% no-repeat');
                            }     
                        },
                        success: function(msg){
                            $('textarea[name=commentText]', allForms).removeAttr('disabled');
                            $('input[name=submit]', allForms).removeAttr('disabled');
                            srcArea.val('');
                            //$('.UI-Button.Pri', form).hide();
                            srcArea.css({
                                'background-color': 'white',
                                'background-image':'none'
                            });
                            var $li = $('#li_' + srcForm.attr('name'));
                            $li.before(msg);
                            Nameee.fuzzyTime.initAll($li.parent().find('span.autotime'));
                        }
                    });
                }
            }
            // after propagation
            commentLength = jQuery.trim(srcTextArea.val()).length;
            if (commentLength == 0)
            {
                srcTextArea.val('');
            }
        });

        Nameee.fuzzyTime.initAll($('span.autotime'));

        var textareas = $('form.formInsertComment').find('textarea'),
            length = textareas.length;

        var $textarea;

        for (var i = 0; i < length; i++) {
            $textarea = $(textareas[i]);

            $textarea.placeholder();
            Nameee.expanding.init($textarea, 100);
        }

    },

    /**
     * Zobrazi komentare skryte pomoci CSS
     */
    cssShow: function(el)
    {
        var $parent = $(el).parent();
        $parent.parent().children('li.hide').show();
        $parent.hide();

        return false;
    },

    /**
     * Zobrazi textareu po kliknuti na odkaz "Pridat komentar"
     */
    cssFormShow: function(name)
    {
        $('#' + name).show();
        $('#' + name + '-commentText').focus();
        return false;
    },

    /**
     * AJAX nacteni dalsi stranky komentaru
     */
    loadNextPage: function(domId, url, contentType, contentId, nextToken)
    {
        $.ajax({
            type: 'POST',
            url: url,
            data: 'commentContentType=' + contentType + '&contentId=' + contentId + '&nextToken=' + nextToken,
            beforeSend: function(){
                Nameee.loader.begin('#' + domId, true);
            },
            success: function(msg){
                $('#' + domId).after(msg).remove();
                Nameee.fuzzyTime.initAll($('span.autotime'));
            }
        });
        
        return false;
    },

//    postComment: function(form) {
//
//
//        $(form).find('.UI-Input.Submit').attr('disabled', 'disabled');
//
//        $.post($(form).attr('action'),
//               $(form).serialize(),
//               function (data) {
//                   $(data).insertBefore($(form).closest('li'));
//                   $(form).find('textarea').val('');
//                   $(form).find('.UI-Button.Pri').hide();
//                   $(form).find('.UI-Input.Submit').removeAttr('disabled');
//                   Nameee.fuzzyTime.initAll('autotime');
//               });
//
////         return false;
//    },

    deleteComment: function(el, url, itemName)
    {
        var comment = $(el).parent();
        $.ajax({
            type: 'POST',
            url:  url,
            data: 'itemName=' + itemName,
            beforeSend: function(){
                Nameee.loader.begin(comment, true);
//                Nameee.loader.begin('#' + domId, true);
            },
            success: function(msg){
                if ( 0 == msg.length ){
                    comment.remove();
                }
                else{
                    comment.html(msg);
                }
            }
        });

        return false;
    }
};

/**
 * Zajisteni inicializace komentaru
 */
$(function(){
    Nameee.comments.init();
});
/**
 * JS support to board module
 *
 * @author Martin Ptacel <ptacek@praguebest.cz>
 */

var Nameee = Nameee || {}

Nameee.democracy = {

    showFormSuggestTopic: function( source )
    {
        $('#democracySuggestTopic').toggle();
        return false;
    }

};/**
 * Support file for flash webcam module
 *
 * @author Jan Juricek <jan@nameee.com>
 */

var Nameee = Nameee || {};

Nameee.fwk = {
    init: function(containerId, width, height, jsCallback, jsTrigger, snapURL) {
        
        var flashvars = {
            maskWidth: width,
            maskHGeight: height,
            maskEnabled: true,
            lockSides: false,
            snapURL: snapURL,
            buttons: true
        };

        if (jsCallback) {
            flashvars.jsFunction = jsCallback;
        }

        if (jsTrigger) {
            flashvars.jsSnap = jsTrigger;
        }

        



        var params = {};
        var attributes = {};
        swfobject.embedSWF(
            "/swf/fwk/snap.swf",
            containerId,
            width, height,
            "9.0.0",
            "/swf/expressInstall.swf",
            flashvars,
            params,
            attributes);
            
    },

    success: function( data )
    {
        alert(data);
    }
};/**
 * JS support to groups module
 *
 * @author Jakub Zapletal <zapletal@synergio.cz>
 */

var Nameee = Nameee || {};

Nameee.groups = {};

Nameee.groups.deleteDialog = {
    show : function(url) {
        Nameee.ajaxDialog.open('delete-dialog', url);
        void(0);
    },

    confirm : function() {
        document.forms["groups-delete-form"].submit();
        // console.log("send");
        return false;
    }
};


Nameee.groups.groupInformation = {
    onMainCategorySelect : function() {
        var mainCategoryId = $('#mainCategorySelect').val();
        $.get(
            "/run/groups/index/fetchSubcategories",
            {
                'categoryId' : mainCategoryId
            },
            Nameee.groups.groupInformation.fetchSubcategoryResponse,
            "json"
            );

    },

    fetchSubcategoryResponse : function(data) {
        var subcategorySelect = $('#subcategorySelect');
        Nameee.groups.groupInformation.clearSubcategorySelectBox();

        for(var subcategoryId in data) {
            var subcategoryName = data[ subcategoryId ];
            var option = document.createElement('option');
            option.value = subcategoryId;
            option.innerHTML = subcategoryName;
            subcategorySelect.append( option );
        }
    },

    clearSubcategorySelectBox : function() {
        var subcategorySelect = $('#subcategorySelect');
        subcategorySelect.empty();
    }
};

Nameee.groups.imageDialog = {
    show : function(groupId) {
        Nameee.ajaxDialog.open('groups-logo', '/run/groups/dialog/logo/?groupId=' + groupId);
    },

    close : function() {
        Nameee.dialog.close('groups-logo-form');
        return false;
    },
    
    upload : function() {
        Nameee.imageUpdate.upload('groups-logo-form', 'groups-logo', "groups-logo");
        return false;
    }
};

Nameee.groups.contentTabs = {
    create : function(defaultTab) {
        $("#detail-content").tabs({
            selected : defaultTab,
            select : Nameee.groups.contentTabs.onSelect
        });
    },

    onSelect : function(event, ui) {
        var className = ui.tab.className;
        if(className == "showWithLeftMenu") {
            $("#group-left-menu").show();
        } else {
            $("#group-left-menu").hide();
        }
    }
};


Nameee.groups.informationTextarea = {
    show : function() {
        Nameee.inlineEdit.openTextArea("information-textarea", Nameee.groups.informationTextarea.onUpdate);
    },

    onUpdate : function() {
        // console.log(arguments);
    }
};

Nameee.groups.generalInformation = {
    updatePage : function(name, description, category, subcategory) {
        $(".group-name").text(name);
        $(".group-description").text(description);
        $(".group-category").text(category);
        $(".group-subcategory").text(subcategory);
    }
}

Nameee.groups.generalInformationForm = {
    show : function(groupId) {
        $("#content-information-general").load( '/run/groups/index/generalInformationForm/?groupId=' + groupId);
        void(0);
    },

    submit : function(groupId) {
        var name = $("#group-informations-form [name=name]").val();
        var description = $("#group-informations-form [name=description]").val();
        var categoryName = $("#group-informations-form [name=category_id] :selected").text();
        var subcategoryName = $("#group-informations-form [name=subcategory_id] :selected").text();
        
        $("#group-informations-form").ajaxSubmit({
            success : function(content) {
                var contentNode = $("#content-information-general");
                contentNode.html(content);
                // if form was physiccaly posted succesfully, than update page
                if (contentNode.find("#group-informations-form").size() == 0) {
                    Nameee.groups.generalInformation.updatePage(name, description, categoryName, subcategoryName);
                } 
            }
        });
        return false;
    },

    cancel : function(groupId) {
        this.hide(groupId);
        return false;
    },

    hide : function(groupId) {
        $("#content-information-general").load('/run/groups/index/generalInformationContent/?groupId=' + groupId);
    }
};


Nameee.groups.contactInformation = {
    updateWebsites : function(groupId) {
        $(".group-websites").load("/run/groups/index/contactWebsites/?groupId=" + groupId);
    }
};


Nameee.groups.contactInformationForm = {
    show : function(groupId) {
        $("#content-information-contacts").load( '/run/groups/index/contactsInformationForm/?groupId=' + groupId);
        void(0);
    },

    submit : function(groupId) {
        //        var website = $("#group-contacts-form [name=website]").val();
        $("#group-contacts-form").ajaxSubmit({
            success : function(content) {
                var contentNode = $("#content-information-contacts");
                contentNode.html(content);
                if(contentNode.find().size() == 0) {
                    Nameee.groups.contactInformation.updateWebsites(groupId);
                }
            }
        })
        return false;
    },

    cancel : function(groupId) {
        this.hide(groupId);
        // console.log("cancel");
        return false;
    },

    hide : function(groupId) {
        $("#content-information-contacts").load( '/run/groups/index/contactsInformationContent/?groupId=' + groupId);
    }
};


Nameee.groups.memberList = {
    show : function(type) {
        // console.log(type);
        void(0);
    }
};

Nameee.groups.ownerDialog = {
    show : function() {
        // console.log("ownerDialog");
    }
};

Nameee.groups.adminsDialog = {
    show : function() {
        // console.log("adminsDialog");
    }
};/**
 * Homepage scripting
 *
 * @author Jan Juricek <jan@nameee.com>
 */

var Nameee = Nameee || {};

Nameee.hp = {

};/**
 * Utility class that should be used to create and handle loading parts of
 *  HTML documents and manipulating with the DOM after AJAX calls
 *
 * @author Jan Juricek <jan@nameee.com>
 * @author Svatopluk Svec <svatopluk.svec@webcorp.cz>
 * @author Jan Komarek <jan.komarek@webcorp.cz>
 * @author David Pilny <david.pilny@webcorp.cz>
 */

var Nameee = Nameee || {}

Nameee.loader = {

    requests: [],

    addRequest: function(request) {
        Nameee.loader.requests.push(request);
    },

    stopRequests: function()
    {
        jQuery.map(
            this.requests,
            function (req) {
                req.abort();
            }
        );

        Nameee.loader.requests = [];
    },

    begin: function(targetId, keepDimensions, tinyType, darkType) {
        var img = '';
        var dimensions = '';

        if (tinyType) {
            img = '/img/tiny-loading.gif';
            dimensions = 'width:16px;height:11px;';
        } else {
            if (darkType) {
                img = '/img/fancybox-loading.gif';
                dimensions = 'width:40px;height:40px;';        
            } else {
                img = '/img/loading.gif';
                dimensions = 'width:25px;height:25px;';
            }
        }

        if (keepDimensions == true) {
            $(targetId).html(''
                +   '<div style="width:' + $(targetId).width().toString() + 'px;'
                +               'height:' + $(targetId).height().toString() + 'px;'
                +               'min-height:40px;'
                +               'background:url(' + img + ') no-repeat center;'
                +               '">'
                +   '</div>'
            );
        } else {
            $(targetId).html(''
                +   '<img src="'+img+'" alt="Loading" style="'+dimensions+'" class="loading" />');
        }

    },

    endSuccess: function(targetId) {

    },

    endFailure: function(targetId) {

    },

    loadInsideDialog: function(dialog, url) {

        Nameee.loader.begin(
            $(dialog).children('.Content'),
            true
        );

        $.ajax({
            method: 'GET',
            url: url,
            cache: false,
            success: function(content){
                dialog.html(content);
            },
            failure: function(content) {
//                dialog.html('asf');
            }
        });
    },

    loadImageInsideContainer: function (container, url, darkType) {
        Nameee.loader.begin(
            $(container),
            true,
            false,
            darkType
        );
        
        $('body').append(
            '<img id="image-load-waiting" src="'+url+'" style="display:none" />'
        );
         
        $('#image-load-waiting').load(function() {
            $('#image-load-waiting').remove();
            $(container).html(
                '<img src="'+url+'"/>'
            );
        });
    },

    _loadFormResponse: function(form, callback, loader, type) {
        if (typeof loader != 'undefined') {
            Nameee.loader.begin(
                loader,
                true
            );
        }

//        console.log(form);
//        console.log($(form));

        var formdata = $(form).serialize();
        var formAction = $(form).attr('action');

//        console.log(formdata);
//        console.log(formAction);

        $.post(
            formAction,
            formdata,
            function (data) {
                callback(data);
            },
            type
        );

        return false;
    },

    loadFormResponse: function(targetId, form) {
        return Nameee.loader._loadFormResponse(
            form,
            function (data) {
                $('#' + targetId).prepend(data);
                jQuery(form)[0].reset();

                if (Nameee.fuzzyTime) {
                    Nameee.fuzzyTime.initAll('autotime');
                }
            }
        );
    },

    /**
     * @deprecated
     */
    loadFormReponseInsideDialog: function(dialog, form) {
        return Nameee.loader.loadFormResponseInsideDialog(dialog, form);
    },

    loadFormResponseInsideDialog: function(dialog, form) {
        return Nameee.loader._loadFormResponse(
            form,
            function (data) {
                dialog.html(data);
            },
            $(dialog).children('.Content')
        );
    },

    /**
     * @deprecated
     */
    loadFormReponseInsideAnythink: function(conteiner, form) {
        return Nameee.loader.loadFormResponseInsideContainer(conteiner, form);
    },

    loadFormResponseInsideContainer: function(container, form) {
        return Nameee.loader._loadFormResponse(
            form,
            function (data) {
                container.html(data);
            },
            $(container)
        );
    },

    /**
     * @deprecated
     */
    loadJsonFormReponseInsideDialog: function(dialog, form, scsCallback, errCallback) {
        return loadJsonFormResponseInsideDialog(dialog, form, scsCallback, errCallback);
    },

    loadJsonFormResponseInsideDialog: function(dialog, form, scsCallback, errCallback) {
        if (!(scsCallback instanceof 'function')) {
            scsCallback = function(){};
        }
        if (!(errCallback instanceof 'function')) {
            errCallback = function(){};
        }

        return Nameee.loader._loadFormResponse(
            form,
            function (data) {
                data = eval(data);
                dialog.html(data.content);

                if (data.status == true) {
                    scsCallback(data);
                } else {
                    errCallback(data);
                }
            },
            $(dialog).children('.Content'),
            'json'
        )
    }

};/**
 * Utility class allowing to load "next page" of results after reaching
 *  bottom of the page via AJAX
 *
 * @author Jan Juricek <jan@nameee.com>
 */

var Nameee = Nameee || {};


Nameee.pager = {

    _listener: {},
    _maxReloadCount: {},
    _loadCount: {},
    _cycleAutoLoad: {},

    afterLoad: function(){},

    init: function(domId, maxReloadCount, afterLoadCallback, cycleAutoLoad) {
        if (typeof(afterLoadCallback) == 'function'){
            Nameee.pager.afterLoad = afterLoadCallback;
        }

        if (typeof maxReloadCount != 'undefined') {
            //console.log('set:'+maxReloadCount);
            Nameee.pager._maxReloadCount[domId] = maxReloadCount;
        }

        if (typeof cycleAutoLoad == 'undefined') {
            cycleAutoLoad = false;
        }
        //console.log('setcycle'+cycleAutoLoad);
        Nameee.pager._cycleAutoLoad[domId] = cycleAutoLoad;

    },

    _initAutoClick: function(domId) {
        if (Nameee.scroll) {
//            alert(this._getLink(domId).html());
            Nameee.pager._listener[domId] = Nameee.scroll.addEventListener(
                'bottom',
                function() {
                    Nameee.pager.loadNext(domId);
                },
                0
            );

//           Nameee.pager.getLink(domId).bind('click', Nameee.pager.loadNext(domId));


         }
    },

    _incrementLoadCount: function(domId) {
        if (typeof Nameee.pager._loadCount[domId] == 'undefined') {
            Nameee.pager._loadCount[domId] = 0;
        } else {
            Nameee.pager._loadCount[domId] += 1;
        }
    },

    _handleAutoClickBind: function(domId) {
        Nameee.pager._incrementLoadCount(domId);

        var cycle = Nameee.pager._cycleAutoLoad[domId];
        var loadCount = Nameee.pager._loadCount[domId];
        var maxReloadCount = Nameee.pager._maxReloadCount[domId];
        var hasAutoClick = loadCount == 0 && maxReloadCount > 0;
        var reset = loadCount != 0 && loadCount % maxReloadCount == 0;
//        console.log('domId:'+domId);
//        console.log('loadCount:'+loadCount);
//        console.log('maxReloadCount:'+maxReloadCount);
//        console.log('hasAutoClick:'+hasAutoClick);
//        console.log('reset'+reset);
//        console.log('cycle:'+cycle);
        //console.log('reset:'+reset);
        if (reset) {
            //Moved removing listener inside self from scroll, because
            //scroll tries to decrement the counter each time the bottom
            //is reached without knowing whether the previous request
            //has already been processed causing mismatch when we want
            //to enable auto-load by chunks - 10 and stop, 10 and stop
            Nameee.scroll.removeEventListener(
                'bottom',
                Nameee.pager._listener[domId]
            );

            if (cycle) {
                Nameee.pager._loadCount[domId] = undefined;
            }
        }

//        console.log('cycle:'+cycle);
//        console.log('load:'+loadCount);
//        console.log('max:'+maxReloadCount);
//        console.log('product:'+(loadCount % maxReloadCount));

        if (hasAutoClick) {
            Nameee.pager._initAutoClick(domId);
        }
    },

    loadNext: function(domId) {
        var link = Nameee.pager.getLink(domId);
        if (link.attr('href')) {
            Nameee.pager._handleAutoClickBind(domId);

            var wrapper =  Nameee.pager.getWrapper(domId),
                $contentWrapper = $('#' + domId);

            var request = $.ajax({
                method: 'GET',
                url: link.attr('href'),
                cache: false,
                beforeSend: Nameee.loader.begin(wrapper, false, true),
                success: function(content){
                    wrapper.remove();
                    $contentWrapper.append(content);
                    Nameee.fuzzyTime.initAll($contentWrapper.find('span.autotime'));
                    Nameee.pager.afterLoad();
                }
            });
            Nameee.loader.addRequest(request);
        }
    },

    getLink: function(domId) {
        return $('#' + domId + 'npln');
    },

    getWrapper: function(domId) {
        return $('#' + domId + 'np');
    }
};var Nameee = Nameee || {};

Nameee.pager_regular = {
    init: function(domId) {
    },

    loadPage: function(domId, elm) {
        $elm = $(elm);
        var link = $elm.attr('href');
        var wrapper = Nameee.pager_regular.getWrapper(domId);
        $.ajax({
            method: 'GET',
            url: link,
            cache: false,
            dataType: 'xml',
            beforeSend: Nameee.loader.begin(wrapper),
            success: function(xml){
                wrapper.remove();

                if ($(xml).find('paginator').length > 0) {
                    $('#' + domId + 'paginator').replaceWith($(xml).find('paginator').text());
                }
                if ($(xml).find('content').length > 0) {
                    $('#' + domId).append($(xml).find('content').text());
                }
                Nameee.fuzzyTime.initAll('autotime');
            }
        });
    },

    getWrapper: function(domId) {
        return $('#' + domId + 'np');
    }

};/**
 * JS support to pages module
 *
 * @author Jakub Zapletal <zapletal@synergio.cz>
 */
var Nameee = Nameee || {};

Nameee.pages = {};

Nameee.pages.fanList = {
    show : function(url, mode) {
        Nameee.ajaxDialog.open('fanlist', url);
        return false;
    }
};


Nameee.pages.adminsDialog = {
    show : function(url) {
        Nameee.ajaxDialog.open('adminset', url);
        return false;
    }
}


Nameee.pages.ownerDialog = {
    show : function(url) {
        Nameee.ajaxDialog.open('owner', url);
        return false;
    }
}

Nameee.pages.informations = {
    updateBasic : function(name, description, office, phone, openHoursText) {
        $(".pages-name").text(name);
        $(".pages-description").text(description);
        $(".pages-office").text(office);
        $(".pages-phone").text(phone);
        $(".pages-open-hours-text").text(openHoursText);
    }
};

Nameee.pages.detailsForm = {
    show : function(url) {
        $("#pages-details").load(url);
        return false;
    },

    submit : function() {
        $("#detailssetting").ajaxSubmit({
           success : function(content) {
               var contentNode = $("#pages-details");
               contentNode.html(content);
           }
        });

        return false;
    },

    cancel : function(url) {
        $("#pages-details").load(url);
        return false;
    }
};

Nameee.pages.imageDialog = {
    show : function(groupId) {
        Nameee.ajaxDialog.open('pages-logo', '/run/pages/dialog/logo/?id=' + groupId);
    },

    upload : function() {
        Nameee.imageUpdate.upload('pages-logo-form', 'pages-logo', "pages-logo");
        return;
    }
};


Nameee.pages.informationsForm = {
    show : function(url) {
        $("#pages-informations").load(url);
        return false;
    },

    submit : function() {
      var name = $("#informationsetting [name=name]").val();
      var description = $("#informationsetting [name=description]").val();
      var office = $("#informationsetting [name=office]").val();
      var phone = $("#informationsetting [name=phone]").val();

      $("#informationsetting").ajaxSubmit({
            success : function(content) {
                var contentNode = $("#pages-informations");
                contentNode.html(content);
                // if form was physiccaly posted succesfully, than update page
                if (contentNode.find("#informationsetting").size() == 0) {
                    var openHours = $("#pages-informations .open-hours-text")[0].innerHTML;
                    Nameee.pages.informations.updateBasic(name, description, office, phone, openHours);
                }
            }
        });

        return false;
    },

    cancel : function(url) {
        $("#pages-informations").load(url);
        return false;
    }
}

Nameee.pages.openHours = {
    init : function() {
        var instance = this;
        $("#open-hours-fieldset .dayCheckbox").each(function(id, node) {
            var dayEnabled = node.checked;
            var day = node.value;
            instance.toggleDayGroup(day, dayEnabled);
        });

        var isSecondaryEnabled = document.getElementById("pages-open-hours-secondary-checkbox").checked;
        this.toggleSecondaryDays(isSecondaryEnabled);
    },

    toggleDayGroup : function(day, enabled) {
        var openHours = $("#open-hours-fieldset .day-" + day);
        openHours.not(".blocked-secondary").attr("disabled", !enabled);

        if(enabled) {
            openHours.removeClass("blocked-days");
        } else {
            openHours.addClass("blocked-days");
        }
    },

    dayGroupChange : function(checkbox) {
        var isChecked = checkbox.checked;
        var day = checkbox.value;
        this.toggleDayGroup(day, isChecked);
    },

    toggleSecondaryDays : function(enabled) {
        var secondaryHours = $("#open-hours-fieldset .secondary");
        secondaryHours.not(".blocked-days").attr("disabled", !enabled);

        if(enabled) {
            secondaryHours.removeClass("blocked-secondary");
        } else {
            secondaryHours.addClass("blocked-secondary");
        }
    },

    secondaryDaysChange : function(checkbox) {
        var isChecked = checkbox.checked;
        this.toggleSecondaryDays(isChecked);
    }
};/**
 * Support file for a special form field allowing to select a set of users and
 *  send the selected list to the server along with other form field values
 *
 * @author Jan Juricek <jan@nameee.com>
 */

var Nameee = Nameee || {}

Nameee.peoplepicker = {
    brak: function(){
        alert('This shoudn happen');
    },

    getArray: function(checkboxes) {
        var params = [];
        jQuery.each(checkboxes.serializeArray(), function(index,value) {
            params.push(value.value);
        });
        return params;
    },
    init: function(domId, multiChoose){

        $('#PP-' + domId + ' label').click(function(e) {
            var li = $(this).closest('li');
            var cb = $('#' + li.attr('id') + '-cb');
            if (cb.attr('checked')) {
                cb.attr('checked', false);
                li.removeClass('selected');
            } else {
                if (multiChoose) {
                    $('#PP-' + domId + ' li').removeClass('selected');
                    $('#PP-' + domId + '-form input:checkbox:checked').attr('checked', false);
                }
                cb.attr('checked', true);
                li.addClass('selected');
            }
            e.preventDefault();

        });
    },



    updateOpener: function(domId) {
        var selected = Nameee.peoplepicker.getArray($('#PP-' + domId + '-form input:checkbox:checked'));
        var selectedUsers = new Array(selected.length)
        var name;
        var url;
        $('#' + domId).val(selected);
        for (var i = 0; i < selected.length; i++) {
            name = $('#PP-' + domId + '-' +  selected[i] + '-pn').val();
            //url = $('#PP-' + domId + '-' +  selected[i] + '-pu').val();
            selected[i] = name;
        }
        Nameee.peoplepicker.updateOpenerLink(domId,selected);
    },

    updateOpenerLink: function(domId, selected) {
        var prefix = $('#' + domId + '-link').html().split(':')[0];
        var users = '';
        for (var i = 0; i < selected.length; i++) {

        }
        //$('#' + domId + '-link').html(prefix + ': ' + $('#' + domId).val().split(',').length);
        $('#' + domId + '-link').html(prefix + ': ' + selected.join(', '));
    },

    preSelect: function(domId){
        $.each($('#' + domId).val().split(','), function(key, value){
            value = parseInt(value);
            $('#PP-' + domId + '-' + value + '-cb').attr('checked', true);
            $('#PP-' + domId + '-' + value).addClass('selected');
        });
    }
};/**
 * Support file for a special form field allowing to select a set of users and
 *  send the selected list to the server along with other form field values
 *
 * @author Jan Juricek <jan@nameee.com>
 */

var Nameee = Nameee || {}

Nameee.placePicker = {
    _geocoder: null,

    _map: null,

    _marker: null,

    _latlng: null,

    getMarker: function () {

    },

    geocode: function( geocoder, marker, mapWrapper )
    {
        geocoder.geocode({
            'latLng': marker.getPosition()
        }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                    $("#" + mapWrapper + '_ac').val(results[0].formatted_address);
                    $("#" + mapWrapper + '_lat').val(marker.getPosition().lat());
                    $("#" + mapWrapper + '_lon').val(marker.getPosition().lng());
                //              infowindow.setContent(results[0].formatted_address);
                //              infowindow.setPosition(marker.getPosition());
                //              infowindow.open(map);
                //infowindow.
                }
            }
        });
    },

    init: function(mapWrapper, latitude, longitude, zoom) {
        //console.log('initiating gmap ('+ latitude +','+ longitude +')');
        latitude = parseFloat(latitude.replace(',', '.'));
        longitude = parseFloat(longitude.replace(',', '.'));

        var latlng = new google.maps.LatLng(latitude, longitude);
        var options = {
            zoom: zoom,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        Nameee.placePicker._latlng = latlng;

        map = new google.maps.Map(document.getElementById(mapWrapper), options);
        geocoder = new google.maps.Geocoder();
        marker = new google.maps.Marker({
            map: map,
            draggable: true
        });

        Nameee.placePicker._marker = marker;

        map.setCenter(latlng);
        marker.setPosition(latlng);

        Nameee.placePicker.geocode(geocoder, marker, mapWrapper);

        //        infowindow = new google.maps.InfoWindow({
        //              position: event.latLng,
        //              content: event.latLng.toString()
        //            })
        google.maps.event.addListener(map, 'click', function(event) {
            var position = event.latLng;
            $("#" + mapWrapper + '_lat').val(position.lat());
            $("#" + mapWrapper + '_lon').val(position.lng());
            //var location = new google.maps.LatLng(position.lat(), position.lng());

            marker.setPosition(position);
            map.setCenter(position);
            Nameee.placePicker.geocode(geocoder, marker, mapWrapper);
        //            new google.maps.InfoWindow({
        //              position: event.latLng,
        //              content: event.latLng.toString()
        //            }).open(map);
        });

        $("#" + mapWrapper + '_ac').autocomplete({
            //This bit uses the geocoder to fetch address values
            source: function(request, response) {
                geocoder.geocode( {
                    'address': request.term
                }, function(results, status) {
                    response($.map(results, function(item) {
                        return {
                            label:  item.formatted_address,
                            value: item.formatted_address,
                            latitude: item.geometry.location.lat(),
                            longitude: item.geometry.location.lng()
                        }
                    }));
                })
            },
            //This bit is executed upon selection of an address
            select: function(event, ui) {
                $("#" + mapWrapper + '_lat').val(ui.item.latitude);
                $("#" + mapWrapper + '_lon').val(ui.item.longitude);
                var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
                marker.setPosition(location);
                map.setCenter(location);
            }
        });


        //Add listener to marker for reverse geocoding
        google.maps.event.addListener(marker, 'drag', function() {
            geocoder.geocode({
                'latLng': marker.getPosition()
            }, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[0]) {
                        $("#" + mapWrapper + '_ac').val(results[0].formatted_address);
                        $("#" + mapWrapper + '_lat').val(marker.getPosition().lat());
                        $("#" + mapWrapper + '_lon').val(marker.getPosition().lng());
                    }
                }
            });
        });

        Nameee.placePicker._map = map;
    },

    reload: function ()
    {
        map = Nameee.placePicker._map;
        google.maps.event.trigger(map, 'resize');
        map.setZoom( map.getZoom() );
        map.setCenter(Nameee.placePicker._latlng);
    }


};

/*
var geocoder;
var map;
var marker;

function initialize(){
//MAP
  var latlng = new google.maps.LatLng(41.659,-4.714);
  var options = {
    zoom: 16,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.SATELLITE
  };

  map = new google.maps.Map(document.getElementById("map_canvas"), options);

  //GEOCODER
  geocoder = new google.maps.Geocoder();

  marker = new google.maps.Marker({
    map: map,
    draggable: true
  });

}

$(document).ready(function() {

  initialize();

  $(function() {
    $("#address").autocomplete({
      //This bit uses the geocoder to fetch address values
      source: function(request, response) {
        geocoder.geocode( {'address': request.term }, function(results, status) {
          response($.map(results, function(item) {
            return {
              label:  item.formatted_address,
              value: item.formatted_address,
              latitude: item.geometry.location.lat(),
              longitude: item.geometry.location.lng()
            }
          }));
        })
      },
      //This bit is executed upon selection of an address
      select: function(event, ui) {
        $("#latitude").val(ui.item.latitude);
        $("#longitude").val(ui.item.longitude);
        var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
        marker.setPosition(location);
        map.setCenter(location);
      }
    });
  });

  //Add listener to marker for reverse geocoding
  google.maps.event.addListener(marker, 'drag', function() {
    geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (results[0]) {
          $('#address').val(results[0].formatted_address);
          $('#latitude').val(marker.getPosition().lat());
          $('#longitude').val(marker.getPosition().lng());
        }
      }
    });
  });

});
*//**
 * Personal profile support files
 *
 * @author Jan Juricek <jan@nameee.com>
 */

var Nameee = Nameee || {}

Nameee.profile = {
    
    _fwkInitialized: false,

    _initFwk: function()
    {
        if (!this._fwkInitialized) {
            if (Nameee.fwk) {
                Nameee.fwk.init('WP-fwk', 528, 396, 'processFWKResponseProfile', "/run/account/settings/proccess-photo-fwk-action/index.php");
            } else {
                alert('Unable to connect to your webcam');
            }
        }
    },

    showFormPhoto: function( source )
    {

        $('#photoLinks').hide();
        $('#photoUpload').hide();
//        $('#photoFWK').hide();

//        if (source == 'fwk') {
//            $('#photoFWK').show();
//            this._initFwk()
//        } else {
        if (source != 'fwk') {
            $('#settingsprofilephoto-photo').trigger('click');
            $('#photoUpload').show();
        }

        $('#photoSubmit').show();

        return false;
    },
    
    loadContentToTop: function (elId, url)
    {
        var $parent = $('#' + elId),
            $DD = $parent.find('div.dropdown-menu');

        if($DD.length == 0)
        {
            /**
             * Add dropdown menu
             */
            $DD = $('<div>', {
                'class': 'dropdown-menu'
            });

            $parent.append($DD);
            Nameee.loader.begin($DD, false, true);
        }

        if ($parent.hasClass('active') == false) {

            $('#DD').find('li').filter('.active').removeClass('active');
            $parent.addClass('active');

            /*
             * get content
             */
            $.ajax({
                method: 'GET',
                url: url,
                cache: false,
                success: function(content) {
                    data = jQuery.parseJSON(content);
                    $DD.html(data.html);

                    /* autotime */
                    Nameee.fuzzyTime.initAll($DD.find('span.autotime'))
                },
                error: function() {
                    $parent.removeClass('active');
                    Nameee.ajaxDialog.open(
                        'dropdown-notification-ajax-error',
                        '<div class="UI-Message Warning"><p>' + lm('An error occurred. Please try it again.') + '</p></div>',
                        {
                            title: lm('Error'),
                            ajax: false
                        }
                    );
                }
            });



        }

    }
};

function processFWKResponseProfile(data)
{
    $('input[name=fwkdata]').val(data);
    alert('Image has been saved.');
}/**
 * Flash Shingle support files
 *
 * @author Jan Juricek <jan@nameee.com>
 */

var Nameee = Nameee || {};

Nameee.shingle = {
    edit: function(containerId, width, height) {
//        alert('A');
        var flashvars = {
            saveURL: '/ajax/service/shingle/save/',
            uploadURL: '/ajax/service/shingle/upload-image/',
            clickthru: '/exit.php',
            imgUrl1: '/data/shingle/images.xml',
            imgUrl2: '/data/shingle/background.xml',
            xmlUrl: '/data/shingle.xml',
            itemList: true,

            title: 'Editor',
            saveXML: 'Uložit',
            addText: 'Text',
            uploadImg: 'Nahrát obrázek',
//            addImgLib: 'Obrázek z knihovny',
            addVideo: 'Vložit video',
            uploadBackImage: 'Nahrát pozadí',
//            addBackLibImage: 'Pozadní z knihovny',
            selectedItemLink: 'Vložte odkaz',
            editText: 'Úprava textu',
            itemsShow: 'Zobrazit objekty vizitky',
            itemsHide: 'Skrýt objekty vizitky',
            err: 'Chyba',
            errUpload: 'Nepodařilo se nahrát soubor',
            cancelled: 'Nahrávání bylo zrušeno',
            starting: 'Spouštím nahrávání',
            imageLabel: 'Obrázek',
            textLabel: 'Text',
            swfLabel: 'Flash'

        };

        var params = {};
        var attributes = {};

//        alert('a');
        swfobject.embedSWF(
            "/swf/shingle/edit.swf",
            containerId,
            width,
            height,
            "9.0.0",
            "/swf/expressInstall.swf",
            flashvars,
            params,
            attributes);
    }
};/**
 * This class is a part of Tabs view helpers. It allows to use tabs as expected.
 *
 * @author Jan Juricek <jan@nameee.com>
 */

var Nameee = Nameee || {};

Nameee.tabs = {

    _hideAll: function(bufferId) {
        selector = '#TB' + bufferId + ' .UI-Tabs-Content-Block';
//        // console.log($(selector));
        $(selector).removeClass('active');
        selector = '#TB' + bufferId + ' .UI-Tabs-Control li';
        $(selector).removeClass('active');
    },

    _showOne: function(bufferId, tabId) {
        selector = '#TB' + bufferId + 'T' + tabId;
        $(selector).addClass('active');
        selector = '#TB' + bufferId + 'L' + tabId;
        $(selector).addClass('active');
    },

    show: function(bufferId, tabId, tabUrl, reload) {

        if( typeof( reload ) == 'undefined' )
            reload = false;

        Nameee.tabs._hideAll(bufferId);

        if (tabUrl) {
            tabContent = $('#TB' + bufferId + 'T' + tabId);
            if (!tabContent.hasClass('ContentLoaded') || reload ) {
                $.ajax({
                    url: tabUrl,
                    cache: false,
                    success: function(htmlResponse){
                        tabContent.html(htmlResponse)
                        tabContent.addClass('ContentLoaded');
                    },
                    beforeSend: function() {
                        Nameee.tabs._showOne(bufferId, tabId);
                        Nameee.loader.begin(tabContent, true)
                    }
                });
            } else {
                Nameee.tabs._showOne(bufferId, tabId);
            }
        } else {
            selector = '#TB' + bufferId + 'T' + tabId;
            $(selector).addClass('active');
            selector = '#TB' + bufferId + 'L' + tabId;
            $(selector).addClass('active');
        }
    }
};/**
 * Support for votes on page
 *
 * @author Jan Hrouza <hrouza@awebsys.cz>
 */

var Nameee = Nameee || {};

Nameee.votes = {
    init: function()
    {
    },

    /**
     * Nacteni HTML bloku bodovani
     * @param el id of DOMelement of cod
     */
    loadVoteHtmlBlock: function(el, loadUrl, afterLoadCallback)
    {
        if (typeof(afterLoadCallback) != 'function'){
           afterLoadCallback = function(){};
        }
        $(el).load(loadUrl,null,afterLoadCallback);
        Nameee.loader.begin(el, false, true);
        return false;
    },

    /**
     * HTML pouzite v okamzicich cekani na odpoved
     */
    getWaitingHtml: function()
    {
//        Nameee.loader.begin()
//        return '<img src="/img/loading.gif" alt="Loading" style="width:25px;height:25px;" />';
    },

    photoPromoteCallback: function() {
        id = $(this).attr('id')
        id = $('#'+id.substr(15));
        parent = $(id).parent();
        id.detach();
        $(parent).prepend(id);
    }
}

/**
 * Zajisteni inicializace
 */
$(document).ready(function() {
    Nameee.votes.init();
});

/**
 * JS support to the wall
 *
 * @author Jan Juricek <jan@nameee.com>
 */

var Nameee = Nameee || {}

Nameee.wall = {

    _preventSubmitLink: false,

    _prepared: false,

    _fwkInitialized: false,

    _initFwk: function()
    {
        if (!this._fwkInitialized) {
            if (Nameee.fwk) {
                Nameee.fwk.init('WP-fwk', 518, 396, Nameee.wall.submitForm, '/upload.php');
            } else {
                alert('Unable to connect to your webcam');
            }
        }
    },

    setDefault: function()
    {
        Nameee.wall.setActive('#shareStatus', 'status');
    },

    setActive: function(elementId, storytype)
    {
        $('#wall-storytype').val(storytype);
        Nameee.wall.removeBackground();
        $(elementId).addClass('active');
    },

    removeBackground: function()
    {
        $('.StoryAdd ol li').removeClass('active');
    },

    changeVisible: function(show, hide)
    {
        for (var i in show) {
            $(show[i]).show();
        }

        for (var i in hide) {
            $(hide[i]).hide();
        }
    },

    showShareStatus: function()
    {
        Nameee.wall.setActive(
            '#shareStatus',
            'status'
        );
        Nameee.wall.changeVisible(
            ['#WW', '#WT', '#WB'],
            ['#WL', '#WE', '#WP']
        );

        $('#wall-text').focus();

        return false;
    },

    showNothing: function(resetForm)
    {
        Nameee.wall.setDefault();
        Nameee.wall.changeVisible(
            ['#WW', '#WT'],
            ['#WL', '#WE', '#WP', '#WB']
        );

        if (resetForm) {
//            alert($('#wall'));
            $('#wall').get(0).reset();
//            $('#wall').reset();
        }

        return false;
    },

    showSharePhoto: function( source )
    {
        Nameee.wall.setActive(
            '#sharePhoto',
            'photo'
        );

        Nameee.wall.changeVisible(
            ['#WW'],
            ['#WT', '#WL', '#WE', '#WB']
        );

//        if (source == 'fwk') {
//            Nameee.wall.changeVisible(
//                ['#WP-fwk', '#WP', '#WB', '#WT'],
//                ['#WP-sw', '#WP-pu']
//            );
//            this._initFwk()
//        } else if (source == 'pu') {
            Nameee.wall.changeVisible(
                ['#WP-pu', '#WP', '#WB', '#WT'],
                ['#WP-sw', '#WP-fwk']
            );
//        } else {
//            Nameee.wall.changeVisible(
//                ['#WP-sw', '#WP'],
//                ['#WP-fwk', '#WP-pu']
//            );
//        }

        return false;
    },



    showShareLink: function()
    {
        Nameee.wall.setActive('#shareLink', 'link');
//        alert($('#wall-storytype').val());
        Nameee.wall.changeVisible(
            ['#WT', '#WW', '#WL', '#WB'],
            ['#WP', '#WE']
        );

        $("#wall-link_url").focus(function(e){Nameee.wall._preventSubmitLink = true;})
                           .blur(function(e){Nameee.wall._preventSubmitLink = false;})
                           .change(function(e){
                               if ($(this).val() != '') {
                                   Nameee.wall._prepared = false;
                               }
                           });

        return false;
    },

    showShareEvent: function()
    {
        Nameee.wall.setActive('#shareEvent', 'event');
        Nameee.wall.changeVisible(
            ['#WW', '#WE', '#WB'],
            ['#WL', '#WT', '#WP']
        );

        return false;
    },

    extractThumbnails: function(id, data)
    {
        data = $.parseJSON(data)
        $('#' + id).html(data.html);

        if (data.result == 'success') {
            Nameee.wall._prepared = true;
            $('#' + id + ' ul li:first-child').addClass('active');

            $('#WB').show();
            $('#WT').show();
        }
    },

    extractThumbnailsStart: function(id, url) {
        $('#' + id).show();
        $('#' + id).html('<img src="/img/loading.gif" alt="Loading" style="height:25px;margin:5px;width:25px;" />');
    },

    thumbnailNext: function(id)
    {
        elm = $('#' + id + ' li.active');

        if (elm.next().length > 0) {
            elm.removeClass('active').next().addClass('active');
        }
    },

    thumbnailPrev: function(id)
    {
        elm = $('#' + id + ' li.active');
        if (elm.prev().length > 0) {
            elm.removeClass('active').prev().addClass('active');
        } else {

        }
    },

    submitForm: function(form)
    {
        thumb = $(form).find('.foundthumbs li.active img');
        if(thumb.attr('src')) {
            $(form).find('input.link_thumb').val(thumb.attr('src'));
        }

        $(form).find('input.link_title').val($(form).find('#link_title_content').text());
        $(form).find('input.link_desc').val($(form).find('#link_desc_content').text());
        $(form).find('input.video_code').val($(form).find('#video_code_content').text());

        if ($('#wall-storytype').val() == 'link') {
            if (!Nameee.wall._prepared) {
                if ($('#wall-link_url').val() != ''){
                    $('#wall-extract').click();
                } else {
                    $('#wall-link_url').focus();
                }
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    },

    reload: function(object, id, resetForm) {
        var url = '/ajax/wall2/load-page/?o=' + object + '&i=' + id;
        var $wrapper = $('#WallWrapper');
        $.ajax({
            method: 'GET',
            url: url,
            cache: false,
            success: function(content){
                $wrapper.html(content);
                Nameee.fuzzyTime.initAll($wrapper.find('span.autotime'));
            }
        });
    },

    prependStory: function(jsonString) {
        var $wrapper = $('#WallWrapper');
        $wrapper.prepend(jsonString);
        Nameee.fuzzyTime.initAll($wrapper.find('span.autotime'));
//        Nameee.wall.showNothing();
//        jQuery('form.StoryAdd')[0].reset();
    },

    noFlashFallBack: function( e ){
        // alert("e.success = " + e.success +"\ne.id = "+ e.id +"\ne.ref = "+ e.ref);
        if ( false == e.success && undefined != e.id && null != e.id )
        {
            $('#' + e.id).show();
            $('#' + e.id).html('<a href="http://get.adobe.com/flashplayer/" target="_blank"><img src="/img/btn-get-flashplayer.gif" alt="Flash Player" width="160" height="41" /></a><div class="clear"></div>');
        }
    },

    embedVideo: function(domId, handler, videoCode){
        var params = {allowScriptAccess: "always", wmode: "transparent", allowFullScreen: "true"};
        var atts = {id: domId + 'video'};

        var embedUrl = 'embedurl';
        switch ( handler )
        {
            default:
            case 'yt':
                    embedUrl = "http://www.youtube.com/v/" + videoCode + "?enablejsapi=1&playerapiid=ytplayer&autoplay=1&fs=1";
                break;

            case 'dm':
                    embedUrl = "http://www.dailymotion.com/swf/video/" + videoCode + "?autoPlay=1";
                break;

            case 'mc':
                    embedUrl = "http://www.metacafe.com/fplayer/" + videoCode + "/dummy.swf?playerVars=autoPlay=yes";
                break;

            case 'vi':
                    embedUrl = "http://vimeo.com/moogaloop.swf?clip_id=" + videoCode + "&amp;autoplay=1&amp;color=f69429&amp;fullscreen=1";
                break;
        }
        $(domId).show();
        $('#'+ domId + '-data').hide();
        swfobject.embedSWF(embedUrl,
                           domId, "475", "290", "8", null, null, params, atts, this.noFlashFallBack);
    },

    listAjaxRequest: function( elementToRemove, url, listId ) {
        $.ajax({
            method: 'GET',
            url: url,
            cache: false,
            success: function(content){
                $('#'+elementToRemove).slideUp(
                    'fast',
                    function() {
                        $('#'+elementToRemove).remove();
                        if ( 0 == $('#'+listId+' li').length )
                        {
                            $('#'+listId+'-Frame').remove();
                            $('#'+listId+'-Warn').show();
                        }
                    }
                );
            },
            failure: function(content)
            {
            }
        });
    },


    toggleAjaxRequest: function( element, url, state1, state2 ) {
        $.ajax({
            method: 'GET',
            url: url,
            cache: false,
            success: function(content){
                var e = $('#'+element);
                ( e.html().toString() == state1 ? e.html(state2) : e.html(state1) )
            },
            failure: function(content)
            {
            }
        });
    },

    hideStory: function( element ) {
        $('#'+element).slideUp(
            500,
            function() {
                $('#'+element).remove();
            }
        );
    },

    toggleDelMenu: function (el) {
        var className = 'Open';
        var active = false;

        if ($(el).hasClass(className)) {
            active = true;
        }

        $('#WallWrapper .Remove.' + className).removeClass(className);

        if (active == true) {
            $(el).removeClass(className);
        } else {
            $(el).addClass(className);
        }
    },

    /**
     * Simple ajax get, with no success/failure handling
     */
    callOnBackground: function( url ) {
        if ( null != url && undefined != url )
        {
            $.ajax({
                method: 'GET',
                url: url,
                cache: false,
                async: true,
                success: function(){},
                failure: function(){}
            });
        }
    },

    expandTextBlock: function( domobj )
    {
        $(domobj).parent().hide();
        $(domobj).parent().next().show(500);
        $(domobj).parent().remove();
    }

};/**
 * JS support to friend requests etc
 *
 * @author Damian Brhel <damian.brhel@webcorp.cz>
 */

var Nameee = Nameee || {}

Nameee.requests = {
    
    processFriends: function( el, url )
    {
        var user = $(el).parents().filter('li');
        var user = $(user.get(0));
        var userText = $($(user).children('div.MsgCont'));
        
        var block = $(user.parent());
        
        $.ajax({
            type: 'POST',
            url:  url,
            beforeSend: function(){
                Nameee.loader.begin(userText, true);
            },
            success: function(response){
                if ( 0 == response.length ) {
                    user.remove();
                }
                else {
                   response = jQuery.parseJSON(response);
                   userText.html('<p>' + response.message + '</p>');
                   
                   /**
                    * Decrement count
                    */
                   
                   if(response.result == 1) {
                       $counts = $('#DDFri').find('.counts');
                        var actualCount = parseInt($.text($counts));
                        if(actualCount == 1) {
                            $counts.remove();
                        } else {
                            $counts.text(actualCount - 1);
                        }
                   }

                   /**
                    * Remove user
                    */
                   user.delay(1000).fadeOut('slow', function() { 
                       user.remove();
                       if($(block).children().length == 0) {
                           $(block).append('<li><p>' + response.noMoreRequests + '</p></li>').hide().fadeIn('slow');
                       }
                  } );
                }
            }
        });
        
        return false;
    }
};var Nameee = Nameee || {};

/**
 * Nameee.photoTag
 */
Nameee.photoTag = {
		
	//object holding photo tag thats beeing created
	currentPhotoTag: {
		'item': '',
		'x': '',
		'y': ''
	},

    init: function() {
        
        this._actTagType = 'friend-tagger'; //default tagger type
    	//move tagger box(containing list of friends) under body tag so it's fine with css and positioning
    	var tagger = $('#photo-tagger').remove();
    	if (tagger.length > 0) {
    		tagger.appendTo($('body'));

	    	//clicking or resizing the document hides the tagging dialog
	        //the function cannot be called directly as it gets event as param
	        $(document).bind('click', function() {
                    Nameee.photoTag.hidePhotoTagger();
	        });
	    	$(window).resize(function() {
                    Nameee.photoTag.hidePhotoTagger();
                });

	        //clicking the image makes the tagging dialog visible, this must survive ajax content change
	        $('body').delegate('img.photo-tagger-enabled', 'click', function(e) {
                    Nameee.photoTag.showPhotoTagger(e, this);
                    return false;
	        });
    	}
    },

    startTagging: function () {
        $('#gallerybox-left').hide();
        $('#gallerybox-right').hide();
        $('#photo-wrapper img').addClass('photo-tagger-enabled');
        $('#start-tagging').html(lm('Finish tagging')).attr('onclick', null);
        $('#tagging-message').show();
        return false;
    },

    cleanCurrentPhotoTag: function() {
    	return Nameee.photoTag.currentPhotoTag = {
			'item': '',
			'x': '',
			'y': ''
		};
    },

    removePhotoTag: function(ptid, pitem, showLoadingElm) {

    	var link = '/run/albums/ajax/remove-tag/?random=' + new Date().getTime();
    	link += '&ptid=' + ptid;
    	link += '&pitem=' + pitem;
    	if (showLoadingElm) {
            Nameee.loader.begin(showLoadingElm, false, true);
    	}
    	$.ajax({
            type: 'GET',
            url: link,
            dataType: 'xml',
            success: function(response){
            	if ($(response).find('result').text() == '1') {
            		if ($(response).find('list').length > 0) {
            			$('.photo-tagged-list.' + pitem).replaceWith($(response).find('list').text());
            		}
            	} else if ($(response).find('error').length > 0) {
            		alert($(response).find('error').text());
            	}
            },
            complete: function() {
            	if (showLoadingElm) {
                    $(showLoadingElm).replaceWith(lm('Removed'));
            	}
            }
        });
    },
    
    savePhotoTaggerXhr: false,
    savePhotoTagger: function( myself ) {
    	//console.info('savePhotoTagger');
        var uid = $('#friend-tagger-select').val();
        if( typeof( myself ) != 'undefined' )
            uid = -1; //myself uid
    	var link = '/run/albums/ajax/save-tag/?random=' + new Date().getTime();
    	link += '&uid=' + uid;
        $('#friend-tagger-select').val('');
    	link += '&name=' + $('#friend-tagger-name').val();
    	link += '&email=' + $('#friend-tagger-mail').val();
    	link += '&pitem=' + Nameee.photoTag.currentPhotoTag.item;
    	link += '&x=' + Nameee.photoTag.currentPhotoTag.x;
    	link += '&y=' + Nameee.photoTag.currentPhotoTag.y;

    	if (Nameee.photoTag.savePhotoTaggerXhr != false) {
    		Nameee.photoTag.savePhotoTaggerXhr.abort();
    	}
    	
    	//hide buttons and show loading
        //$('#photo-tagger .Content div').hide();
    	$('#photo-tagger .Buttons div').hide();
    	$('#photo-tagger .Buttons img').show();
    	
    	Nameee.photoTag.savePhotoTaggerXhr = $.ajax({
            type: 'GET',
            url: link,
            dataType: 'xml',
            success: function(response){
            	if ($(response).find('result').text() == '1') {
            		if ($(response).find('list').length > 0) {
            			$('.photo-tagged-list.' + Nameee.photoTag.currentPhotoTag.item).replaceWith($(response).find('list').text());
            		}
            		Nameee.photoTag.hidePhotoTagger(true);
            	} else if ($(response).find('error').length > 0) {
            		alert($(response).find('error').text());
            	}
            },
            complete: function() {
            	Nameee.photoTag.savePhotoTaggerXhr = false;
            	//hide buttons and show loading
                //$('#photo-tagger .Content div').show();
            	$('#photo-tagger .Buttons div').show();
            	$('#photo-tagger .Buttons img').hide();
            }
        });
    },
    
    showPhotoTagger: function(event, elm) {

    	//console.info('showPhotoTagger');

    	if (!Nameee.photoTag.hidePhotoTagger()) {
    		return false;
    	}

    	//create new hidden box and append it into DOM
    	box = $('<div>')
    		.attr('id', 'photo-tag-box')
    		.css({'display': 'none'})
    		.appendTo($('body'));

    	halfBoxWidth = Math.round(box.outerWidth() / 2);
    	halfBoxHeight = Math.round(box.outerHeight() / 2);

    	var pwp = $('#photo-wrapper').position();
    	elmPos = $(elm).position();
        elmPos.top += pwp.top;
        elmPos.left += pwp.left;

        
    	//get position of event
    	var pos_x = event.offsetX ? event.offsetX + elmPos.left : event.pageX;
    	var pos_y = event.offsetY ? event.offsetY + elmPos.top : event.pageY;

    	var min_x = elmPos.left + parseInt($(elm).css('border-left-width')) + parseInt($(elm).css('padding-left'));
    	var min_y = elmPos.top + parseInt($(elm).css('border-top-width')) + parseInt($(elm).css('padding-top'));
    	var max_x = min_x + $(elm).width() - halfBoxWidth * 2;
    	var max_y = min_y + $(elm).height() - halfBoxHeight * 2;

    	Nameee.photoTag.currentPhotoTag.item = $(elm).attr('id');
    	Nameee.photoTag.currentPhotoTag.x = (100 / $(elm).width()) * (pos_x - min_x);
    	Nameee.photoTag.currentPhotoTag.y = (100 / $(elm).height()) * (pos_y - min_y);

    	pos_x -= halfBoxWidth;
    	pos_y -= halfBoxHeight;

    	if (pos_x > max_x) {
    		pos_x = max_x;
    	} else if (pos_x < min_x) {
    		pos_x = min_x;
    	}

    	if (pos_y > max_y) {
    		pos_y = max_y;
    	} else if (pos_y < min_y) {
    		pos_y = min_y;
    	}

    	var taggerLeft = elmPos.left - $('#photo-tagger').outerWidth();
    	var taggerTop = elmPos.top;
        
        
    	if ($(elm).parent().is('.UI-Photo.Detail')) {
    		taggerLeft = Math.round(pos_x + halfBoxWidth * 2.5);
    		taggerTop = pos_y;
    	}

    	$('#photo-tagger').css({
            'display': 'block',
            'top': taggerTop,
            'left': taggerLeft
        })
        .click(function(e){
            e.stopPropagation();
        });

        //links in tagging dialog
        $('#tag-friend-link').click(function(){
            return Nameee.photoTag.showFriendSelect();
        });
        $('div.friend-tagger-close').click(function(){
                $('#friend-tagger-select').val(0);
                $('#tag-friend-link').trigger('click');
                Nameee.photoTag.hidePhotoTagger();
        });

        Nameee.photoTag.showFriendSelect();
    	//update box with new position and show it
    	box.css({
    		'top': pos_y,
    		'left': pos_x,
    		'display': 'block'
        });
    },

    showFriendSelect: function(){
        this._actTagType = 'friend-tagger';
        $('#another-friend-tagger').hide();
        $('#friend-tagger').show();
        $('#friend-tagger-name, #friend-tagger-mail').val('');
        $('#friend-tagger-select').focus();
        return false;
    },

    showAnotherFriendSelect: function()
    {
        this._actTagType = 'another-friend-tagger';
        $('#another-friend-tagger').show();
        $('#friend-tagger').hide();
        $('#friend-tagger-select').val(0);
        $('#friend-tagger-name').focus();
        return false;
    },
    
    hidePhotoTagger: function(force) {
    	//don't hide when there is loading visible
    	if ($('#photo-tagger .Buttons img:visible').length > 0) {
    		if (typeof(force) != 'undefined') {
    			if (!force) {
    				return false;
    			}
    		} else {
    			return false;
    		}
    	}

    	//clean the tag entry
    	Nameee.photoTag.cleanCurrentPhotoTag();

    	//remove already existing box
    	$('#photo-tag-box').remove();
    	$('#photo-tagger').hide();
        //get back prev/next photo  controls

        if( force )
        {
            $('#gallerybox-left').show();
            $('#gallerybox-right').show();
            
            $('body').find('img.photo-tagger-enabled').unbind('click');
            $('#photo-wrapper img').removeClass('photo-tagger-enabled');
        }
    	return true;
    },
    
    showTagMarker: function(imgId, x, y) {
    	elm = '#' + imgId;

        var pwp = $('#photo-wrapper').position();
    	elmPos = $(elm).position();
        elmPos.top += pwp.top;
        elmPos.left += pwp.left;

    	box = $('<div>')
    		.attr('id', 'photo-tag-marker-box')
    		.css({
    			'display': 'none'
    		})
    		.appendTo($('body'));

    	halfBoxWidth = Math.round(box.outerWidth() / 2);
    	halfBoxHeight = Math.round(box.outerHeight() / 2);

    	var min_x = elmPos.left + parseInt($(elm).css('border-left-width')) + parseInt($(elm).css('padding-left'));
    	var min_y = elmPos.top + parseInt($(elm).css('border-top-width')) + parseInt($(elm).css('padding-top'));
    	var max_x = min_x + $(elm).width() - halfBoxWidth * 2;
    	var max_y = min_y + $(elm).height() - halfBoxHeight * 2;

    	pos_x = min_x + ($(elm).width() / 100) * x;
    	pos_y = min_y + ($(elm).height() / 100) * y;
    	
    	pos_x -= halfBoxWidth;
    	pos_y -= halfBoxHeight;

    	if (pos_x > max_x) {
    		pos_x = max_x;
    	} else if (pos_x < min_x) {
    		pos_x = min_x;
    	}

    	if (pos_y > max_y) {
    		pos_y = max_y;
    	} else if (pos_y < min_y) {
    		pos_y = min_y;
    	}
    	
    	//update box with new position and show it
    	box.css({
            'top': pos_y,
            'left': pos_x,
            'display': 'block'
        });
    },

    hideTagMarker: function() {
    	$('#photo-tag-marker-box').remove();
    },

    addMarkerOnPhoto: function(text, imgId, x, y) {
    	elm = '#' + imgId;

    	elmPos = $(elm).position();

    	box = $('<div>')
    		.attr('title', text)
    		.addClass('tag-marker')
    		.css({
    			'display': 'none'
    		})
    		.appendTo($(elm).parent());

    	halfBoxWidth = Math.round(box.outerWidth() / 2);
    	halfBoxHeight = Math.round(box.outerHeight() / 2);

        /* IE nepobírá border-width - vrací medium */
    	var min_x = elmPos.left + /*parseInt($(elm).css('border-left-width')) + */parseInt($(elm).css('padding-left'));
    	var min_y = elmPos.top + /*parseInt($(elm).css('border-top-width')) + */parseInt($(elm).css('padding-top'));

        var max_x = min_x + $(elm).width() - halfBoxWidth * 2;
    	var max_y = min_y + $(elm).height() - halfBoxHeight * 2;

    	pos_x = min_x + ($(elm).width() / 100) * x;
    	pos_y = min_y + ($(elm).height() / 100) * y;

    	pos_x -= halfBoxWidth;
    	pos_y -= halfBoxHeight;

    	if (pos_x > max_x) {
    		pos_x = max_x;
    	} else if (pos_x < min_x) {
    		pos_x = min_x;
    	}

    	if (pos_y > max_y) {
    		pos_y = max_y;
    	} else if (pos_y < min_y) {
    		pos_y = min_y;
    	}
        
    	//update box with new position and show it
    	box.css({
            'top': pos_y,
            'left': pos_x,
            'display': 'block'
        });
    }
};
