/**
 * Create namespace for this
 */
oSL.blogPageMaker = function(){
    /**
     * These vars will become private vars of created object (that)
     */
    var oHref = {}, //
 rsid, //
 action, //
 myArray, //
 curParentMid, //
 regexRsid = /(rsid=|\/p|\/thread)([0-9]+)/, // (&|-) // a=([a-zA-Z\-])(?:&[amp;]*)
 regexMid = /(replyid(?:=)*|showid(?:=))([0-9]+)/, // (?:(?:a=)(blogitem|nntp-thread)&)(?:.*)(reply(?:=)*|show(?:=))([0-9]+)
 sBaseUrl = '/index.php?a=', // blogitem or nntp-thread depending on aRes[1]
 sAction = 'blogitem', // nntp-thread pages have navbar div, the blog page does not
 oPanelConfig = {
        width: "770px",
        height: "700px",
        fixedcenter: true,
        constraintoviewport: true,
        underlay: "shadow",
        close: true,
        visible: false,
        draggable: true,
        modal: true
    }, //
 getRsid = function(){
        var aRes = regexRsid.exec(window.location.href);
        $Y.log('commentForm 32 ' + window.location.href + ' ' + $LANG.dump(aRes));
        if (aRes && aRes[2]) {
            rsid = aRes[2];
            //action = aRes[1];
            if ($('navbar')) {
                sAction = 'nntp-thread';
            }
            return aRes[2]; // aRes[2]
        }
        
        return null;
    }, //
 that = {};
    
    that.toString = function(){
        return 'object blogPage';
    }
    
    that.fHandleHover = function(o){
    
        var target = $E.getTarget(o), sSrc;
        if (target.nodeName && target.nodeName.toLowerCase() === 'img') {
            sSrc = target.getAttribute('src'); // s=t&ts
            if (/(\/img\/tiny\/|s=t&ts)/.test(sSrc) && (target.parentNode.nodeName.toLowerCase() === 'a')) {
                var srcnew = target.parentNode.getAttribute('href');
                $Y.log('commentForm 54 ' + target.parentNode.nodeName + ' a href: ' + srcnew);
                target.setAttribute('src', srcnew);
                //target.parentNode.parentNode.replaceChild(target.parentNode, target);
                var parentDiv = $D.getAncestorByTagName(target, 'div');
                $Y.log('commentForm 54 parentDiv: ' + parentDiv + ' target: ' + target);
                oSL.fAddIcon(target.parentNode);
                $LANG.later('500', this, function(){
                    parentDiv.replaceChild(target, target.parentNode)
                });
                
            }
            
        }
    }
    
    that.fHandleClick = function(o){
        // temporary for debugging
        // $E.stopEvent(o);
        var target = $E.getTarget(o), href;
        var oParsed;
        
        $Y.log('commentForm 77 this is: ' + this); // oSL
        if (target.nodeName && target.nodeName.toLowerCase() === 'a') {
        
            $Y.log('commentForm 40 clicked on ' + target.nodeName.toLowerCase() + 'class: ' + target.getAttribute('class'));
            href = target.getAttribute('href');
            
            $Y.log('commentForm 43 href: ' + href);
            
            //alert('click click mOFo target: ' + target + ' href: ' + href); // ?showid=975
            
            var myRsid = rsid || getRsid();
            $Y.log('commentForm 62 myRsid: ' + myRsid + ' rsid: ' + rsid);
            
            //alert('myRsid: ' + myRsid);
            
            oParsed = this.parseHref(href);
            //alert('oParsed: ' + $LANG.dump(oParsed));
            if (oParsed) {
                $Y.log('commentForm 65 oParsed: ' + $LANG.dump(oParsed));
                oHref = {
                    'mid': oParsed[2],
                    'rsid': rsid
                };
                $E.stopEvent(o);
                if (oParsed[1] === 'showid=') {
                    oSL.fAddIcon(target.parentNode, true);
                    this.fShowMessage();
                    //$LANG.later('200', this, this.fShowMessage);
                }
                else {
                    this.fMakeReplyPanel();
                }
                
            }
            
        }
    }
    
    that.parseHref = function(sHref){
    
        myArray = regexMid.exec(sHref);
        $Y.log('111 myArray: ' + $LANG.dump(myArray));
        if (myArray && myArray[1] && myArray[2]) {
            // sAction = myArray[1];
            return myArray;
        }
        
        return false;
    }
    
    that.fMakeReplyPanel = function(){
    
        $Y.log('commentForm 75 this is: ' + this);
        if (!$D.inDocument('commentPanel')) {
            var myPanel = document.createElement('div');
            myPanel.id = 'commentPanel';
            
            
            var hd = document.createElement('div');
            var bd = document.createElement('div');
            var ft = document.createElement('div');
            hd.setAttribute('class', 'hd');
            bd.setAttribute('class', 'bd');
            ft.setAttribute('class', 'ft');
            myPanel.appendChild(hd);
            myPanel.appendChild(bd);
            myPanel.appendChild(ft);
            $('bpcomments').appendChild(myPanel);
        }
        
        //The second argument passed to the
        //constructor is a configuration object:
        if (!this.formPanel) {
            this.formPanel = new $W.Panel("commentPanel", oPanelConfig);
            
            this.formPanel.setHeader('Reply form');
            
            this.formPanel.changeBodyEvent.subscribe(this.fAfterChange, this, true); // with 3rd true, oSL.fAfterChange will have this set to panel object
            this.formPanel.hideEvent.subscribe(oSL.blogPage.fClearPanelBody, this, true);
            
            this.formPanel.render('bpcomments');
        }
        this.formPanel.show();
        
        oSL.fAddIcon(this.formPanel.body);
        /**
         * getForm() will issue ajax request
         * get the html of the form
         * and a callback will use oSL.formPanel.setBody()
         * with the html of the new form
         *
         * the setBody in turn will fire the afterChange event
         * which will call fAfterChange()
         */
        this.getForm();
        
    }
    
    
    that.getForm = function(){
        var sUrl;
        $Y.log('commentForm 138 this: ' + this); // 
        if (oHref && oHref.mid && oHref.rsid) {
            sUrl = sBaseUrl + sAction + '&replyid=' + oHref.mid + '&rsid=' + oHref.rsid
        }
        else {
            alert('object oHref not available or url of reply link was not parsed');
        }
        $CONN.resetFormState();
        $CONN.asyncRequest("GET", sUrl, oSL.oFrm.fUploadCallback);
    }
    
    that.fAfterChange = function(sType, args, o){
        $Y.log('commentForm 136 this: ' + this, 'warn'); //object blogPage
        $E.removeListener('bpcomments', "click", oSL.blogPage.fHandleClick);
        
        if ($D.inDocument('uForm')) {
        
            if ($D.inDocument('mbody')) {
                this.editor = new $W.SimpleEditor('mbody', {
                    width: '600px',
                    height: '160px'
                });
                this.editor._defaultToolbar.buttonType = 'advanced';
                
                this.editor.render();
            }
            
            /**
             * parseForm()
             * should be after render()
             * because it will need access to RTE object
             * so it can use saveHTML() method to extract contents
             * of RTE and use it as textarea of the form.
             *
             * the parseForm is in formJax.js
             * it basically subscribes the form's
             * submit button as well as onSubmit event
             * to start async POST request to iframe
             * and also if there are any files to upload
             * it will initiate the file upload progress checks.
             *
             */
            oSL.parseForm();
            
        }
        
    }
    
    that.fClearPanelBody = function(){
        $Y.log('commentForm 171 this: ' + this, 'warn'); // object BlogPage
        $E.addListener('bpcomments', "click", oSL.blogPage.fHandleClick, oSL.blogPage, true);
        if (this.editor) {
            this.editor.destroy();
        }
        
        if (this.formPanel.body.firstChild && (this.formPanel.body.firstChild.id === 'replyForm')) {
        
            this.formPanel.body.removeChild(this.formPanel.body.firstChild);
            
        }
    }
    
    that.appendReply = function(sReply, mid){
        $Y.log('commentForm 185 this: ' + this + ' parent mid: ' + oHref.mid); // object blogPage
        var parentDiv = $('m' + oHref.mid), newDiv;
        if (parentDiv) {
            parentDiv.innerHTML = parentDiv.innerHTML + sReply;
        }
        else {
            $Y.log('commentForm 241 parent div not found', 'alert');
            /**
             * This is a comment to a blog post itself
             * in this case append it as a first child of
             * bpcomments div
             */
            newDiv = document.createElement('div');
            $('bpcomments').appendChild(newDiv);
            newDiv.innerHTML = sReply;
        }
        
        this.newDiv = $('m' + mid);
        $Y.log('commentForm 233 ' + this.newDiv);
        if (this.newDiv) {
            this.newDiv.scrollIntoView(true);
            setTimeout("oSL.fColorChange(oSL.blogPage.newDiv, '#00FF00', '#FFFFFF')", 1000);
        }
        
        /**
         * Remove the pannel with reply form
         */
        if (this.formPanel) {
            this.formPanel.hide();
        }
        
    }
    
    that.replaceMessage = function(sMessage){
        /**
         * Find div id m{oHref.mid}
         * find its child with class tc2
         * replace that child with sMessage
         */
        var containerDiv = $('m' + oHref.mid), tc2divs, tc2div;
        if (containerDiv) {
            tc2divs = $D.getElementsByClassName('tc2', 'div', containerDiv);
            $Y.log('commentForm 255 tc2divs ' + $LANG.dump(tc2divs));
            if (tc2divs) {
                tc2div = tc2divs[0];
                $Y.log('commentForm 258 ' + $LANG.dump(tc2div));
                tc2div.parentNode.removeChild(tc2div);
                containerDiv.innerHTML = sMessage + containerDiv.innerHTML;
            }
        }
    }
    
    that.fShowMessage = function(){
        var sUrl = sBaseUrl + sAction + '&rsid=' + rsid + '&showid=' + oHref.mid;
        $CONN.resetFormState();
        $CONN.asyncRequest("GET", sUrl, oSL.oFrm.fUploadCallback);
    }
    
    $Y.log('commentForm 279', "warn");
    return that;
    
} // end blogPageMaker
oSL.fHandleClick = function(o){



    var target = $E.getTarget(o), href;
    
    
    $Y.log('282 this is: ' + this);
    
    if (target.nodeName &&
    target.nodeName.toLowerCase() === 'a' &&
    $D.hasClass(target, 'repl')) {
        //$Y.log('this is: ' + this); // object HTMLDivElement
        
        $E.stopEvent(o);
        $Y.log(' 289 clicked on ' + target.nodeName.toLowerCase() + 'class: ' + target.getAttribute('class'));
        href = target.getAttribute('href');
        //href = '/index.php?a=blogitem&reply=575&rsid=84590&title=from_OE';
        $Y.log('292 href: ' + href);
        
        //alert(href);
        /**
         * Links may look like these:
         * /p84590-from_OE/reply575.html
         /index.php?a=blogitem&reply=575&rsid=84590&title=from_OE
         */
        //myArray = myRegex.exec(href);
        /*
         $Y.log('myArray: ' + myArray); // null if no matches
         if (!myArray) {
         myArray = re.exec(href);
         }
         $Y.log('num matches: ' + myArray.length + ' matches: ' + $LANG.dump(myArray));
         
         */
        this.parseHref(href);
        this.fMakeReplyPanel();
        
    }
}
oSL.parseHref = function(sHref){
    var oRes, myArray, myRegex = /\/p([0-9]+)(?:.*)\/reply([0-9]+)/, //
 myRegex2 = /((?:a=)(blogitem|nntp-thread)&)(?:.*)(?:replyid=)([0-9]+)(?:.*)(?:rsid=)([0-9]+)/;
    
    myArray = myRegex.exec(sHref);
    if (myArray && myArray[1] && myArray[2]) {
        $Y.log('318 myRegex OK');
        oRes = {
            rsid: myArray[1],
            mid: myArray[2]
        }
    }
    else {
        myArray = myRegex2.exec(sHref);
        $Y.log('326 myArray: ' + $LANG.dump(myArray));
        if (myArray && myArray[1] && myArray[2]) {
            oRes = {
                rsid: myArray[2],
                mid: myArray[1]
            }
        }
    }
    
    this.oHref = oRes;
}

oSL.fMakeReplyPanel = function(){

    $Y.log('commentForm 246 this is: ' + this);
    if (!$D.inDocument('commentPanel')) {
        var myPanel = document.createElement('div');
        myPanel.id = 'commentPanel';
        
        
        var hd = document.createElement('div');
        var bd = document.createElement('div');
        var ft = document.createElement('div');
        hd.setAttribute('class', 'hd');
        bd.setAttribute('class', 'bd');
        ft.setAttribute('class', 'ft');
        myPanel.appendChild(hd);
        myPanel.appendChild(bd);
        myPanel.appendChild(ft);
        $('bpcomments').appendChild(myPanel);
    }
    
    //The second argument passed to the
    //constructor is a configuration object:
    if (!this.formPanel) {
        this.formPanel = new $W.Panel("commentPanel", {
            width: "770px",
            height: "700px",
            fixedcenter: true,
            constraintoviewport: true,
            underlay: "shadow",
            close: true,
            visible: false,
            draggable: true,
            modal: true
        });
        
        this.formPanel.setHeader('Reply form');
        //this.formPanel.setBody('please wait...');
        this.formPanel.changeBodyEvent.subscribe(this.fAfterChange, this, true); // with 3rd true, oSL.fAfterChange will have this set to panel object
        this.formPanel.hideEvent.subscribe(function(o){
            /**
             * Add listener back because it was removed on panel hideEvent
             */
            $E.addListener('bpcomments', "click", oSL.fHandleClick, oSL, true);
            if (oSL.editor) {
                oSL.editor.destroy();
            }
            
            if (this.body.firstChild && (this.body.firstChild.id === 'replyForm')) {
                //alert('removing reply form');
                this.body.removeChild(this.body.firstChild);
                
            }
        })
        //this.formPanel.subscribe('changeBody', this.fAfterChange);
        this.formPanel.render('bpcomments');
    }
    this.formPanel.show();
    //myPanel.cfg.setProperty("underlay", "matte");
    this.fAddIcon(this.formPanel.body);
    /**
     * getForm() will issue ajax request
     * get the html of the form
     * and a callback will use oSL.formPanel.setBody()
     * with the html of the new form
     *
     * the setBody in turn will fire the afterChange event
     * which will call fAfterChange()
     */
    this.getForm();
    
}
/**
 * This method called  ONLY
 * after the new html form
 * is rendered inside the panel body
 * It attaches the RTE editor to form's
 * textarea
 *
 * @param {Object} sType
 * @param {Object} args
 * @param {Object} o
 */
oSL.fAfterChange = function(sType, args, o){

    $E.removeListener('bpcomments', "click", oSL.fHandleClick);
    //alert('this is:' + this + '\nsType: ' + sType + '\no is ' + o + '\nargs is: ' + args); // args is the content of the body: html string
    //alert('form: ' + $('uForm') + '\npbar: ' + $('pbar'));
    //  $('pbar').innerHTML = 'Progress bar'; // it works - the entire html string is not in the DOM 
    if ($D.inDocument('uForm')) {
    
    
        //create the RTE:
        
        this.editor = new $W.SimpleEditor('mbody', {
            width: '600px',
            height: '160px'
        });
        this.editor._defaultToolbar.buttonType = 'advanced';
        
        //attach the Editor's reusable property-editor
        //panel to an element inside our main Dialog --
        //this allows it to get focus even when the Dialog
        //is modal:
        /*
         this.editor.on('windowRender', function(){
         $('rtediv').appendChild(this.get('panel').element);
         });
         */
        //render the editor explicitly into a container
        //within the Dialog's DOM:
        this.editor.render();
        
        /**
         * parseForm()
         * should be after render()
         * because it will need access to RTE object
         * so it can use saveHTML() method to extract contents
         * of RTE and use it as textarea of the form.
         *
         * the parseForm is in formJax.js
         * it basically subscribes the form's
         * submit button as well as onSubmit event
         * to start async POST request to iframe
         * and also if there are any files to upload
         * it will initiate the file upload progress checks.
         *
         */
        this.parseForm();
        
    }
    
    
}
oSL.getForm = function(){

    $Y.log('commentForm 183 this: ' + this); // object oSL
    if (this.oHref && this.oHref.mid && this.oHref.rsid) {
        sUrl = '/index.php?a=blogitem&replyid=' + this.oHref.mid + '&rsid=' + this.oHref.rsid
    }
    else {
        alert('object this.oHref not available or url of reply link was not parsed');
    }
    $CONN.resetFormState();
    $CONN.asyncRequest("GET", sUrl, this.oFrm.fUploadCallback);
}

/**
 * subscribe to onClick inside the bpcomments block
 */
//$E.addListener('bpcomments', "click", oSL.fHandleClick, oSL, true);



$E.onDOMReady(function(){
    $Y.log('commentForm 442 ' + window.location.href); //http://webmaster.sharedlog.com/p84591-after_some_changes/page1.html?show=606
    oSL.blogPage = oSL.blogPageMaker();
    $E.addListener('yui-main', "click", oSL.blogPage.fHandleClick, oSL.blogPage, true);
    $E.addListener('bpcomments', "mouseover", oSL.blogPage.fHandleHover, oSL.blogPage, true); // bpbody
    //$E.addListener('blog_post', "mouseover", oSL.blogPage.fHandleHover, oSL.blogPage, true);

});

