var ShareOnFriendFeed = new function()
{   
    this.bDialogCreated = false;
    this.oOverlayEl = null;
    this.oFormEl = null;
    this.oLoadingEl = null;
    this.oCloseBtnEl = null;
 
    this._init = function()
    {
        //document.addEvent("click", this._handleClick.bindWithEvent( this ) );
        
        var aAnchors = document.getElementsByTagName("a");
        var iCount = aAnchors.length;
        for(var i = 0; i < iCount; i++)
        {
            if(aAnchors[i].href == ShareOnFriendFeed.ACCESSIBLE_PUBLISH_URL)
            {
                $(aAnchors[i]).addEvent("click", this._handleShowShareDialogClick.bindWithEvent( this ) );
            }
        }
    };
    
    this._handleShowShareDialogClick = function(oEvent)
    {  
        if( this.bDialogCreated == false )
        { 
            var sSrc = ShareOnFriendFeed.AJAX_GET_HTML_URL + "?";
            var sQueryString = "soff_template=PublishMessageTemplate.html" + "&";
            sQueryString += "soff_callback=ShareOnFriendFeed._publishTemplateFetchCallback";
            
            // Get dialog html
            this._createScript(sSrc + sQueryString);
            
            ShareOnFriendFeed.clickedAnchor = this._getAnchor(oEvent.target || oEvent.srcElement);
            
            this.bDialogCreated = true;
        }
        else
        {
            this._showShareDialog();
        }
        
        return false;   
    };
    
    this._publishTemplateFetchCallback = function(oResult)
    {
        // change context of this to object instance
        ShareOnFriendFeed._createShareDialog.call(ShareOnFriendFeed, oResult);
    };
    
    this._createShareDialog = function(oResult)
    {
        var oAnchor = $(ShareOnFriendFeed.clickedAnchor);
        ShareOnFriendFeed.clickedAnchor = null;
        
        var oPositions = oAnchor.getPosition();
        var oSize = oAnchor.getSize();
        this.oOverlayEl = new Element('div', {
                                            'id': 'soff_overlay'
                                          });
        this.oOverlayEl.setOpacity(0.5);                                        
        document.body.appendChild(this.oOverlayEl);
        
        var oTmpEl = new Element( 'div', {
                                            'id': 'soff_form_holder',
                                            'html': oResult.HTML
                                        });
                                        
        // Position next to the link                                        
        this.oFormEl = $(oTmpEl.firstChild);        
        this.oFormEl.setStyle("top", oPositions.y + oSize.y);
        this.oFormEl.setStyle("left", oPositions.x + oSize.x);
        this.oFormEl.setOpacity(0);
        
        document.body.appendChild(this.oFormEl);
        //oOverlay.appendChild(this.oFormEl);
        
        // This doesn't appear to work.
        //oForm.addEvent("submit", this._shareOnFriendFeed.bindWithEvent( this ) );
        this.oFormEl.onsubmit = this._shareOnFriendFeed.bindWithEvent( this );
        
        var sTitle = document.title;
        $("soff_title").value = sTitle;
        
        this.oLoadingEl = $("soff_loading");
        this.oLoadingEl.setOpacity(0.5);
        
        this.oCloseBtnEl = $("soff_close");
        this.oCloseBtnEl.addEvent( "click", this._closeBtnHandler.bindWithEvent(this) );
        
        this._showShareDialog();
    };
    
    this._closeBtnHandler = function(oEvent)
    {
        this._closeShareDialog();
        return false;
    };
    
    this._showShareDialog = function()
    {
        // Fade in form
        var myFx = new Fx.Tween(this.oFormEl);
        myFx.start('opacity', '0', '1');
        this.oOverlayEl.setStyle("display", "block");
        this.oFormEl.setStyle("display", "block");
    };
    
    this._closeShareDialog = function()
    {
        this.oOverlayEl.setStyle("display", "none");
        this.oFormEl.setStyle("display", "none");
    };
        
    /**
     * Form submit handler which submits the provided information
     * to the FriendFeed service.
     */
    this._shareOnFriendFeed = function()
    {
        var oNickName = $("soff_nickname");
        var oRemoteKey = $("soff_remotekey");
        var oTitle = $("soff_title");
    
        var iInvalidCount = 0;
        iInvalidCount += ( this._validate(oNickName) ? 0:1 );
        iInvalidCount += ( this._validate(oRemoteKey) ? 0:1 );
        iInvalidCount += ( this._validate(oTitle) ? 0:1 );
        
        if(iInvalidCount == 0)
        {
            var sNickName = oNickName.value;
            var sRemoteKey = oRemoteKey.value;
            var sTitle = oTitle.value;
            var sMessage = $("soff_message").value;
            var sLink = document.location.href;
            var sCallback = "ShareOnFriendFeed._messagePublishedCallback";
            
            this._showLoading();
            
            this.publishMessage(sNickName, sRemoteKey, sTitle, sLink, sMessage, sCallback);                      
        }
        
        return false;
    };
    
    this.publishMessage = function(sNickName, sRemoteKey, sTitle, sLink, sMessage, sCallback)
    {
        var sSrc = ShareOnFriendFeed.AJAX_PUBLISH_URL + "?";
        var sQueryString = "soff_nickname=" + sNickName + "&";
        sQueryString += "soff_remotekey=" + sRemoteKey + "&";
        sQueryString += "soff_title=" + escape( sTitle ) + "&";
        sQueryString += "soff_link=" + escape( sLink ) + "&";
        sQueryString += "soff_message=" + escape( sMessage ) + "&";
        sQueryString += "soff_callback=" + sCallback;
                
        this._createScript(sSrc + sQueryString);
    };
    
    this._messagePublishedCallback = function(oResult)
    {
        ShareOnFriendFeed._messagePublished.call(ShareOnFriendFeed, oResult);
    };
    
    this._messagePublished = function(oResult)
    {
        switch( oResult.Result )
        {
            case 0:
                // Pass
                alert("You message has been successfully published to your FriendFeed.");
                this._hideLoading();
                this._closeShareDialog();
                break;
            case 2:
                // Exception occurred
                if( oResult.ExceptionMessage.indexOf("401") != -1 )
                {
                    alert("Your username/email and password combination was not recognised by FriendFeed.");
                }
                else
                {
                    alert( oResult.ExceptionMessage );
                }
                this._hideLoading();
                break;
            default:
                alert("Publish failed for unknown reason.");
                this._hideLoading();
                break;

        }        
    };
    
    this._showLoading = function()
    {
        this.oLoadingEl.setStyle("display", "block");
    };
    
    this._hideLoading = function()
    {
        this.oLoadingEl.setStyle("display", "none");
    };
    
    this._validate = function(oFormEl)
    {
        var bValid = false;
        if( oFormEl.value.replace(" ", "").length == 0 )
        {
            oFormEl.addClass("soff-not-validated");
        }
        else
        {
            bValid = true;
            oFormEl.removeClass("soff-not-validated");
            oFormEl.addClass("soff-validated");
        }
        return bValid;
    };
    
    this._createScript = function(sSrc)
    {
        if( ShareOnFriendFeed.awaitingCallback == false )
        {
            var oScript = document.createElement("script");
            oScript.setAttribute("type", "text/javascript");
            oScript.src = (sSrc);
            
            oScript.id = ShareOnFriendFeed.scriptIDPrefix + (ShareOnFriendFeed.scriptCreateCount++);
                    
            var aHeads = document.getElementsByTagName("head");
            if(aHeads.length > 0)
            {
                aHeads[0].appendChild(oScript);
            }
            else if(document.body)
            {
                document.body.appendChild(oScript);
            }
            
            ShareOnFriendFeed.awaitingCallback = true;
        }
        else
        {
            alert("please wait for the previous request to complete");
        }
    };
    
    this.handleCallback = function( oResult )
    {
        var sScriptID = ShareOnFriendFeed.scriptIDPrefix + (ShareOnFriendFeed.scriptCreateCount-1);
        var oScript = document.getElementById( sScriptID );
        var oParent = oScript.parentNode || oScript.parentElement;
        if(oParent)
        {
            oParent.removeChild( oScript );
        }
        
        ShareOnFriendFeed.awaitingCallback = false;
        
        eval( oResult.Callback )( oResult );
    };
    
    this._getAnchor = function(oEl)
    {
        var oAnchor = null;
        if( oEl == null || oEl.tagName.toLowerCase() == "body" )
        {
            // Either the element was not set or no more
            // parent nodes can be found
        }
        if( oEl.tagName.toLowerCase() == "a" )
        {
            oAnchor = oEl;
        }
        else if( oEl.parentNode )
        {
            oAnchor = this._getAnchor( oEl.parentNode );
        }
        return oAnchor;
    };
    
    window.addEvent("domready", this._init.bindWithEvent( this ) );
};
ShareOnFriendFeed.scriptCreateCount = 0;
ShareOnFriendFeed.scriptIDPrefix = "SOFF";
ShareOnFriendFeed.awaitingCallback = false;
ShareOnFriendFeed.clickedAnchor = null;

ShareOnFriendFeed.BASE_URL = "http://share.leggetter.co.uk/ShareOnFriendFeed/";
ShareOnFriendFeed.AJAX_GET_HTML_URL = ShareOnFriendFeed.BASE_URL + "Ajax/GetHTML/";
ShareOnFriendFeed.AJAX_PUBLISH_URL = ShareOnFriendFeed.BASE_URL + "Ajax/PublishMessage/";
ShareOnFriendFeed.ACCESSIBLE_PUBLISH_URL = ShareOnFriendFeed.BASE_URL + "Accessible/PublishMessage/";