/**
 * Copyright (c) 2013, Kairat Bakytow
 * All rights reserved.

 * ATTENTION: This commercial software is intended for use with Oxwall Free Community Software http://www.oxwall.org/
 * and is licensed under Oxwall Store Commercial License.
 * Full text of this license can be found at http://www.oxwall.org/store/oscl
 */

window.smileys = (function( $ )
{
    var instance, _elements = {textarea: {}}, _methods = {};

    function _construct()
    {
        _methods.toggleSlide = function( element )
        {
            var handler = $( element );
            
            if ( !handler.hasClass('ui-state-active') )
            {
                _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.panelOnReady = function( content )
        //{
            _elements.panel = $(document.getElementById('smileys-panel'));
           // _methods.init();
        //};
        
        //OW.loadComponent( 'SMILEYS_CMP_Panel', [], _methods.panelOnReady );
               
        //_methods.init = function()
        //{
            _elements.panelContents = $( '.ui-accordion-content', _elements.panel );
            _elements.panelCaptions = $( '.smileys-header', _elements.panel ).hover(function(){$(this).addClass('ui-state-hover');},function(){$(this).removeClass('ui-state-hover');});
            
            _elements.panelCaptions.on( 'click', function()
            {
                _methods.toggleSlide( this );
                _methods.loadSmileys( this );
            });
            
            _methods.toggleSlide( _elements.panelCaptions[0] );
        //};
        
        
        
        _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], category: category, name: smileys[key].replace(/\.gif$/, '')} ).appendTo( handlerContent );
                        }
                        
                        handlerContent.find( 'img' )
                            .addClass('smile')
                            .on( 'click', function()
                            {
                                if ( _elements.currentTextarea === 'wysiwyg' )
                                {
                                    _elements.textarea['wysiwyg'].jhtmlareaObject.insertSmileys( '<img src="' + $(this).attr('src') + '" />' );
                                }
                                else
                                {
                                    var html = '[' + $(this).attr('category') + '/' + this.name + ']';
                                    
                                    if ( _elements.currentTextarea == 'shoutbox' )
                                    {
                                        var textarea = owForms.ShoutboxWindow.elements.text_entry;
                                        
                                        if ( textarea.getValue() == '' )
                                        {
                                            textarea.setValue('');
                                        }
                                    }
                                    
                                    _elements.textarea[_elements.currentTextarea].insertSmileys( html );
                                    _elements.smileysFloatBox.close();
                                }
                            });
                    },
                    error: function( XMLHttpRequest, textStatus, errorThrown )
                    {
                        //OW.error( textStatus );
                        //throw textStatus;
                    }
                });
            }
            
            if ( handler.siblings('div.ui-state-active').length === 0 )
            {
                handlerContent.slideDown( 'fast' );
            }
        };
        
        $.fn.extend(
        {
            insertSmileys: function( text )
            {
                return this.each(function() 
                {
                    if ( document.selection && this.tagName == 'TEXTAREA' )
                    {
                        this.focus();
                        var sel = document.selection.createRange();
                        sel.text = text;
                        this.focus();
                    }
                    else if ( this.selectionStart || this.selectionStart == '0') 
                    {
                        var startPos = this.selectionStart;
                        var endPos = this.selectionEnd;
                        var scrollTop = this.scrollTop;
                        this.focus();
                        this.value = this.value.substring(0, startPos) + text + this.value.substring(endPos, this.value.length);
                        
                        this.selectionStart = startPos + text.length;
                        this.selectionEnd = startPos + text.length;
                        this.scrollTop = scrollTop;
                    } 
                    else 
                    {
                        this.focus();
                        this.value += text;
                        this.value = this.value;
                    }
                });
            }
        });
        
        return {        
            addSmileButton: function( id, textarea, content, className )
            {
                var className = className || 'smileys_btn';
                _elements.textarea[id] = textarea;

                $( '<span />', {class: className, title: window.smileysParams.label, textareaId: id} )
                    .appendTo( content )
                    .on( 'click', function()
                    {
                        _elements.currentTextarea = $( this ).attr( 'textareaId' );
                        instance.showFloatBox();
                    });
            },

            addSmileToComment: function( id )
            {
                var content = $( document.getElementById(id) );
                
                instance.addSmileButton( id, content.find( 'textarea:first'), content.find('span.buttons') );
            },
                    
            addSmileToIChat: function( id )
            {
                var id = 'main_tab_contact_' + id;
                var content = $( document.getElementById(id) );
                
                instance.addSmileButton( id, content.find('.ow_chat_message textarea').height(60), content.find('.ow_chat_message_block .ow_chat_in_item_photo').css('overflow', 'visible'), 'smileys_btn_IChat' );
            },
            
            addSmileToUpdateStatus: function( id )
            {
                instance.addSmileButton( id, $(document.getElementById(id)).find('textarea.ow_newsfeed_status_input'), $(document.getElementById(id)).find('.buttons') );
            },
            
            addSmileToWysiwyg: function( textarea )
            {
                if ( !_elements.textarea['wysiwyg'] )
                {
                    _elements.textarea['wysiwyg'] = textarea;
                }
                
                _elements.currentTextarea = 'wysiwyg';
            },
            
            addSmile: function( cid )
            {
                var textarea = $(document.getElementById(cid));
                
                _elements.textarea[cid] = textarea;
                textarea.before($('<a>', {class: 'smileys_btn_2'}).on( 'click', function()
                {
                    _elements.currentTextarea = cid;
                    instance.showFloatBox();
                }));
            },
            
            addSmileChat: function( opponentId )
            {
                if ( $('span.smileys-btn2', "#" + "main_tab_contact_" + opponentId).length )
                {
                    return;
                }
                
                var textarea = $("#dialogTextarea", "#" + "main_tab_contact_" + opponentId);
                
                _elements.textarea[opponentId] = textarea;
                $("#dialogAttachmentsBtn", "#" + "main_tab_contact_" + opponentId).before($("<span>", {class: "smileys-btn2"}).on( 'click', function()
                {
                    _elements.currentTextarea = opponentId;
                    instance.showFloatBox();
                }));
            },
            
            addSmileChatForm: function()
            {
                var textarea = $("#dialogTextarea");
                
                _elements.textarea['dialogTextarea'] = textarea;
                $("#dialogAttachmentsBtn").before($("<span>", {class: "smileys-btn2"}).on( 'click', function()
                {
                    _elements.currentTextarea = 'dialogTextarea';
                    instance.showFloatBox();
                }));
                
                textarea = $('#conversationTextarea');
                _elements.textarea['conversationTextarea'] = textarea;
                $('#nfa-feed1 .buttons').append($('<span>', {class: 'smileys-btn3'}).on('click', function()
                {
                    _elements.currentTextarea = 'conversationTextarea';
                    instance.showFloatBox();
                }));
            },
            
            addSmileNewMessage: function()
            {
                var textarea = $("#mailbox-new-message-form textarea");
                
                _elements.textarea['newMessage'] = textarea;
                $("#mailbox-new-message-form span.buttons").append($("<span>", {class: "smileys-btn3"}).on( 'click', function()
                {
                    _elements.currentTextarea = 'newMessage';
                    instance.showFloatBox();
                }));
            },
            
            noConflict: function( pluginKey, action, id )
            {
                switch ( pluginKey )
                {
                    case 'attachments':
                        switch ( action )
                        {
                            case 'newsfeedUpdStatus':
                                var content = $( document.getElementById(id) );
                                
                                instance.addSmileButton( id, content.find('textarea.ow_newsfeed_status_input:first'), content.find('span.buttons:first') );
                                break;
                            case 'comments':
                                var content = $( document.getElementById(id) );
                        
                                instance.addSmileButton( id, content.find('textarea.ow_comment_textarea:first'), content.find('span.buttons:first') );
                                break
                        }
                        break;
                    case 'questions':
                        switch ( action )
                        {
                            case 'newsfeedUpdStatus':
                                var content = $( document.getElementById(id) );
                                
                                instance.addSmileButton( id, content.find('textarea.ow_newsfeed_status_input:first'), content.find('span.buttons:first') );

                                var textarea = content.find('textarea[name="question"]');
                                _elements.textarea['questions'] = textarea;

                                $( '<a>', {class: 'smileys_btn smileys_btn_question', title: window.smileysParams.label} )
                                    .appendTo( content.find('form[name="questions_add"] span.ow_attachment_btn:first') )
                                    .on( 'click', function()
                                    {
                                        _elements.currentTextarea = 'questions';
                                        instance.showFloatBox();
                                    });
                                break;
                            case 'page':
                                var textarea = $('form[name="questions_add"] textarea[name="question"]');
                                _elements.textarea['questionspage'] = textarea;

                                $( '<a>', {class: 'smileys_btn smileys_btn_question', title: window.smileysParams.label} )
                                    .appendTo($('form[name="questions_add"] div.q-save-c') )
                                    .on( 'click', function()
                                    {
                                        _elements.currentTextarea = 'questionspage';
                                        instance.showFloatBox();
                                    });
                                    break;
                        }
                        break;
                    case 'equestions':
                        switch ( action )
                        {
                            case 'newsfeedUpdStatus':
                                var content = $( document.getElementById(id) );
                                var updateStatusForm = content.find( 'form[name="newsfeed_update_status"]' );
                                var questionForm = content.find( 'form[name="questions_add"]' );
                                
                                instance.addSmileButton( 'status', updateStatusForm.find('textarea[name="status"]'), updateStatusForm.find('span.buttons:first') );
                                instance.addSmileButton( 'question', questionForm.find('textarea[name="question"]'), questionForm.find('span.buttons:first') );
                                break;
                            case 'question':
                                var content = $( 'form[name="questions_add"]' );

                                instance.addSmileButton('questionPage', content.find('textarea[name="question"]'), content.find('span.buttons:first'));
                                $('.ql_string').each(function()
                                {
                                    var data = {text: $(this).html()};
                                    OW.trigger('smileys.renderText', data);
                                    $(this).html(data.text);
                                })
                                break;
                        }
                        break;
                }
            },
            
            showFloatBox: function()
            {
                _elements.smileysFloatBox = new OW_FloatBox(
                {
                    $title: window.smileysParams.label,
                    width: '800px',
                    $contents: _elements.panel
                });

                _elements.smileysFloatBox.bind( 'show', function()
                {
                    _methods.loadSmileys( _elements.panelCaptions[0] );
                });
                
                return _elements.smileysFloatBox;
            }
        };
    }
    
    OW.bind('smileys.renderText', function( data )
    {
        if ( !data || !data.text )
        {
            return;
        }

        data.text = data.text.replace(/\[([^/]+\/[^/]+)\]/ig, '<img src="' + window.smileysParams.smileysUrl + '$1.gif' + '"/>');
    });

    OW.bind('smileys.addSmileys', function( data )
    {
        var keys;

        if ( !data || data !== Object(data) || (keys = Object.keys(data)).length === 0 )
        {
            return;
        }

        var required = ['key', 'textarea', 'toolbar'];

        if ( required.some(function( item )
        {
            return keys.indexOf(item) === -1;
        }) )
        {
            return;
        }

        _elements.textarea['shoutbox'] = $('form[name="' + data.key + '"] textarea[name="' + data.textarea + '"]');

        var btn = $('<div>', {class: 'ow_left shoutbox_bold smileys_btn', title: window.smileysParams.label})
            .on( 'click', function()
            {
                _elements.currentTextarea = 'shoutbox';
                instance.showFloatBox();
            });

        switch ( data.positioin )
        {
            case 'append':
                btn.appendTo($(data.toolbar));
                break;
            case 'prepend':
            default:
                btn.prependTo($(data.toolbar));
                break;
        }
    });

    return {
        getInstance: function()
        {
            if ( !instance )
            {
                instance = _construct();
            }
            
            return instance;
        }
    };
})( jQuery );
