window.smileys_admin = (function( $ )
{
    var instance;
    
    function _construct()
    {        
        var _elements = {}, _methods = {};
        
        _methods.panelOnReady = function( content )
        {
            _elements.panel = $( content ).appendTo( document.getElementById('smileys-placeholder') );
            _methods.init();
        };
        
        $( function(){OW.loadComponent('SMILEYS_CMP_Panel', [], _methods.panelOnReady);} );
               
        _methods.init = function()
        {
            if ( _elements.panel[0].children[0].children.length !== 0 )
            {
                _elements.panelContents = $( '.ui-accordion-content', _elements.panel );
                _elements.panelCaptions = $( '.smileys-header', _elements.panel )
                    .droppable(
                    {
                        accept: 'img.smile', 
                        activeClass: 'ui-state-hover', 
                        hoverClass: 'ui-state-active',
                        drop: _methods.moveSmileys,
                        out: function( event, ui ) 
                        {
                            _methods.toggleSlide( ui.draggable.parent().prev() );
                        }
                    })
                    .hover(function(){$(this).addClass('ui-state-hover');},function(){$(this).removeClass('ui-state-hover');});

                var btn = $( '<span />', {class: 'smileys-btn', style: 'color:#91b1fd'} );
                btn.clone().text( OW.getLanguageText('smileys', 'delete_category') ).on( 'click', _methods.deleteCategory ).appendTo( _elements.panelCaptions );            
                btn.clone().text( OW.getLanguageText('smileys', 'rename_category') ).on( 'click', _methods.renameCategory ).appendTo( _elements.panelCaptions );
                btn.clone().text( OW.getLanguageText('smileys', 'upload_smileys') ).on( 'click', _methods.uploadSmileys ).appendTo( _elements.panelCaptions );

                _elements.panelCaptions.on( 'click', function()
                {
                    _methods.toggleSlide( this );
                    _methods.loadSmileys( this );
                });

                this.toggleSlide( _elements.panelCaptions[0] );
                this.loadSmileys( _elements.panelCaptions[0] );
            }

            _elements.panel.show();
        };
        
        _methods.toggleSlide = function( element )
        {
            var handler = $( element );
            
            if ( !handler.hasClass('ui-state-active') )
            {
                _elements.currentCategory = handler.attr( 'category' );
                _elements.panelCaptions.not( handler ).removeClass( 'ui-state-active' ).addClass( 'ui-corner-all' );
                handler.removeClass( 'ui-corner-all' ).addClass( 'ui-state-active' );
                _elements.panelContents.not( handler.next() ).slideUp( 'fast' );
            }
        };
        
        _methods.loadSmileys = function( element )
        {
            var handler = $( element );
            var handlerContent = handler.next();
            var category = handler.attr( 'category' );
            
            if ( handlerContent[0].children.length === 0 )
            {
                $.ajax(
                {
                    url: window.smileysParams.url,
                    cache: false,
                    data: { category: category },
                    dataType: 'json',
                    type: 'POST',
                    success: function( smileys )
                    {
                        if ( $.isEmptyObject(smileys) )
                        {
                            $( '<div />', {class: 'ow_center', text: 'No items'} ).appendTo( handlerContent );
                            
                            return;
                        };
                        
                        var image = $( new Image() );
                        
                        for ( var key in smileys )
                        {
                            image.clone().attr( {src: window.smileysParams.smileysUrl + category + '/' + smileys[key] + '?' + Math.random(), category: category, name: smileys[key], title: smileys[key].replace(/\.gif$/, '')} ).appendTo( handlerContent );
                        }
                        
                        var smileItems  = handlerContent.find( 'img' );
                        
                        smileItems
                            .addClass( 'smile' )
                            .draggable( {helper: 'clone', zIndex: 100} );
                    
                        OW.bindTips( smileItems );
                    },
                    error: function( XMLHttpRequest, textStatus, errorThrown )
                    {
                        //OW.error( textStatus );
                        //throw textStatus;
                    }
                });
            }
            
            handlerContent.slideDown( 'fast' );
        };
        
        _methods.createCategory = function()
        {
            window.owForms.newCategory.removeErrors();
            window.owForms.newCategory.getElement( 'command' ).setValue( 'createNewCategory' );
            window.owForms.newCategory.getElement( 'categoryName' ).setValue( '' );
            
            var floatbox = new OW_FloatBox(
            {
                $title: OW.getLanguageText( 'smileys', 'new_category' ),
                $contents: $( document.getElementById('newCategoryContent') ),
                width: 500
            });
        };
        
        _methods.renameCategory = function()
        {
            var category = $( this ).closest( '.smileys-header' ).attr( 'category' );
            window.owForms.newCategory.removeErrors();
            window.owForms.newCategory.getElement( 'command' ).setValue( 'renameCategory' );
            window.owForms.newCategory.getElement( 'categoryName' ).setValue( category );
            window.owForms.newCategory.getElement( 'oldName' ).setValue( category );

            var floatbox = new OW_FloatBox(
            {
                $title: OW.getLanguageText( 'smileys', 'rename_category' ),
                $contents: $( document.getElementById('newCategoryContent') ),
                width: 500
            });
        };
        
        _methods.deleteCategory = function()
        {
            if ( confirm('Are you sure?') )
            {
                window.owForms.newCategory.getElement( 'command' ).setValue( 'deleteCategory' );
                window.owForms.newCategory.getElement( 'categoryName' ).setValue( $(this).closest('.smileys-header').attr('category') );
                $( window.owForms.newCategory.form ).submit();
            };
        };
        
        _methods.uploadSmileys = function()
        {
            var category = $( this ).closest( '.smileys-header' ).attr( 'category' );
            window.owForms.uploadSmileys.getElement( 'category' ).setValue( category );
            window.owForms.uploadSmileys.getElement( 'command' ).setValue( 'uploadSmileys' );

            var floatbox = new OW_FloatBox(
            {
                $title: OW.getLanguageText( 'smileys', 'floatbox_smileys_upload_caption' )  + ' - [' + category + ']',
                $contents: $( document.getElementById('uploadSmileysContent') ),
                width: 800
            });
        };
        
        _methods.moveSmileys = function( event, ui )
        {
            var handler = $( this );
            
            if ( handler.attr('category') !== ui.draggable.attr('category') )
            {
                $.ajax(
                {
                    url: window.smileysParams.adminRsp,
                    cache: false,
                    async: false,
                    data:
                    { 
                        command: 'move',
                        smileys: ui.draggable.attr( 'name' ),
                        oldCategory: ui.draggable.attr( 'category' ),
                        newCategory: handler.attr( 'category' )
                    },
                    dataType: 'json',
                    type: 'POST',
                    success: function( data )
                    {
                        if ( !data )
                        {
                            return;
                        }
                        
                        if ( data.result )
                        {
                            OW.info( OW.getLanguageText('smileys', 'message_smile_move') );
                            handler.next().empty();
                            ui.draggable.detach();
                        }
                        else
                        {
                            var params = {
                                smile: data.smile,
                                category: data.category
                            };
                            
                            OW.error( OW.getLanguageText('smileys', 'message_smile_move_error', params) );
                            return false;
                        }
                    },
                    error: function( XMLHttpRequest, textStatus, errorThrown )
                    {
                        //OW.error( textStatus );
                        //throw textStatus;
                    }
                });
            }
        };
        
        _methods.deleteSmileys = function( event, ui )
        {
            $.ajax(
            {
                url: window.smileysParams.adminRsp,
                cache: false,
                data:
                {
                    command: 'delete',
                    smileys: ui.draggable.attr('name'),
                    category: _elements.currentCategory
                },
                dataType: 'json',
                type: 'POST',
                success: function()
                {
                    ui.draggable.detach();
                }
            });
        };
        
        $( document.getElementById('newCategory') ).on( 'click', _methods.createCategory );
        $( document.getElementById('uploadSmileys') ).on( 'click', _methods.uploadSmileys );
        $( document.getElementById('deleteSmileys') ).droppable( {accept: 'img.smile', activeClass: 'ui-state-hover', hoverClass: 'ui-state-active', drop: _methods.deleteSmileys} );
        $( 'input:file', document.getElementById('uploadSmileysContent') ).live( 'change', function()
        {
            var handler = $( this );

            if ( handler.is('input:last-child') )
            {
                handler.parent().append( '<br />' );
                handler.parent().append( $('<input />', {type: 'file', name: 'smileys[]'}) );
            }
        });
        
        return {
            
        };
    }
    
    return {
        getInstance: function()
        {
            if ( !instance )
            {
                instance = _construct();
            }
            
            return instance;
        }
    };
})( jQuery ).getInstance();
