/*
    name : sidebarClicks
    file : jquery.sidebarClicks.js
    author : gregory tomlinson
    Dual licensed under the MIT and GPL licenses.
    ///////////////////////////
    ///////////////////////////        
    dependencies : jQuery 1.4.2, jquery.cookie.js
    ///////////////////////////
    ///////////////////////////
    
*/

(function($) {
    
    $.fn.sidebarClicks = function( options ) {
        // extend the defaults settings
        var el = this, o = $.extend(true, defaults, options);
        if(el.length <= 0) return this;
        
        $(document.body).bind('shortenComplete', function(e, data ) {
            console.log(data)
            // o.params.hash = data.userHashes;
            // 
            // //setTimeout(function(){
            //     
            // //}, 100)
            
            o.params.hash = [data.hash];
            connector(o.url, o.params, success, error );
            
            var html = "";
            html += renderHeader();
            html += renderClicks( data.hash, data.global_hash );            
            $(html).appendTo( el );
            el.css('display', 'block')

        });
        
        return this;
        
        /********* Render Header *******************/
        
        function renderHeader() {
            var html = "";
            html += '<div class="sidebarClicks_header">'
                html += '<h3>Clicks</h3>'
            html += '</div>'
            
            return html;
        }
        
        function renderClicks( user_hash, global_hash ) {
            var html = "";
            html += '<div class="sidebarClicks_metrics">'
                html +='<ul class="sidebarClicks_metricsList">'
                    html += '<li class="sidebarMetricsCountColumn"><a class="sidebar_metrics_count" type="'+user_hash+'" href="http://'+o.host_name+'/'+user_hash+'+">0</a></li>'
                    html += '<li>On your bit.ly link <br />More info: <a href="http://'+o.host_name+'/'+user_hash+'+">http://'+o.host_name+'/'+user_hash+'+</a></li>'   
                    html += '<div class="hr"><hr /></div>'                 
                html +='</ul>'        
                
                html +='<ul class="sidebarClicks_metricsList">'
                    html += '<li class="sidebarMetricsCountColumn"><a class="sidebar_metrics_count" type="'+global_hash+'" href="http://'+o.host_name+'/'+global_hash+'+">0</a></li>'
                    html += '<li>On All bit.ly links to this page<br />More info: <a href="http://'+o.host_name+'/'+global_hash+'+">http://'+o.host_name+'/'+global_hash+'+</a></li>'    
                    html += '<div class="hr"><hr /></div>'                
                html +='</ul>'                        
                html += '<div class="hr"><hr /></div>'
            html += '</div>'
            
            return html;
        }
        
        
        /********* ASYNC EVENTS *******************/
        
        function success( jo ) {
            if (jo.status_code !== 200) {
                //return error(jo);
                
                return;
            }
            
            console.log(jo)
            // always declare vars up top - son
            var hashes = jo.data.clicks, i=0, li, links = el.find('.sidebar_metrics_count'), $elem;
            
            
            
            
            for(; i<hashes.length; i++) {
                li = hashes[i];
                if(li.error) continue;
                $elem = links.filter("[type $='" + li.global_hash + "']");
                console.log('word')
                if(li.global_clicks > 1000) $elem.addClass('largeNumber')
                $elem.html( $.commifyNumber(li.global_clicks) );
                
                
           
                $elem = links.filter("[type $='" + li.user_hash + "']");
                if(li.user_clicks > 1000) $elem.addClass('largeNumber')                
                $elem.html( $.commifyNumber(li.user_clicks) );                

            }
            
            if(hashes[0].global_hash === hashes[0].user_hash) {
                el.find('.sidebarClicks_metricsList').eq(0).slideUp();
            }
            

            

            //stats_collection.parents('.statsList').fadeIn('normal');
        }
        
        function error(jo) {
            // console.log('error', jo);
            //  
            //  var d = $('<div class="metricsDataErrorMessage errorMessagBox">Uh oh, we aren\'t able to access click data right now, don\'t worry your data is safe.</div>');
            //  
            //  d.prependTo( el );
            
            el.trigger('errorMessage', {
                text : "Oops, we aren't able to access click metrics right now, don't worry your data is safe."
            });            
        }

    }
    
    
    var defaults = {
    
        url : '/data/clicks',
        params : {
            hash : []
        },
        host_name : 'bit.ly',
        multiRowToggle : true
        
    }, $bod;
    

    
    function connector(url, params, callback, error) {
        params._xsrf = $.cookie.get('_xsrf');
        var str = $.param( params );
        $.ajax({
            dataType: 'json',
            type : "POST",
            data : str,
            'url' : url,
            success: callback,
            'error' : error
        });
    }

})(jQuery);
