<?php

/**
 * 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
 */

/**
 * 
 *
 * @author Kairat Bakytow <kainisoft@gmail.com>
 * @package ow_plugins.smileys.classes
 * @since 1.0
 */
class SMILEYS_CLASS_HtmlDocument 
{
    CONST PATTERN = '/<img[^>]*(?:(?<=src=")(?!.+\/ow_userfiles\/plugins\/smileys\/images\/.+\/.+\.gif")).*>/i';
    
    private static $classInstance;
    
    public static function getInstance()
    {
        if ( self::$classInstance === null )
        {
            self::$classInstance = new self();
        }

        return self::$classInstance;
    }
    
    private $document;
    private $plugin;
    
    private function __construct()
    {
        $this->document = OW::getDocument();
        $this->plugin = OW::getPluginManager()->getPlugin( 'smileys' );
    }

    public function replaceBaseWysisyg()
    {
        $js = UTIL_JsGenerator::composeJsString( ';window.smileysParams = {"url":{$url}, "smileysUrl":{$smileysUrl}, "adminRsp":{$rsp}, "label":{$label}};', 
                array('url' => OW::getRouter()->urlForRoute('smileys.smileLoader'),
                      'smileysUrl' => $this->plugin->getUserFilesUrl() . 'images/',
                      'rsp' => OW::getRouter()->urlForRoute('smileys.admin-rsp'),
                      'label' => OW::getLanguage()->text('smileys', 'smileys')) );
        $this->document->addScriptDeclarationBeforeIncludes( $js );

        $this->document->addStyleDeclaration( '.smileys-btn{margin:0 5px;float:right}.smileys-btn:hover{text-decoration:underline}.smileys-header{text-align:left;text-transform:uppercase}.smile{margin:3px}.smile:hover{outline:1px solid #cccccc;cursor:pointer}' );
        $this->document->addStyleDeclaration( '.smileys-btn2{background:url(' . $this->plugin->getStaticUrl() . 'images/wysiwyg.png) no-repeat scroll -242px 1px;border: 1px solid #ccc;
    border-radius: 2px;
    cursor: pointer;
    float: left;
    height: 22px;
    overflow: hidden;
    position: absolute;
    right: 26px;
    text-decoration: none;
    width: 21px;}
            ' );
        
        $this->document->addStyleDeclaration( '.smileys-btn3{background:url(' . $this->plugin->getStaticUrl() . 'images/wysiwyg.png) no-repeat scroll -242px 1px;border: 1px solid #ccc;
    border-radius: 2px;
    cursor: pointer;
    float: left;
    height: 22px;
    overflow: hidden;
    right: 26px;
    text-decoration: none;
    width: 21px;}
            ' );

        $javaScripts = $this->document->getJavaScripts();
        
        if ( OW::getPluginManager()->isPluginActive('mailbox') )
        {
            $this->document->addOnloadScript(';OW.bind("mailbox.open_dialog", function( data )
            {
                window.smileys.getInstance().addSmileChat(data.opponentId);
            });', 9999);
            
            $this->document->addScriptDeclaration(';OW.bind("mailbox.update_message", function( data )
            {
                $("#" + "main_tab_contact_" + data.opponentId + " .ow_dialog_in_item p").each(function()
                {
                    $(this).html($(this).html().replace(/\[([^/]+\/[^/]+)\]/ig, "<img src=\'" + window.smileysParams.smileysUrl + "$1.gif" + "\' />"));
                });
            });');
            
            $this->document->addScriptDeclaration(';OW.bind("mailbox.after_write_mail_message", function( data )
            {
                $("#conversationLog .ow_dialog_in_item p").each(function()
                {
                    $(this).html($(this).html().replace(/\[([^/]+\/[^/]+)\]/ig, "<img src=\'" + window.smileysParams.smileysUrl + "$1.gif" + "\' />"));
                });
                
                $("#conversationLog .ow_mailbox_message_content").each(function()
                {
                    $(this).html($(this).html().replace(/\[([^/]+\/[^/]+)\]/ig, "<img src=\'" + window.smileysParams.smileysUrl + "$1.gif" + "\' />"));
                });
            });');
            
            $this->document->addScriptDeclaration(';OW.bind("mailbox.dialogLogLoaded", function( data )
            {
                $("#" + "main_tab_contact_" + data.opponentId + " .ow_dialog_in_item p").each(function()
                {
                    $(this).html($(this).html().replace(/\[([^/]+\/[^/]+)\]/ig, "<img src=\'" + window.smileysParams.smileysUrl + "$1.gif" + "\' />"));
                });
                
                window.smileys.getInstance().addSmileChat(data.opponentId);
                OW.trigger("smileys.updateScroll", data.opponentId);
            });');
            
            $this->document->addOnloadScript(';OW.bind("mailbox.update_chat_message", function( data )
            {
                $("#" + "main_tab_contact_" + data.recipientId + " .ow_dialog_in_item p").each(function()
                {
                    $(this).html($(this).html().replace(/\[([^/]+\/[^/]+)\]/ig, "<img src=\'" + window.smileysParams.smileysUrl + "$1.gif" + "\' />"));
                });
            });', 9999);
            
            $this->document->addOnloadScript(';OW.bind("mailbox.message", function( data )
            {
                $("#" + "main_tab_contact_" + data.senderId + " .ow_dialog_in_item p").each(function()
                {
                    $(this).html($(this).html().replace(/\[([^/]+\/[^/]+)\]/ig, "<img src=\'" + window.smileysParams.smileysUrl + "$1.gif" + "\' />"));
                });
            });', 9999);
            
            $this->document->addOnloadScript(';OW.bind("smileys.updateScroll", function( opponentId )
            {
                try {
                for ( var id in OW.Mailbox.contactManagerView.dialogs )
                {
                    var dialog = OW.Mailbox.contactManagerView.dialogs[id];
                    
                    if ( dialog.model.opponentId == opponentId )
                    {
                    
                        setTimeout(function(){dialog.scrollDialog();}, 200);
                        break;
                    }
                }
                }
                catch (e){}
            });', 9999);
            
            $this->document->addOnloadScript(';window.smileys.getInstance().addSmileNewMessage();', 9999);
        }
        
        $requestHandler = array();

        $requestHandler['PHOTO_CTRL_Upload']  = array( 'submit' );
        $requestHandler['VIDEO_CTRL_Add']     = array( 'index' );
        $requestHandler['EVENT_CTRL_Base']    = array( 'add' );
        $requestHandler['GROUPS_CTRL_Groups'] = array( 'create' );
        $requestHandler['LINKS_CTRL_Save']    = array( 'index' );
        
        $handler = OW::getRequestHandler()->getHandlerAttributes();
        
        if ( $handler[OW_RequestHandler::ATTRS_KEY_CTRL] == 'MAILBOX_CTRL_Messages' && $handler[OW_RequestHandler::ATTRS_KEY_ACTION] == 'index' )
        {
            $this->document->addOnloadScript(';window.smileys.getInstance().addSmileChatForm();
                OW.bind("mailbox.update_message", function()
                {
                    $("#conversationLog .ow_dialog_in_item p").each(function()
                    {
                        $(this).html($(this).html().replace(/\[([^/]+\/[^/]+)\]/ig, "<img src=\'" + window.smileysParams.smileysUrl + "$1.gif" + "\' />"));
                    });
                    
                    $("#conversationLog .ow_mailbox_message_content").each(function()
                    {
                        $(this).html($(this).html().replace(/\[([^/]+\/[^/]+)\]/ig, "<img src=\'" + window.smileysParams.smileysUrl + "$1.gif" + "\' />"));
                    });
                });

                OW.bind("mailbox.conversation_marked_read", function()
                {
                    $("#conversationLog .ow_dialog_in_item p").each(function()
                    {
                        $(this).html($(this).html().replace(/\[([^/]+\/[^/]+)\]/ig, "<img src=\'" + window.smileysParams.smileysUrl + "$1.gif" + "\' />"));
                    });
                    
                    OW.trigger("smileys.scrollDialog");
                });
                
                OW.bind("mailbox.mark_message_read", function()
                {
                    $("#conversationLog .ow_dialog_in_item p").each(function()
                    {
                        $(this).html($(this).html().replace(/\[([^/]+\/[^/]+)\]/ig, "<img src=\'" + window.smileysParams.smileysUrl + "$1.gif" + "\' />"));
                    });
                    
                    OW.trigger("smileys.scrollDialog");
                });
                
                OW.bind("mailbox.history_loaded", function()
                {
                    $(".ow_mailbox_message_content,.ow_dialog_in_item p", "#conversationLog").each(function()
                    {
                        $(this).html($(this).html().replace(/\[([^/]+\/[^/]+)\]/ig, "<img src=\'" + window.smileysParams.smileysUrl + "$1.gif" + "\' />"));
                    });
                });
                
                OW.bind("mailbox.render_conversation_item", function( data )
                {
                    var item = data.$el.find(".ow_mailbox_convers_preview");
                    
                    if ( item.length )
                    {
                        item.html(item.html().replace(/\[([^/]+\/[^/]+)\]/ig, "<img src=\'" + window.smileysParams.smileysUrl + "$1.gif" + "\' />"));
                    }
                });
                ', 9999);
            
                $this->document->addOnloadScript(';OW.bind("smileys.scrollDialog", function()
                {
                    try 
                    {
                        setTimeout(function(){OW.Mailbox.conversationController.scrollDialog();}, 200);
                    }
                    catch (e){}
                });', 9999);
        }
        elseif ( $handler[OW_RequestHandler::ATTRS_KEY_CTRL] == 'QUESTIONS_CTRL_List' )
        {
            $this->document->addOnloadScript( UTIL_JsGenerator::composeJsString(';window.smileys.getInstance().noConflict({$pluginKey}, {$action});',
                array('pluginKey' => 'questions', 'action' => 'page' )) );
        }
        
        if ( array_key_exists($handler[OW_RequestHandler::ATTRS_KEY_CTRL], $requestHandler) && 
            in_array($handler[OW_RequestHandler::ATTRS_KEY_ACTION], $requestHandler[$handler[OW_RequestHandler::ATTRS_KEY_CTRL]]) )
        {
            return;
        }
        
        if ( !empty($javaScripts['items'][1000]) )
        {
            foreach ( $javaScripts['items'][1000]['text/javascript'] as $key => $script )
            {
                if ( strpos($script, '/ow_static/plugins/base/js/htmlarea.js') !== false )
                {
                    $javaScripts['items'][1000]['text/javascript'][$key] = $this->plugin->getStaticJsUrl() . 'htmlarea.js';
                    $this->document->setJavaScripts( $javaScripts );

                    $js = UTIL_JsGenerator::composeJsString( ';window.smileysHtmlAreaData = {"smileys":{$smileys}}', array('smileys' => OW::getLanguage()->text('smileys', 'smileys')) );
                    $this->document->addScriptDeclarationBeforeIncludes( $js );
                    
                    $this->document->addScriptDeclaration( ';window.smileys.getInstance();' );
                    
                    $styleSheets = $this->document->getStyleSheets();
        
                    if ( !empty($styleSheets['items'][1000]) )
                    {
                        foreach ( $styleSheets['items'][1000]['all'] as $key => $style )
                        {
                            if ( strpos($style, '/ow_static/plugins/base/css/htmlarea.css') !== false )
                            {
                                $styleSheets['items'][1000]['all'][$key] = $this->plugin->getStaticCssUrl() . 'htmlarea.css';
                                break;
                            }
                        }

                        $this->document->setStyleSheets( $styleSheets );
                    }
                    
                    break;
                }
            }
        }
    }
    
    public function replaceBaseComment()
    {
        $this->document->addStyleDeclaration( '.smileys_btn{background:url(' . $this->plugin->getStaticUrl() . 'images/wysiwyg.png) no-repeat;background-position:-241px 0;width:22px;cursor:pointer;float:left;height:22px;overflow:hidden;text-decoration:none;margin:1px 0 0 0;}
            .smileys_btn_IChat{background:url(' . $this->plugin->getStaticUrl() . 'images/wysiwyg.png) no-repeat;background-position:-242px 0;outline:1px solid #CCCCCC;width:21px;cursor:pointer;float:left;height:21px;overflow:hidden;text-decoration:none;margin:4px 0 0 5px;}' );
        
        $this->document->addStyleDeclaration( '.smileys_btn_2{background:url(' . $this->plugin->getStaticUrl() . 'images/wysiwyg.png) no-repeat scroll -242px 0;border: 1px solid #ccc;    border-radius: 2px;    cursor: pointer;    float: left;    height: 20px;    margin: 1px 0 0;    overflow: hidden;    position: absolute;    right: 30px;    text-decoration: none;    top: 7px;    width: 21px;    }' );
        
        $this->document->addScriptDeclaration( ';OW.bind("base.comments_list_init",function()
            {
                $(".ow_comments_content",this.$context).each(function()
                {
                    var self = $(this);
                    self.data("origCont", self.html());
                    self.html(self.html().replace(/\[([^/]+\/[^/]+)\]/ig,"<img src=\'"+window.smileysParams.smileysUrl+"$1.gif"+"\'/>"));
                });
                window.smileys.getInstance().addSmile("cta"+this.cid);
            });' );
        $this->document->addScriptDeclaration( ';OW.bind("base.comments_list_init",function()
            {
                if(["profile-cover", "avatar-change"].indexOf(this.entityType)!==-1)return;
                var closest=$(this.$context).closest(".ow_newsfeed_body"),content;
                if ( (content=closest.find(".ow_newsfeed_body_status")).length )
                {
                    content.html(content.html().replace(/\[([^/]+\/[^/]+)\]/ig,"<img src=\'"+window.smileysParams.smileysUrl+"$1.gif"+"\'/>"));
                }
                else
                {
                    if ( this.entityType == "photo_comments") return;
                    closest.find(".ow_newsfeed_content").each(function()
                    {
                        var self=$(this);
                        self.data("origCont",self.html());
                        self.html(self.html().replace(/\[([^/]+\/[^/]+)\]/ig,"<img src=\'"+window.smileysParams.smileysUrl+"$1.gif"+"\'/>"));
                    });
                }
            });');
        $this->document->addScriptDeclaration( ';OW.bind("onChatAppendMessage",function(message)
            {
                var p=message.find("p");
                p.html(p.html().replace(/\[([^/]+\/[^/]+)\]/ig,"<img src=\'"+window.smileysParams.smileysUrl+"$1.gif"+"\'/>"));
            });' );
        $this->document->addScriptDeclaration( ';OW.bind("consoleAddItem",function(items)
            {
                for(var item in items)
                {
                    items[item].html=items[item].html.replace(/\[([^/]+\/[^/]+)\]/ig,"<img src=\'"+window.smileysParams.smileysUrl+"$1.gif"+"\'/>");
                }
            });');
        $this->document->addScriptDeclaration( ';OW.bind("photo.onBeforeLoadFromCache",function(items)
            {
                OW.bind("base.comments_list_init",function()
                {
                    $(".ow_comments_content",this.$context).each(function()
                    {
                        var self = $(this);
                        self.data("origCont", self.html());
                        self.html(self.html().replace(/\[([^/]+\/[^/]+)\]/ig,"<img src=\'"+window.smileysParams.smileysUrl+"$1.gif"+"\'/>"));
                    });
                    window.smileys.getInstance().addSmile("cta"+this.cid);
                });
                
                OW.bind("mailbox.open_dialog", function( data )
                {
                    window.smileys.getInstance().addSmileChat(data.opponentId);
                });
            });
            
            OW.bind("photo.onFloatboxClose",function(items)
            {
                OW.bind("base.comments_list_init",function()
                {
                    $(".ow_comments_content",this.$context).each(function()
                    {
                        var self = $(this);
                        self.data("origCont", self.html());
                        self.html(self.html().replace(/\[([^/]+\/[^/]+)\]/ig,"<img src=\'"+window.smileysParams.smileysUrl+"$1.gif"+"\'/>"));
                    });
                    window.smileys.getInstance().addSmile("cta"+this.cid);
                });
            });');
        
        if ( OW::getPluginManager()->isPluginActive('questions') )
        {
            $this->document->addStyleDeclaration('.smileys_btn_question{margin-top: 5px;}');
            $this->document->addOnloadScript( UTIL_JsGenerator::composeJsString(';window.smileys.getInstance().noConflict({$pluginKey}, {$action}, {$id});',
                array('pluginKey' => 'questions', 'action' => 'newsfeedUpdStatus', 'id' => 'feed1' )) );
            $this->document->addOnloadScript( 'var smileysContent=$(".q-text");if(!smileysContent.length)return; smileysContent.html(smileysContent.html().replace(/\[([^/]+\/[^/]+)\]/ig,"<img src=\'"+window.smileysParams.smileysUrl+"$1.gif"+"\'/>"));' );
        }
        else if ( OW::getPluginManager()->isPluginActive('equestions') )
        {
            $this->document->addStyleDeclaration('.smileys_btn_question{margin-top: 5px;}');
            $this->document->addOnloadScript( UTIL_JsGenerator::composeJsString(';window.smileys.getInstance().noConflict({$pluginKey}, {$action}, {$id});',
                array('pluginKey' => 'equestions', 'action' => 'newsfeedUpdStatus', 'id' => 'gtabs-1' )) );
            $this->document->addOnloadScript( 'var smileysContent=$(".q-text");if(!smileysContent.length)return; smileysContent.html(smileysContent.html().replace(/\[([^/]+\/[^/]+)\]/ig,"<img src=\'"+window.smileysParams.smileysUrl+"$1.gif"+"\'/>"));' );
            
            $handler = OW::getRequestHandler()->getHandlerAttributes();
            
            if ( $handler[OW_RequestHandler::ATTRS_KEY_CTRL] == 'EQUESTIONS_CTRL_List' )
            {
                $this->document->addOnloadScript( UTIL_JsGenerator::composeJsString(';window.smileys.getInstance().noConflict({$pluginKey}, {$action}, {$id});',
                    array('pluginKey' => 'equestions', 'action' => 'question', 'id' => 'gtabs-1' )) );
            }
        }
        
        if ( OW::getPluginManager()->isPluginActive('shoutbox') )
        {
            $this->document->addScriptDeclaration(';window.smileys.getInstance();');
        }
        
        $this->document->addScript( $this->plugin->getStaticJsUrl() . 'smileys.js' );
    }
    
    public function addSmileToNewsfeedUpdateStatus( OW_Event $event )
    {
        $params = $event->getParams();
        
        if ( OW::getPluginManager()->isPluginActive('attachments') )
        {
            $this->document->addScriptDeclaration( UTIL_JsGenerator::composeJsString(';window.smileys.getInstance().noConflict({$pluginKey}, {$action}, {$id});',
                array('pluginKey' => 'attachments', 'action' => 'newsfeedUpdStatus', 'id' => $params['feedAutoId'])), 'text/javascript', 1003 );
        }
        else
        {
            $this->document->addScriptDeclaration( UTIL_JsGenerator::composeJsString(';window.smileys.getInstance().addSmileToUpdateStatus({$feedId});',
                array('feedId' => $params['feedAutoId'])), 'text/javascript', 1003 );
        }
    }

    public function addSmileysToComment()
    {
        $params = json_decode( $_POST['params'] );
        
        if ( OW::getPluginManager()->isPluginActive('attachments') )
        {
            $js = UTIL_JsGenerator::composeJsString(';window.smileys.getInstance().noConflict({$pluginKey}, {$action}, {$id});',
                array('pluginKey' => 'attachments', 'action' => 'comments', 'id' => $params[7] ));
        }
        else
        {
            $js = UTIL_JsGenerator::composeJsString(';window.smileys.getInstance().addSmileToComment({$id});', 
                array('id' => $params[7] ) );
        }
        
        $this->document->addOnloadScript( $js, 1003 );
    }
}
