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

(function($) {
    
    $.fn.totalClicks = function( options ) {
        // extend the defaults settings
        var el = this, o = $.extend(true, defaults, options);
        if(el.length <= 0) return this;
        
        el.bind('hashList', function(e, data ) {
            if (data.userHashes.length === 0) {
                return;
            }
            o.params.hash = data.userHashes;
            
            setTimeout(function(){
                connector(o.url, o.params, success, error );
            }, 100)

        });
        
        return this;
        
        function success( jo ) {
            if (jo.status_code !== 200) {
                return error(jo);
                
                return;
            }
            
            // always declare vars up top - son
            var stats_collection = el.find('.userStats a, .globalStats a'), 
                hashes = jo.data.clicks, i=0, li;
            
            
            for(; i<hashes.length; i++) {
                li = hashes[i];
                if (li.errror) {continue;}
                stats_collection.filter("[type $='"+li.global_hash +"']").html($.commifyNumber( li.global_clicks ) );
                if (li.user_hash != li.global_hash) {
                    stats_collection.filter("[type $='"+li.user_hash +"']").html( $.commifyNumber( li.user_clicks ) );
                }
            }
            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 : []
        },
        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);
