function amChartInited(chart_id){
    if(chart_id == "traffic_clicks_flash") {
        var time_frame_els = $("#traffic_clicks_buttons li.active a");
        var time_frame_el = $(time_frame_els[0]);
        var time_frame = time_frame_el.attr('rel');
        if (time_frame == "LIVE") {
            $('#traffic_clicks_live').click();            
        }
    }
    if (chart_id == "country_clicks_flash") {
        InfoPage.country_chart_ready = true;
        InfoPage.populateCountryChartIfReady();
    }
}

Bitly.searchTwitterCallbackOriginal = Bitly.searchTwitterCallback;
Bitly.searchTwitterCallback = function(data) {
    Bitly.searchTwitterCallbackOriginal(data);
    $("#dd_twitter_count").html("<img src=\"/static/images/twit_sm.png\" width=\"10\" height=\"13\"> Tweets <span class=\"count\">" + BitlyHelper.commifyNumber(Bitly.summize_total) + "</span>; ");
    $("#view_all_conversations").css('display', '');
    $("#no_conversations").css('display', 'none');
    try {
        var el = $("#_b_summize").children()[0].firstChild;
        el.innerHTML = "<a href='http://search.twitter.com/' title='Powered by Twitter Search'><img class='powered_favi' src='http://twitter.com/favicon.ico' /></a> " + el.innerHTML;
    } catch(ee){}
};

Bitly.searchFacebookShareCallbackOriginal = Bitly.searchFacebookShareCallback;
Bitly.searchFacebookShareCallback = function(data) {
    Bitly.searchFacebookShareCallbackOriginal(data);
    if (!Bitly.fbshareinfo){return;}
    var html = "";
    if (Bitly.fbshareinfo["share_count"] || Bitly.fbshareinfo["like_count"] || Bitly.fbshareinfo["comment_count"]){
        html += '<img src="/static/images/fb_sm.png" width="13" height="13">';
        comma = false;
        if (Bitly.fbshareinfo["share_count"]){
            html += " Shares <span class=\"count\">" + BitlyHelper.commifyNumber(Bitly.fbshareinfo["share_count"])+"</span>";
            comma=true;
        }
        if (Bitly.fbshareinfo["like_count"]){
            if (comma){html+=',';}else{comma=true;}
            html += " Likes <span class=\"count\">" + BitlyHelper.commifyNumber(Bitly.fbshareinfo["like_count"])+"</span>";
        }
        if (Bitly.fbshareinfo["comment_count"]){
            if (comma){html+=',';}else{comma=true;}
            html += " Comments <span class=\"count\">" + BitlyHelper.commifyNumber(Bitly.fbshareinfo["comment_count"])+"</span>";
        }
        html +=";";
        $("#dd_facebook_count").html(html);
        $("#view_all_conversations").css('display', '');
        $("#no_conversations").css('display', 'none');
    }
};

Bitly.searchFriendFeedCallbackOriginal = Bitly.searchFriendFeedCallback;
Bitly.searchFriendFeedCallback = function(data) {
    Bitly.searchFriendFeedCallbackOriginal(data);
    $("#dd_friend_feed_count").html("<img src=\"/static/images/ff_sm.png\" width=\"14\" height=\"14\"> Shares <span class=\"count\">" + BitlyHelper.commifyNumber(Bitly.friend_feed_total) + "</span>; ");
    $("#view_all_conversations").css('display', '');
    $("#no_conversations").css('display', 'none');
    try {
        var el = $("#_b_friendfeed").children()[1].firstChild.firstChild;
        el.innerHTML = "<a href='http://friendfeed.com/' title='Powered by Friend Feed'><img class='powered_favi' src='http://friendfeed.com/favicon.ico' /></a> " + el.innerHTML;
    } catch(ee){}
};

Bitly.backtypeCallbackOriginal = Bitly.backtypeCallback;
Bitly.backtypeCallback = function(data) {
    Bitly.backtypeCallbackOriginal(data);
    $("#dd_backtype_count").html("<img src=\"/static/images/bt_sm.png\" width=\"14\" height=\"14\"> Comments on Page <span class=\"count\">" + BitlyHelper.commifyNumber(Bitly.backtype_total) + "</span>; ");
    $("#view_all_conversations").css('display', '');
    $("#no_conversations").css('display', 'none');
    try {
        var el = $("#_b_backtype").children()[0].firstChild;
        el.innerHTML = "<a href='http://backtype.com/' title='Powered by BackType'><img class='powered_favi' src='http://backtype.com/favicon.ico' /></a>  " + el.innerHTML;
    } catch(ee){}
};

/*
amcharts:
http://www.amcharts.com/column/controlling-chart-with-javascript/
*/

var InfoPage = {
	init:function(bitly_hash, aggregate_hash, shortend_by_user, keyword_hash, real_user_hash) {
	    InfoPage.HOUR = 60 * 60;
		InfoPage.DAY = 60 * 60 * 24;
		InfoPage.WEEK = InfoPage.DAY * 7;
		InfoPage.MONTH = InfoPage.DAY * 30;
	    InfoPage.x_axis_frequency = 5;
	    InfoPage.did_flip_back = false;
	    
	    InfoPage.MAX_REFERRERS = 50;
	    
	    
	    InfoPage.bitly_hash = bitly_hash;
	    InfoPage.aggregate_hash = aggregate_hash;
        InfoPage.shortend_by_user = shortend_by_user;
	    InfoPage.keyword_hash = keyword_hash;
	    InfoPage.real_user_hash = real_user_hash;
	    
        InfoPage.aggregate_user_flag = (bitly_hash == aggregate_hash) ? 'GLOBAL_HASH' : 'USER_HASH';
        if (!InfoPage.keyword_hash) {
            InfoPage.metrics_hash = bitly_hash;
        } else {
            if (real_user_hash) {
                InfoPage.metrics_hash = real_user_hash;
                InfoPage.aggregate_user_flag = 'USER_HASH';
            } else {
                InfoPage.metrics_hash = aggregate_hash;
                InfoPage.aggregate_user_flag = 'GLOBAL_HASH';
            }
            
        }

        InfoPage.country_chart_ready = false;

        // create events
        
        $('.change_date_range').click(function() { return InfoPage.selectTrafficDateRangeTab(this); });

        $('#traffic_pause').click(function() {InfoPage.pauseButtonClick(this); return false;});

        // create objects
        InfoPage.initGraphs();

	},
	
	initGraphs:function() {
        var traffic_so = new SWFObject("/static/js/lib/amcolumn/amcolumn.swf", "traffic_clicks_flash", "100%", "220", "8", "#FFFFFF");
        traffic_so.addVariable('path', "/static/js/lib/");
        traffic_so.addVariable('chart_data','1;0');
        traffic_so.addVariable("chart_id", "traffic_clicks_flash");
        var settings = "<settings>";
            settings += "<column><hover_brightness>50</hover_brightness><width>90</width><grow_time>0</grow_time><balloon_text><![CDATA[<div align='center' style='text-align:center; color:#D9AA40 !important;'>{value} clicks<br />{series}</div>]]></balloon_text></column>";
            settings += "<colors>999999,999999,999999,999999,999999,999999,999999,999999,999999,999999,999999,999999,999999</colors>"; 
            settings += "<grid><category><color>ffffff</color></category><value><color>999999</color></value></grid>";
            settings += "<text_color>999999</text_color><data_type>csv</data_type><legend><enabled>0</enabled></legend>";
            settings += "<thousands_separator>,</thousands_separator>";
            settings += "<plot_area><border_alpha>0</border_alpha><border_color>999999</border_color><margins><left>60</left><right>40</right><top>30</top><bottom>50</bottom></margins></plot_area>";
            settings += "<axes><category><color>999999</color><width>1</width></category><value><color>999999</color><width>1</width></value></axes>";
            settings += "<values>";
                settings += "<value><min>0</min><integers_only>1</integers_only></value>";
                settings += "<category><frequency>5</frequency></category>";
                settings += "</values>";
            settings += "</settings>";
        
        traffic_so.addVariable("chart_settings",  settings);
        traffic_so.addVariable("preloader_color", "#999999");
        traffic_so.addParam("wmode", "transparent");
        traffic_so.write("traffic_clicks_graph");
        
        
        
        var country_so = new SWFObject("/static/js/lib/amcolumn/amcolumn.swf", "country_clicks_flash", "850", "400", "8", "#FFFFFF");
        // var country_so = new SWFObject("/static/js/lib/ampie/ampie.swf", "country_clicks_flash", "300", "300", "8", "#FFFFFF");
        country_so.addVariable('path', "/static/js/lib/");
        country_so.addVariable('chart_data','1;0');
        country_so.addVariable("chart_id", "country_clicks_flash");
        // country_so.addVariable('chart_data','a;1\nb;2\nc;3\nd;4\ne;6;\ne;6;\ne;6;');
        settings = "<settings>";
            settings += "<column><data_labels>{value} ({series})</data_labels><width>40</width><grow_time>0</grow_time></column>";
            settings += "<colors>#999999,#669933,#378799,#366699,#363499,#673399,#983289,#993044,#A35028,#A46E28,#A48827,#666666</colors>";
            settings += "<grid><category><color>ffffff</color></category><value><color>999999</color></value></grid>"; 
            settings += "<text_color>999999</text_color>"; 
            settings += "<thousands_separator>,</thousands_separator>";
            settings += "<data_type>csv</data_type>"; 
            settings += "<legend><enabled>0</enabled></legend>"; 
            settings += "<plot_area><border_alpha>0</border_alpha><border_color>999999</border_color><margins><left>0</left><right>90</right><top>30</top><bottom>30</bottom></margins></plot_area>"; 
            settings += "<axes><category><color>999999</color><width>1</width></category><value><color>999999</color><width>1</width></value></axes>"; 
            settings += "<values><value><min>0</min><integers_only>1</integers_only></value><category><enabled>false</enabled></category></values>";
            settings += "<type>bar</type>";
        settings +="</settings>";
        
        country_so.addVariable("chart_settings", settings);
		country_so.addVariable("preloader_color", "#999999");
		country_so.addParam("wmode", "transparent");
		country_so.write("country_clicks_graph");
        // InfoPage.zeroBuckets();
		
	},
	
	pauseButtonClick:function(_this) {
        var el = $(_this);
        if (el.text() != 'Resume') {
            InfoPage.stopLiveTrafficData();
            el.text('Resume');
        } else {
            $('#traffic_clicks_live').click();
            el.text('Pause');
        }
	    el.blur();
	},
	
	getLiveTrafficData:function(do_start){
	    if (typeof(do_start) == 'undefined') {
	        var do_start = false;
	    }
	    var url = '/info/get_realtime_data?data_set=pathseries&path=' + InfoPage.metrics_hash;
	    if (InfoPage.aggregate_user_flag == 'USER_HASH') {
	        url += "&bitly_user=" + InfoPage.shortend_by_user;
	    }
	    url += "&t=" + (new Date()).getTime();
	    $("#clicks_loading").css('display', '');
	    
	    $.ajax({
           type: "GET",
           "url": url,
           dataType: 'json',
            success: function(data){
                InfoPage.getLiveTrafficDataCB(data, do_start);
            },
            error: function(XMLHttpRequest, thrownErrorString) {
                XMLHttpRequest.error = "An error occurred. Metrics data not available for that time period.";
                InfoPage.getLiveTrafficDataCB(XMLHttpRequest, do_start);
            }
        });
        
        // get referrers and countries
        
        return false;
    },
    
    getLiveTrafficDataCB: function(data, do_start) {
        $("#clicks_loading").css('display', 'none');
        
        if (!InfoPage.did_flip_back && data.length == 0) {
            if (typeof(ONLY_REALTIME) != 'undefined' && ONLY_REALTIME === true) {
                InfoPage.displayTrafficError('No realtime clicks for this link yet.');
                InfoPage.pauseButtonClick(document.getElementById('traffic_pause'));
            } else {
                InfoPage.did_flip_back = true;
                $('#traffic_clicks_all').click();
            }
            return;
        } else if (data.error != null) {
            InfoPage.displayTrafficError(data.error);
            InfoPage.pauseButtonClick(document.getElementById('traffic_pause'));
            return;
        } else {
            var dataset = [];
            $.each(data, function (index, item) {
                dataset.push({date: item.date, prettyDate: InfoPage.prettyTime(item.date), clicks: item.clicks});
            });
            
            
            if (dataset.length == 61) {
                dataset.shift(); // remove the 61st element (at the beginning of the hour)
            }
            
            InfoPage.x_axis_frequency = 5;
            InfoPage.loadTrafficDateRange(dataset);
            
            if (typeof('do_start') != 'undefined' && do_start) {
                InfoPage.startLiveTrafficData();
            }                    
        }
        
        InfoPage.intervals_done++;
        
        if (InfoPage.intervals_done * InfoPage.live_interval < InfoPage.live_max) {
            InfoPage.live_timeout = setTimeout(InfoPage.getLiveTrafficData, InfoPage.live_interval * 1000);
        } else {
            $("#traffic_dialog").css("display", ''); // $("#traffic_dialog").dialog('open');
            InfoPage.pauseButtonClick(document.getElementById('traffic_pause'));
        }
    },
    
    startLiveTrafficData:function() {
        
        InfoPage.live_interval = 5; // live interval in seconds
        InfoPage.live_max = 5 * 60; // the number of seconds to run live
        InfoPage.intervals_done = 0;
        
	},
	
	onCloseDialog:function() {
        InfoPage.startLiveTrafficData();
        $("#traffic_dialog").css("display", 'none');
        InfoPage.pauseButtonClick(document.getElementById('traffic_pause'));
	},
	
	stopLiveTrafficData:function() {
		// stop live timer AND dialog timer
        clearTimeout(InfoPage.live_timeout);
	},
	
	resetTrafficTabs:function() {
		$('#traffic_clicks_buttons li').removeClass('active');
	},
    
    displayTrafficError:function(error_string) {
        var error_div = $("#traffic_error");
        error_div.css('display', '');
        error_div.text(error_string);
    },
    
	loadTrafficDateRange:function(targetRange) {
        var dataset = "";
        var min_ts = null;
        var min_date = null;
        var click_total = 0;
        var data_points_count = 0;
        $.each(targetRange, function(index, item) {
            if (min_ts == null) {
                // first item is the earliest. Set min_date and min_ts
                min_ts = InfoPage.timestampFromDateString(item.date);
                min_date = item.date;
            }
            item.prettyDate = item.prettyDate.replace(/(AM|PM)\s/, "$1<br />");
            dataset += item.prettyDate + ';' + item.clicks  + '\n';
            click_total += parseInt(item.clicks, 10);
            data_points_count++;
        });
        
        
        if (click_total == 0) {
            InfoPage.displayTrafficError('There is no traffic data for this time period.');
            return;
            
        } else {
            $("#traffic_error").css('display', 'none');
        }
        
        var now = Math.round(new Date().valueOf() / 1000);
        
        if (min_ts == null) {
            // an error fetching data occurred
            $("#total_clicks_time").text('');
        } else {
            
            if (min_ts >= (now - 2 * InfoPage.HOUR) ) {
                var fdate = InfoPage.prettyTime(min_date);
            } else if (min_ts >= (now - 1.5 * InfoPage.DAY) ) { // if stats began less than 1.5 days ago, be specific about the time
                var fdate = InfoPage.prettyDateWithTime(min_date);
            } else {
                var fdate = InfoPage.prettyDate(min_date);
            }
            
            if (document.getElementById('traffic_clicks_flash').setParam) {
                document.getElementById('traffic_clicks_flash').setParam("values.category.frequency", InfoPage.x_axis_frequency);
                $("#total_clicks_time").text(" Since " + fdate + " EST");
                $("#total_clicks").text(BitlyHelper.commifyNumber(click_total));
            }
            
        }
        
        
        if (document.getElementById('traffic_clicks_flash').setData) {
            document.getElementById('traffic_clicks_flash').setData(dataset);
        }
        
	},
	
	getMetricsData:function(params, callback) {
	    params['t'] = (new Date()).getTime();
	    $.ajax({
           type: "GET",
           url: '/info/get_metrics_data',
           dataType: 'json',
           data: params,
            success: function(data){
                callback(data);
            },
            error: function(XMLHttpRequest, thrownErrorString) {
                XMLHttpRequest.error = "An error occurred. Metrics data not available for that time period.";
                callback(XMLHttpRequest);
            }
        });
	},
	
	getMetricsCountry:function(time_frame) {
	    $("#locations_loading").css('display', '');
	    return InfoPage.getMetricsData({'hash': InfoPage.metrics_hash, 
	        'scope': InfoPage.aggregate_user_flag, 
	        'time_frame': time_frame, 
	        'data_type': 'country'}, InfoPage.getCountryCB);	    
	},
	
	getMetricsClicks:function(time_frame) {
	    $("#clicks_loading").css('display', '');
	    return InfoPage.getMetricsData({'hash': InfoPage.metrics_hash, 
	        'scope': InfoPage.aggregate_user_flag, 
	        'time_frame': time_frame, 
	        'data_type': 'clicks',
	        'time_series': '1'}, InfoPage.getClicksCB);
	},
	
	getMetricsReferrers: function(time_frame) {
	    $("#refs_loading").css('display', '');
	    return InfoPage.getMetricsData({'hash': InfoPage.metrics_hash, 
	        'scope': InfoPage.aggregate_user_flag, 
	        'time_frame': time_frame, 
	        'data_type': 'referrers'}, InfoPage.getReferrersCB);
	},
	
	timestampFromDateString:function(date_string) {
	    var y,m,d,h,mm;
	    var mt = date_string.match(/(\d{4})-(\d{2})-(\d{2})\s(\d{2}):(\d{2})/);
	    if (mt) {
            h = mt[4];
            mm = mt[5];
	    } else {
	        mt = date_string.match(/(\d{4})-(\d{2})-(\d{2})/);
	        h = 0;
	        mm = 0;
	    }
        y = mt[1];
        m = parseInt(mt[2], 10) - 1;
        d = mt[3];
        
        var dt = new Date();
        dt.setFullYear(y);
        dt.setMonth(m);
        dt.setDate(d);
        dt.setHours(h);
        dt.setMinutes(mm);
        
        return dt.getTime() / 1000;
	},
	
	prettyDateWithTime:function(date_string) {
	    return InfoPage.prettyTime(date_string)  + " " + InfoPage.prettyDate(date_string);
    },
	
	prettyTime:function(date_string) {
	    // given a date string, return date formatted like
	    // 1:05 AM Mar 20, 2009
	    var m = date_string.match(/(\d{4})-(\d{2})-(\d{2})\s(\d{2}):(\d{2})/);
        var A = "AM";
        
        m[4] = parseInt(m[4], 10);
        if (m[4] == 12) {
            A = "PM";
        } else if (m[4] > 12) {
            if (m[4] == 24) {
                A = "AM";
            }
	        m[4] = m[4] - 12;
            A = "PM";
	    }
        return m[4].toString() + ":" + m[5] + " " + A;
	},
	
	prettyDate:function(date_string) {
	    // given a date string, return a date formatted like
	    // Mar 20, 2005
	    var m = date_string.match(/(\d{4})-(\d{2})-(\d{2})/);
	    var mmm = InfoPage.monthAbbrev(m[2]);
        return mmm + " " + m[3] + ", " + m[1];
	},
	
	monthAbbrev:function(month_number) {
        var months = {1: "Jan", 2: "Feb", 3: "Mar", 4: "Apr", 5: "May", 6: "Jun", 7: "Jul", 8: "Aug", 9: "Sep", 10: "Oct", 11: "Nov", 12: "Dec"};
        return months[parseInt(month_number, 10)];
	},
	
	getClicksCB:function(data) {
        $("#clicks_loading").css('display', 'none');
        var now = Math.round(new Date().valueOf() / 1000);
        var click_total = 0;
        if (data.error != null) {
            InfoPage.displayTrafficError(data.error);
        } else {
            
            var format_func = InfoPage.prettyDate;
            
            if (data.time_frame == 'PAST_DAY') {
                InfoPage.x_axis_frequency = 5;
                format_func = InfoPage.prettyDateWithTime;
            } else if (data.time_frame == 'PAST_WEEK') {
                InfoPage.x_axis_frequency = 1;
            } else if (data.time_frame == 'PAST_MONTH') {
                InfoPage.x_axis_frequency = 7;
            } else if (data.time_frame == 'ALL') {
                if (data.results.length > 10) {
                    InfoPage.x_axis_frequency = Math.round(data.results.length / 7);
                } else {
                    InfoPage.x_axis_frequency = 1;
                }
            }
            
            var dataset = [];
            $.each(data.results, function(index, item) {
                item.prettyDate = format_func(item.date);
                dataset.push(item);
                click_total += parseInt(item.clicks, 10);
            });
            InfoPage.loadTrafficDateRange(dataset);
            
            $("#total_clicks").text(BitlyHelper.commifyNumber(click_total));
            
	    }
	},
	
	getReferrersCB:function(data) {
	    $("#refs_loading").css('display', 'none');
        var preproceessed_data = InfoPage.preProcessReferrerData(data['results']);
        InfoPage.drawReferrersTable(InfoPage.aggregate_user_flag, preproceessed_data);
	},
	
	preProcessCountryData:function(results) {
	    var multi_array = [];
        for (var key in results) {
            multi_array.push([key, results[key]]);
        }
        if (multi_array.length == 0) {
            return false;
        }
        
        multi_array = multi_array.sort(function(a,b){return a[1] - b[1]; });
        multi_array.reverse();
        return multi_array;
	},
	
	getCountryCB:function(data) {
	    $("#locations_loading").css('display', 'none');
	    if (data.results == null) { data.results = {}; }; // catch error
        if (typeof(do_populate_chart) == 'undefined') { var do_populate_chart = true; };
	    
        var multi_array = InfoPage.preProcessCountryData(data.results);
        var csv_array = [];
        var max_bars = 15;
        var others_sum = 0;
        for (var i=0; i < multi_array.length; i++) {
            if (i < max_bars) {
                csv_array.push(getCountryName(multi_array[i][0]) + ";" + multi_array[i][1]);
            } else {
                others_sum += multi_array[i][1];
            }
        };
        
        if (others_sum > 0) {
            csv_array.push("Other Countries" + ";" + others_sum);
        }
        
        csv_array.reverse();
        
        var error_div = $("#country_error");
        if (csv_array.length == 0) {
            error_div.css('display', '');
            error_div.text('There is no location data for this time period.');
            return;
        } else {
            error_div.css('display', 'none');
        }
        
        if (data.time_frame == 'ALL') {
            InfoPage.updateCountrySummary(data.results);
        }
        
        var csv = csv_array.join("\n");
        InfoPage.country_csv = csv;
        if (InfoPage.country_chart_ready) {
            InfoPage.populateCountryChartIfReady();
        }
        
	},
	
	updateCountrySummary:function(results) {
	    // UPDATE countries summary
        var multi_array = InfoPage.preProcessCountryData(results);
        var countries_dd_array = [];
        for (var i=0; i < multi_array.length && i < 3; i++) {
            var display = getCountryName(multi_array[i][0]); //(ISO_COUNTRIES[multi_array[i][0]] == null) ? 'Other' : ISO_COUNTRIES[multi_array[i][0]]; 
            countries_dd_array.push(display + " " + BitlyHelper.commifyNumber(multi_array[i][1]));
        };
        if (countries_dd_array.length > 0) {
            $("#countries_dd").html(countries_dd_array.join("; ") + "&nbsp;&nbsp;<a href='#country_clicks_data'>View All</a>");
        } else {
            $("#countries_dd").html("<a href='#country_clicks_data'>View All</a>");
        }
	},
	
	populateCountryChartIfReady:function() {
	    if (InfoPage.country_csv && InfoPage.country_chart_ready) {
	        var el = document.getElementById('country_clicks_flash');
	        if (el.setData) {
	            el.setData(InfoPage.country_csv);
	        }
	    }
	},
	
	getCountriesRealtime:function(clicks_type, bitly_hash) {
	    var url = '/info/get_realtime_data?data_set=summary&keys=cc&types=s&path=' + InfoPage.metrics_hash;
	    if (InfoPage.aggregate_user_flag == 'USER_HASH') {
	        url += "&bitly_user=" + InfoPage.shortend_by_user;
	    }
        $("#locations_loading").css('display', '');
        
        $.ajax({
           type: "GET",
           "url": url,
           dataType: 'json',
            success: function(data){
                InfoPage.getCountriesRealtimeCB(data);
            },
            error: function(XMLHttpRequest, thrownErrorString) {
                XMLHttpRequest.error = "An error occurred. Metrics data not available for that time period.";
                InfoPage.getCountriesRealtimeCB(XMLHttpRequest);
            }
        });
	},
	
	getCountriesRealtimeCB: function(data) {
        $("#locations_loading").css('display', 'none');
        if (data.cc && data.cc.data) {
            InfoPage.getCountryCB({"results": data.cc.data});
        } else {
            var error_div = $("#country_error");
            error_div.css('display', '');
            error_div.text('There is no location data for this time period.');
        }
	},
	
	getReferrersRealtime:function(clicks_type, bitly_hash) {
	    $("#refs_loading").css('display', '');
	    var url = '/info/get_realtime_data?data_set=summary&keys=r&types=s&path=' + InfoPage.metrics_hash;
	    if (InfoPage.aggregate_user_flag == 'USER_HASH') {
	        url += "&bitly_user=" + InfoPage.shortend_by_user;
	    }
	    
	    $.ajax({
           type: "GET",
           "url": url,
           dataType: 'json',
            success: function(data){
                InfoPage.getReferrersRealtimeCB(clicks_type, data);
            },
            error: function(XMLHttpRequest, thrownErrorString) {
                XMLHttpRequest.error = "An error occurred. Metrics data not available for that time period.";
                InfoPage.getReferrersRealtimeCB(clicks_type, XMLHttpRequest);
            }
        });
	},
	
	getReferrersRealtimeCB: function(clicks_type, data) {
	    $("#refs_loading").css('display', 'none');
        if (data['r'] == null || data['r']['data'] == null) {
            InfoPage.drawReferrersError();
        } else {
            var preproceessed_data = InfoPage.preProcessRealtimeReferrerData(data['r']['data']);
            InfoPage.drawReferrersTable(clicks_type, preproceessed_data);                
        }
	},
	
	preProcessRealtimeReferrerData:function(flat_ref_data) {
        var domains = {};
        for (var encoded_url in flat_ref_data) {
            var path = '/';
            var url = unescape(encoded_url);
            var clicks = flat_ref_data[encoded_url];
            var m = url.match(/^https{0,1}\:\/\/([^\/]+)(.*)$/i);
            
            if (m && m[1]) {
                var domain = m[1];
                if (m[2]) {
                    path = m[2];
                }
            } else {
                var domain = url; // if we got here, we couldn't match domain and we need to improve regexp.
            }
            if (InfoPage.domainIsDirect(domain)) {
                domain = 'direct';
            }
            
            if (domains[domain] == null) {
                domains[domain] = {'total': 0, 'paths': {}};
            }
            domains[domain]['total'] += clicks;
            domains[domain]['paths'][path] = clicks;
        }
        
        return InfoPage.sortReferrersData(domains);
	},
	
	preProcessReferrerData:function(numerius_ref_data) {
        var domains = {};
        for (var domain in numerius_ref_data) {
            var paths = numerius_ref_data[domain];
            if (InfoPage.domainIsDirect(domain)) {
                domain = 'direct';
            }
            for (var path in paths) {
                if (domains[domain] == null) {
                    domains[domain] = {'total': 0, 'paths': {}};
                }
                var clicks = parseInt(paths[path], 10);
                domains[domain]['total'] += clicks;
                domains[domain]['paths'][path] = clicks;
            }
        }
        
        return InfoPage.sortReferrersData(domains);
	},
	
	sortReferrersData:function(preprocessed_data) {
        var arr = [];
        var direct = null;
        for (var domain in preprocessed_data) {
            var hsh = preprocessed_data[domain];
            hsh['domain'] = domain;
            //             if (InfoPage.domainIsDirect(domain)) {
            //                 direct = hsh;
            // } else {
	            arr.push(hsh);
            // }
        }
	    var sorted = arr.sort(function(a,b){
	        return b['total'] - a['total']; 
	    });
        // if (direct) {
        //             sorted.push(direct);
        // }
	    return sorted;
	},
	
	domainIsDirect:function(domain) {
        return (domain == '' || domain.match(/direct/i) || domain == 'None');
	},
	
	drawReferrersError: function() {
	    $("#traffic_sources").html("<p>There is no referrer data for this time period.</p>");
	},
	
	drawReferrersTable:function(clicks_type, preproceessed_data) {
	    var data = preproceessed_data;
	    
	    
        if (preproceessed_data.length == 0) {
            InfoPage.drawReferrersError();
            return false;
        }
        var _id = (clicks_type == 'GLOBAL_HASH') ? 'global' : 'local';
        
        // if (clicks_type == 'ALL_HASHES') {
        //     var col_title = "";
        // } else {
        //     var col_title = "On <br />bit.ly Link";
        // }
        
        var html = '';
        
        html += '<table cellspacing="0" cellpadding="0" class="statistics" id="'+_id+'_statistics">';
         html += '<thead>';
             html += '<tr>';
                 html += '<th class="url">Referring Site</th>';
                 html += '<th class="clicks_l">Click(s)</th>';
             html += '</tr>';
         html += '</thead>';
            
            
            var row_type = "row_odd";
            var total = 0;
            
            for (var j=0; j < InfoPage.MAX_REFERRERS && j < preproceessed_data.length; j++) {
                var domain = preproceessed_data[j]['domain'];
                var domain_total = preproceessed_data[j]['total'];
                var paths = preproceessed_data[j]['paths'];
                var is_partner = null;
                
                if (InfoPage.domainIsDirect(domain)) {
                    var direct = true;
                    var domain_display = "Email Clients, IM, AIR Apps, and Direct";
                    var fav_image = '';
                } else if (is_partner = InfoPage.isPartnerDomain(domain)) {
                    var direct = false;
                    var domain_display = "Registered Applications";
                    var fav_image = '';
                } else {
                    // encode the domain for entry onto the page
                    var domain_display = $('<div/>').text(domain).html() ;
                    var direct = false;
                    var fav_image = '<img width="16" height="16" src="http://'+domain+'/favicon.ico" r="'+domain+'" class="fav" />';
                }
                
                
                row_id = '10' +j;
                total += domain_total;
                
                html += '<tr class="row '+row_type+'" id="r_r_'+row_id+'">';
                    html += '<td class="url">';
                        html += domain_display+' <img src="/static/images/open_button.png" class="r_open" id="r_a_1011"/>'; // fav_image+
                    html += '</td>';
                    html += '<td class="clicks_l"><span id="r_cl_'+row_id+'">'+BitlyHelper.commifyNumber(domain_total)+'</span></td>';
                html += '</tr>';
                html += '<tbody class="'+row_type+' sub" id="r_s_'+row_id+'" style="display: none">';
                
                if (direct) {
                    html += '<tr>';
                        html += '<td class="url">Direct Traffic includes people clicking a bit.ly link from: <br />- Desktop email clients like Microsoft Outlook or Apple Mail<br />- AIR applications like Twhirl<br />- Mobile apps like Twitterific or BlackBerry Mail<br />- Chat apps like AIM<br />- SMS/MMS messages<br />It also includes people who typed a bit.ly link directly into their browser</td>';
                        html += '<td class="clicks_l">&nbsp;</td>';
                    html += '</tr>';
                } else if (is_partner) {
                    for (var path in paths) {
                        var partner_info = null;
                        if (partner_info = InfoPage.getPartnerInfo(path)) {
                            var partner_display = '<a target="_blank" href="'+ partner_info.url + '">' + partner_info.display_name + '</a>';
                        } else {
                            var partner_display = 'Other Partner';
                        }
                        
                        html += '<tr>';
                            html += '<td class="url">'+partner_display+'</td>';
                            html += '<td class="clicks_l">'+BitlyHelper.commifyNumber(paths[path])+'</td>';
                        html += '</tr>';
                    }
                } else {
                    for (var path in paths) {
                        html += '<tr>';
                            html += '<td class="url">'+$('<div/>').text(path).html()+'</td>';
                            html += '<td class="clicks_l">'+BitlyHelper.commifyNumber(paths[path])+'</td>';
                        html += '</tr>';
                    }
                }
                html += '</tbody>   ';
                
                
                row_type = (row_type == 'row_odd') ? 'row_even' : 'row_odd';
            }
            
        
         // html += '<tfoot>';
         //     html += '<tr>';
         //         html += '<td class="url">&nbsp;</td>';
         //         html += '<td class="clicks_l">'+BitlyHelper.commifyNumber(total)+'</td>';
         //     html += '</tr>';
         // html += '</tfoot>';
         
        html += '</table>';
        
        $("#traffic_sources").html(html);
        $('#global_statistics .row').click(InfoPage.stattoggle);
        $('#local_statistics .row').click(InfoPage.stattoggle);
	},
	
	stattoggle: function(e) {
      var id = this.id.substring(4);
      
      $('#r_s_' + id).toggle();
      var t = $("#traffic_pause").text();
      if (t && t != "Resume") {
          InfoPage.pauseButtonClick(document.getElementById('traffic_pause'));
      }
    },
	
    isPartnerDomain: function(domain) {
        return (domain == 'partners.bit.ly');
    },
    
    getPartnerInfo: function(partner_string) {
        if (InfoPage.PARTNERS) {
            var m = partner_string.toString().match(/^\/?(\w+)\/?$/i);
            if (m && m[1]) {
                return InfoPage.PARTNERS[m[1]];
            }
        } else {
            return null;
        }
    },

    openTabSection: function(el) {
        el = $(el);
        $("#traffic_tabs li").removeClass("active");
        $(el.parent()[0]).addClass("active");
        el.blur();

        $(".tab_section").css('display', 'none');
        var show_section = $("#" + el.attr('id') + "_section");
        show_section.css('display', '');
        
        this.loadSelectedChartData();

        return false;
    },

    loadSelectedChartData: function() {
        var time_frame_els = $("#traffic_clicks_buttons li.active a");
        var time_frame_el = $(time_frame_els[0]);
        var section_els = $("#traffic_tabs li.active a");
        var section_el = $(section_els[0]);
        
        var time_frame = time_frame_el.attr('rel');
        var section = section_el.attr('id');
        
        InfoPage.stopLiveTrafficData(); 
        var pause_display = (time_frame == 'LIVE') ? '' : 'none';
        $('#traffic_pause').css('display', pause_display);
        if (time_frame == 'LIVE') {
            switch (section) {
                case "clicks_tab":
                    $('#traffic_pause').css('display', '');
                    InfoPage.getLiveTrafficData(true);
                    break;
                case "referrers_tab":
                    InfoPage.getReferrersRealtime(InfoPage.aggregate_user_flag, InfoPage.bitly_hash);
                    break;
                
                case "locations_tab":
                    InfoPage.getCountriesRealtime(InfoPage.aggregate_user_flag, InfoPage.bitly_hash);
                    break;
            }
            
        } else {
            switch (section) {
                case "clicks_tab":
                    InfoPage.getMetricsClicks(time_frame); 
                    break;
                case "referrers_tab":
                    InfoPage.getMetricsReferrers(time_frame); 
                    break;
                
                case "locations_tab":
                    InfoPage.getMetricsCountry(time_frame);
                    break;
            }
        }
    },
    
    selectTrafficDateRangeTab: function(tab_el) {
        tab_el = $(tab_el);
        
        InfoPage.resetTrafficTabs();
        tab_el.blur();
        tab_el.parent().addClass('active');
        
        InfoPage.loadSelectedChartData();
        return false;
    }
    
};
