/*
    name : backtypeSocialSearch
    file : jquery.backtypeSocialSearch.js
    author : gregory tomlinson
    copyright: (c) 2010 bit.ly
    Dual licensed under the MIT and GPL licenses.
    ///////////////////////////
    ///////////////////////////
    dependencies : jQuery 1.4.2
    ///////////////////////////
    ///////////////////////////
    
    Listens for socialSearch event to collect hashes and urls user for inserting tweets and querying backtype respectively;

*/

(function($) {
    
    $.fn.backtypeSocialSearch = function( options ) {
        // extend the defaults settings
        var el = this, o = $.extend(true, defaults, options),
            tweetBoxes, linkData = {}, linkStartExp = new RegExp('<a[^>]+>', 'gi'), linkEndExp = new RegExp('<\/a>', 'gi');
        
        // listen for an event to search backtype - it will provide long urls?
        el.bind('socialSearch', function(e,data) {
           
           if(o.debug) console.log(e,data);
           
           linkData = data;
           
           tweetBoxes = el.find('.backtypeSocialSearchBox')
           
           query_urls = []
           for(var i=0; i<data.longUrls.length; i++) {
               query_urls.push( encodeURIComponent( data.longUrls[i] ) );
               
               //encodeURIComponent
           }
           
           o.params.urls = query_urls.join(',');
           //
           /* 1. loop over
              2. encodeURIComponent
              3. put back into an array
              4. join array on ','
              5. make string and call backtype
              6.
           */
            
            setTimeout(function(){
                connector(o.url, o.params, success, error );
            }, 3000)
        });
        
        return this;
        
        function error(e) {
            console.log('ERROR: unable to get backtype results, API not returning 200', e);
            return;
        }
        
        function success(jo) {
            if(o.debug)  console.log(jo);
            
            var type, pos, links, long_url, i, html, default_text, totalTweets=0;
            
            tweetBoxes.each(function(idx, el) {
                // here
                $el = $(el).css('display','none');
                type = $el.attr('type');
                
                pos = jQuery.inArray(type, linkData.user)
                long_url = linkData.longUrls[pos];
                
                links = jo.data.links;
                
                for(i=0; links && i<links.length; i++) {
                    if( long_url === links[i].url ) {
                        
                        if( links[i].shares) {
                            $el.html( renderTweetItem( links[i] ) );
                            totalTweets+= links[i].shares.length;
                        }
                        break;
                    }
                
                }
                
                if( $el.html() === "" ) {
                    // if(o.debug) console.log('found nothing');
                    // html = "";
                    //     html += '<a class="shareWithFriends" href="#">Share this with friends >></a>';
                    // default_text = $(html).data('url', {'url':long_url} );
                    // $el.html( default_text )
                    $el.fadeIn('normal')
                }
                
                
            
            });
            
            tweetBoxes.find('.moreTweetsShow').toggle(function(e) {
                e.preventDefault();
                var $this = $(this);
                
                $this.parents('.tweetContainer').find('.moreTweetsContainer').slideDown('normal');
                $this.html('close')
            
            },function(e) {
                
                var $this = $(this), tweet_num = $this.attr('tweet_type');
                $this.parents('.tweetContainer').find('.moreTweetsContainer').slideUp('normal');
                $this.html('plus ' + tweet_num + ' more')
            
            });
            
            tweetBoxes.find('.shareWithFriends').click(function(e){
                e.preventDefault();
                var $this = $(this);
                if(o.debug)  console.log('share with friends')
                el.trigger('openSharePanel', $this.data('url') );
            });
            
            if(totalTweets > 0 ) {
                $('<div style="display:none;" class="backtypeAttribution"><a href="http://backtype.com/">Tweets via Backtype</a></div>').appendTo(el).fadeIn('normal');
            }
            tweetBoxes.slideDown();
        }
        function cleanTweetText(txt) {
            return txt.replace(linkStartExp, "").replace(linkEndExp, "")
        }
        function renderTweetItem( link ) {
            var html = "", user, txt;
            
            if(link.shares && link.shares.length > 0) {
                
                user = $.escapeHTML(link.shares[0].tweet_from_user);
                txt = $.escapeHTML(cleanTweetText(link.shares[0].tweet_text));
                //TODO
                // trim tweets to length
                ///len = user.length +
                
                html += '<div class="tweetContainer">'
                    html += '<div class="twitterIconColumn">'
                        html += '<img src="/s/graphics/twitter_tiny.png" alt="" border="0" width="16" height="16" />';
                    html += '</div>'
                    
                    html += '<div class="twitterMainTextColumn">'
                        html += '<div class="socialSearchTweetFirstPosition">'
                            html += '<a href="http://twitter.com/' + user + '/status/' + link.shares[0].tweet_id + '" class="tweetPermalink">#</a>' 
                            html += '<a href="http://twitter.com/'+ user +'">'
                                html += user;
                            html += '</a>: ';
                            html += txt;
                        html += '</div>'
                        
                        if(  link.shares.length > 1 ) {
                            html += '<div class="moreTweetsShowBox">'
                                html += "<a tweet_type='"+(link.shares.length-1)+"' class='moreTweetsShow' href='#'>plus " + (link.shares.length-1) + " more</a>";
                            html += '</div>'
                        }
                    
                    html += '</div>'
                        if(  link.shares.length > 1 ) {
                            //html +=
                                html += '<div class="moreTweetsContainer" style="display:none;">'
                            for(var i=1; i<link.shares.length; i++) {
                                html += '<div class="moreTweetsContainerItem">'
                                    html += '<a href="http://twitter.com/' + $.escapeHTML(link.shares[i].tweet_from_user) + '/status/' + link.shares[i].tweet_id + '" class="tweetPermalink">#</a>' 
                                    html += '<a href="http://twitter.com/'+ $.escapeHTML(link.shares[i].tweet_from_user) +'">'
                                        html += $.escapeHTML(link.shares[i].tweet_from_user);
                                    html += '</a>: ';
                                    html += $.escapeHTML(cleanTweetText(link.shares[i].tweet_text));
                                html += '</div>'
                            }
                            //http://cdixon.org/2010/04/10/twitter-and-3rd-party-developers/
                            //http://www.backtype.com/search?q=
                            var backtype_url = "http://www.backtype.com/search?q=" + encodeURIComponent(link.url)
                            html += '<div><a target="_blank" href="'+backtype_url+'">More Tweets via Backtype</a></div>'
                            html += '</div>'
                        }
                    
                    html += '<div class="hr"><hr /></div>'
                    html += '</div>';
                html += '</div>'
                return html;
            
            }
        
        }
        
        function _render_additional_tweets() {
        
        }
        
        
        function trimTweet() {
            // todo, implement string that will fit, watch for html
        }
    
    }
    
    
    var defaults = {
        //url : 'http://api.backtype.com/shares/by_friends.json',
        url : '/data/partners/backtype/socialsearch/',
        params : {
            urls : ''
        },
        debug:false
    }, $bod;
    
    function connector(url, params, callback, error) {
        params._xsrf = $.cookie.get("_xsrf");
        var str = $.param( params );
        $.ajax({
            dataType: 'json',
            data : str,
            //jsonp: 'callback',
            'url' : url,
            success: callback,
            'error' : error
        });
    }
})(jQuery);
