/**
 * 
 * @param debug
 */

mdp.app.simpleTwitterPopup = function( debug ){
    /* vars */
    var _b, _charCount, _debug, _div, _divDisplay, _msgWindow, _addThisAccount, _addThisTemplate, _fieldUsername, _fieldPassword, _fieldComment, _brand, _contentId, _contentType;
    var _hidden, _twitterTemplate, _processing;

    /* constructor */
    function simpleTwitterPopup(){
        _debug = debug;
        _charCount = 140;
        _addThisTemplate = _addThisAccount = _div = _divDisplay = _msgWindow = _fieldUsername = _fieldPassword = _fieldComment = _brand = _contentId = _contentType = null;
        _hidden = true;
        _b = true;
        _twitterTemplate = "";
        _processing = false;
    }

    /* getters/setters */
    this.setBrand = function( s ){ _brand = s; };
    this.setContentId = function( s ){ _contentId = s; };
    this.setContentType = function( s ){ _contentType = s; };
    this.setDiv = function( o ){
        _div = $("#"+ o.id );
        if( !_div ){
            _div = null;
        } else {
            _hidden = _div.css( 'display' ,'none');
            _div.click(function(){
                if( !_processing ) showHideForm( null );
            });
        }
    };
    this.setDivDisplay = function( o ){
        _divDisplay = $( o.id );
        if( !_divDisplay ){
            _divDisplay = null;
        } else {
            _divDisplay.click(function(){
                /* do nothing */
            });
        }
    };
    this.setMessageWindow = function( o ){ _msgWindow = o; };
    this.setFieldUsername = function( o ){ _fieldUsername = o; };
    this.setFieldPassword = function( o ){ _fieldPassword = o; };
    this.setFieldComment = function( o ){ _fieldComment = o; };
    this.setAddThisAccount = function( s ){ _addThisAccount = s; };
    this.setAddThisTemplate = function( s ){ _addThisTemplate = s; };
    this.setTwitterTemplate = function( s ){ _twitterTemplate = s; };
    this.setCharCount = function( s ){ _charCount = s; };

    /* private */
    function validateData(){
        var noErrors = true;
        var msg = "";

        if( _brand ){
            if( _brand == "" ){
                noErrors = false;
                msg += "<li>Brand is empty.</li>\n";
            }
        } else {
            noErrors = false;
            msg += "<li>Brand was not recieved.</li>\n";
        }

        if( _contentId ){
            if( _contentId == "" ){
                noErrors = false;
                msg += "<li>Content Id is empty.</li>\n";
            }
        } else {
            noErrors = false;
            msg += "<li>Content Id was not recieved.</li>\n";
        }

        if( _contentType ){
            if( _contentType == "" ){
                noErrors = false;
                msg += "Content Type is empty.\n";
            }
        } else {
            noErrors = false;
            msg += "<li>Content Type was not recieved.</li>\n";
        }

        if( _fieldUsername ){
            if( _fieldUsername.value == '' ){
                noErrors = false;
                msg += "<li>Username is empty.</li>\n";
            }
        } else {
            noErrors = true;
            msg += "<li>username field was not recieved.</li>\n";
        }

        if( _fieldPassword ){
            if( _fieldPassword.value == '' ){
                noErrors = false;
                msg += "<li>Password is empty.</li>\n";
            }
        } else {
            noErrors = false;
            msg += "<li>Password field was not recieved.</li>\n";
        }

        if( _fieldComment ){
            /*if( _fieldComment.value == '' ){noErrors = false;msg += "<li>Comment is empty.</li>\n";}*/
        } else {
            noErrors = false;
            msg += "<li>Comment field was not recieved.</li>\n";
        }

        displayMessage( msg );

        return noErrors;
    }

    function getNextHighestZindex(obj){
       var highestIndex = 0;
       var currentIndex = 0;
       var elArray = Array();
       if(obj){ elArray = obj.getElementsByTagName('*'); }else{ elArray = document.getElementsByTagName('*'); }
       for(var i=0; i < elArray.length; i++){
          if (elArray[i].currentStyle){
             currentIndex = parseFloat(elArray[i].currentStyle['zIndex']);
          } else if(window.getComputedStyle){
             currentIndex = parseFloat(document.defaultView.getComputedStyle(elArray[i],null).getPropertyValue('z-index'));
          }
          if(!isNaN(currentIndex) && currentIndex > highestIndex){ highestIndex = currentIndex; }
       }
       return(highestIndex+1);
    }

    function showHideForm( e, b ){
        /* if b == true || b == null */
        if( b == null ){
            b = true;
        }
        if( b ){
            if( _hidden ){
               $('body:first').append(_div);
               _div.css({
                   width: window.getWidth(),
                   height: window.getHeight(),
                   top: 0,
                   left: 0,
                   margin:0,
                   padding: 0,
                   border: 0,
                   position: 'fixed',
                   display: 'block',
                   'z-index': getNextHighestZindex( $('body:first') )
                });

               _divDisplay.css({
                   margin: ( window.height()/4 ) + 'px auto',
                   'z-index': getNextHighestZindex( $('body:first') )
                });

                _hidden = false;
            } else {
                _div.css( 'display', 'none' );
                _hidden = true;
            }
        } else {
            _b = true;
        }
    }

    function getAddThisURL( o ){
        var m = o || {},
            a = "http://api.addthis.com/oexchange/0.8/forward/",
            b = m['service'] || "twitter",
            c = "/offer?",
            d = "url=" + encodeURI( o['url'] || self.location.protocol+'//'+self.location.host +self.location.pathname ),
            e = m['template'] || "",
            f = m["additional"] || "";
        return a+b+c+d+e+f;
    }

    function displayMessage( s ){
        if( $("#mdp_widget_twitter_popup_response").length > 0 ){
            $("#mdp_widget_twitter_popup_response").html('<ul>' + s + '</ul>');
        } else {
            if( _debug ) alert( 'displayMessage: ' + s );
        }
    }

    function displayErrorMessage( s ){
        if( _msgWindow ){
            _msgWindow.innerHTML = '<ul>' + s + '</ul>';
        } else {
            if( _debug ) alert( 'displayErrorMessage: ' + s );
        }
    }

    /* public */
    /*
        •	RemoteShareBarService. sendTwitterStatus(brand, contentId, contentType, twitterUser, twitterPwd, comment)
            o	This should be called if the user is sharing via twitter and they opt in to share comments
            o	Parameter descriptions are as follows:
                ?	Brand – The current site brand
                ?	contentId – The ID for the content the user is sharing
                ?	contentType – The content type the user is sharing (“story” or “slideshow”)
                ?	twitterUser – The users twitter login
                ?	twitterPwd – The users twitter password
                ?	comment – The twitter comment value

     */

    this.init = function( brand, contentId, contenType, popupDiv, displayDiv, msgWindow, usernameField, passwordField, commentField, addThisInfo, twitterTemplate, textCount ){

        _brand = brand;
        _contentId = contentId;
        _contentType = contenType;
        _charCount = textCount['count'];
        _div = $("#"+ popupDiv.id );
        _divDisplay = $("#"+ displayDiv.id );

        _div.click(function(){
            if( !_processing ) showHideForm( null, _b );
        });
        _divDisplay.click(function(){
            _b = false;
        });
        _hidden = _div.css('display','none');

        if(_div.length == 0) _div = null;

        _msgWindow = msgWindow;
        _fieldUsername = usernameField;
        _fieldPassword = passwordField;
        _fieldComment = commentField;
        _fieldComment.addEvent('keydown',function(){
            if( _fieldComment.value.length >= _charCount ){
                _fieldComment.value = _fieldComment.value.substr(0,_charCount);
                _msgWindow.innerHTML = "You have reached your maximum limit of characters allowed.";
            }
            if( textCount['id'] ) $(textCount['id']).innerHTML = ( _charCount - _fieldComment.value.length ) + " characters left.";
        });

        _addThisAccount = addThisInfo['addThisAccount'] || _addThisAccount;

        _addThisTemplate = addThisInfo['addThisTemplate'] || _addThisTemplate;
        
        twitterTemplate = twitterTemplate == null ? _twitterTemplate : twitterTemplate;
        _twitterTemplate = twitterTemplate;

    };

    this.sendToTwitter = function( useDWR ){
        sendToTwitter( useDWR );    
    };

    function sendToTwitter ( useDWR ){
        displayErrorMessage( '' );
        if( useDWR ) {
            if( validateData() ) {
                _processing = true;
                displayMessage( "<h2>Your tweet is being submitted...</h2>" );
                RemoteShareBarService.countShare(_brand, 'Twitter', _contentId, _contentType, function(){});
                RemoteShareBarService.sendTwitterStatus( _brand, _contentId, _contentType, _fieldUsername.value, _fieldPassword.value, _fieldComment.value + _twitterTemplate, onTwitterStatusCallback );
            }
        } else {
            if( _addThisAccount != "" && _addThisAccount != null ){
                _processing = true;
                var f = function(){
                    displayMessage( "<h2>Thanks for tweeting.</h2>" );
                    setTimeout(function(){showHideForm(null);}, 2500);
                    $(window).unbind('focus',f);
                    _processing = false;
                };
                window.focus(f);
                displayMessage( "<h2>Sending you to twitter to tweet...</h2>" );
                RemoteShareBarService.countShare(_brand, 'Twitter', _contentId, _contentType, function(){});
                var nw = window.open ( getAddThisURL( { service : 'twitter', additional:'&pub=' + _addThisAccount + '&template=' + encodeURI( _fieldComment.value ) + _twitterTemplate } ) , "addthisWindow" );
            } else {
                if( _debug ) displayMessage( 'no AddThis Account Specified' );
                displayErrorMessage( 'There was an error.' );
            }
        }
    }

    this.showHideDiv = function( e ){
        if( _div ) showHideForm( e );
    };


    this.hideDiv = function(  ){
        if( _div ) showHideForm( null );
    };

    /* events */
    function onTwitterStatusCallback( remoteResult ){

        _processing = false;
        if (remoteResult.statusCode == 0) {
            /* Success! */
            displayMessage( "<h2>Your tweet is live.</h2><strong><a href='http://www.twitter.com/"+_fieldUsername.value+"' target='_blank'>Check it out...</a></strong>" );
            setTimeout(function(){showHideForm(null);}, 2500);
        } else {
            $("#mdp_widget_twitter_popup_response").css('display','none');
            $("#mdp_widget_twitter_popup_forms").css('display','block');
            displayErrorMessage( 'There was an error. You may want to:<br/>Check your login information.<br/><a onclick="mdp.simpleTwitterPopup.sendToTwitter ( false );">Click here to tweet from twitter.</a>' );
        }
    }
     
    simpleTwitterPopup();
};
/*
  getAddThisURL( { service : 'twitter', additional:'&pub=pledgeforhealthApp&template=' + encodeURI( _field_pledge.value ) + '%20{{url}}%20%23pledgeforhealth' } );      
*/
