/*
* Copyright (c) 2009-2010 ATMAIL. All rights reserved
* See http://atmail.com/license.php for license agreement
*/

var graphData = [];
var themeColorsHash = {
    blue: {lineColor: "#1b92d5", fillColor: "rgba(232, 244, 251, 0.8)", gradientColorTop: "#e8f4fb", gradientColorBottom: "#1b92d5"},
    green: {lineColor: "#00a0a3", fillColor: "rgba(229, 245, 246, 0.8)", gradientColorTop: "#e5f5f6", gradientColorBottom: "#00a0a3"},
    orange: {lineColor: "#eb7a4b", fillColor: "rgba(253, 241, 237, 0.8)", gradientColorTop: "#fdf1ed", gradientColorBottom: "#eb7a4b"},
    purple: {lineColor: "#7a62ac", fillColor: "rgba(241, 239, 247, 0.8)", gradientColorTop: "#f1eff7", gradientColorBottom: "#7a62ac"},
    red: {lineColor: "#df4a57", fillColor: "rgba(252, 237, 238, 0.8)", gradientColorTop: "#fcedee", gradientColorBottom: "#df4a57"}
}

var themeColorsCurrent = null

function themeColorsCurrentUpdate()
{

    var color = /blue|green|purple|red|orange/.exec( $("body").attr('class') )
    if( color != null && color.length > 0 && color[0].length > 0 )
        themeColorsCurrent = themeColorsHash[color[0]]
    else
        themeColorsCurrent = themeColorsHash.blue

}

// Fetch a large graph
function onDataReceived(series, graphId) {
	
	if($("#Dashboard").css('display') == 'none' && $("#Users").css('display') == 'none') {
		//return;
	}
	
	var options = {
	    lines: { show: true },
	    points: { show: true },
		grid: { color: "#999", clickable: true },
		yaxis: {tickDecimals: 1, min: 0, autoscaleMargin: 0.1},
		xaxis  : { mode: "time", localTimezone: true }
	};
    //set the line color to currently selected ui color

    if( themeColorsCurrent == null )
        themeColorsCurrentUpdate();

    series.color = themeColorsCurrent.lineColor;
    series.lines.fillColor = themeColorsCurrent.fillColor;

    var data = [];
    data.push(series);

    if(graphId.length && graphId.is(':visible'))
    {
        $.plot(graphId, data, options);
    }
 }

function zoomGraph(largeGraphId, smallGraphId) {
	
	if($("#Dashboard").css('display') == 'none') {
		//return;
	}
	
	var options = {
	    lines: { show: true },
	    points: { show: true },
	    //xaxis: { tickSize: 1 },
		grid: { color: "#999" },
		yaxis: {tickDecimals: 1, min: 0, autoscaleMargin: 0.1},
		xaxis  : { mode : "time", localTimezone: true }
	};

	var data = [];
	data.push(smallGraphId.data('graphData'));

    if(largeGraphId.length && largeGraphId.is(':visible'))
    {
        $.plot(largeGraphId, data, options);
    }
	// Update the header in the UI
	var graphText = smallGraphId.parent().find('.statName').text();

	// Change the H1 at the parent roof with the new name
	largeGraphId.parent().find('H1').html(graphText);
	
 }

// Fetch a small graph
function onDataReceivedSmall2(series, graphId, type, context) {

	if(!type)
		type = '';

	if(!context)
		context = '';
		
	if($("#Dashboard").css('display') == 'none' && $("#Users").css('display') == 'none') {
		//return;
	}
	
	if(type == 1)
		var optionsSmall = {
		    lines: { show: true },
			grid: { color: "#999" },
			yaxis: {tickDecimals: 1, min: 0, autoscaleMargin: 0.1, ticks: []},
			xaxis : { mode : "time", localTimezone: true },
			label: ""
		};
	else
		var optionsSmall = {
		    lines: { show: true },
			grid: { color: "#999" },
			yaxis: {tickDecimals: 1, min: 0, autoscaleMargin: 0.1},
			xaxis : { mode : "time", localTimezone: true },
			label: ""
		};
	
	var total = 0;

	// Not IE compat
	for (var item in series.data) {
		var row = series.data[item];
		total = Number(row[1]) + Number(total);
	}

    if( themeColorsCurrent == null )
        themeColorsCurrentUpdate();

    //set the line color to currently selected ui color
    series.color = themeColorsCurrent.lineColor;
    series.lines.fillColor = themeColorsCurrent.fillColor;

    $("#" + graphId).data('graphData', series);
	var dataRecord = $("#" + graphId).data('graphData');
		
	var graphData = [];
    graphData.push(series);

	$("#" + graphId).parent().find('.statTotal').text(total);

	// Format the number, e,g 24,340
	$("#" + graphId).parent().find('.statTotal').format({format:"#,###", locale:"us"});

    // and plot all we got
    if($("#" + graphId).length)
    {
        $.plot($("#" + graphId, context), graphData, optionsSmall);
    }
}

// Fetch a small graph
$.fn.onDataReceivedSmall = function(series, type) {

	if(!type)
		type = '';
		
	if($("#Dashboard").css('display') == 'none' && $("#Users").css('display') == 'none') {
		//return;
	}
	
	if(type == 1)
		var optionsSmall = {
		    lines: { show: true },
			grid: { color: "#999" },
			yaxis: {tickDecimals: 1, min: 0, autoscaleMargin: 0.1, ticks: []},
			xaxis : { mode : "time", localTimezone: true },
			label: ""
		};
	else
		var optionsSmall = {
		    lines: { show: true },
			grid: { color: "#999" },
			yaxis: {tickDecimals: 1, min: 0, autoscaleMargin: 0.1},
			xaxis : { mode : "time", localTimezone: true },
			label: ""
		};
	
	var total = 0;

	// Not IE compat
	for (var item in series.data) {
		var row = series.data[item];
		total = Number(row[1]) + Number(total);
	}

    if( themeColorsCurrent == null )
        themeColorsCurrentUpdate();

    //set the line color to currently selected ui color
    series.color = themeColorsCurrent.lineColor;
    series.lines.fillColor = themeColorsCurrent.fillColor;

    // This is used when the graph is clicked, and the large version appears above
	$(this).data('graphData', series);
	var dataRecord = $(this).data('graphData');
		
	var graphData = [];
    graphData.push(series);

	$(this).parent().find('.statTotal').text(total);

	// Format the number, e,g 24,340
	$(this).parent().find('.statTotal').format({format:"#,###", locale:"us"});

    // and plot all we got
    if($(this).length)
    {
      $.plot( $(this), graphData, optionsSmall);
    }

}

function generateLargeGraph(selector, url, view, log) {
    selector = selector.find('.statGraph');
    selector.html("<div id='loading' style='top: 50%; position: relative;left: 50%;'><h1 class='loading-text'><img class='loadingimg' src='" + siteBaseUrl + "images/25.gif' width='28' height='28'/><span class='loading'>" + jsTranslate('Loading...') + "</span></h1></div>");
return;
    var request = url + view + "/log/" + log
    if(typeof(selector) != 'undefined' && selector.attr('logtype') != '')
    {
        request = request + "/type/" + selector.attr('logtype')
    }
	// Launch request for large graph
	$.ajax({
	    url: request,
	    method: 'GET',
	    dataType: 'json',
		success: function(graphdata, type) {
            onDataReceived(graphdata, selector );
		}
	});

}

function generateSmallGraph(selector, url, view, log) {
    selectorBig = selector.find('.statGraph');
    if($.browser.safari)
    {
        // some weird canvas bug
        var currentwidth = $("BODY").width() - 300;
        if(currentwidth > 650) currentwidth = 650;
        selectorBig.width(currentwidth);
		selectorBig.height(100);
    }

    selector = selector.find('.statGraphSmall');
    selector.html("<div id='loading' style='top: 50%; position: relative;left: 50%;'><h1 class='loading-text'><img class='loadingimg' src='" + siteBaseUrl + "images/25.gif' width='28' height='28'/><span class='loading'>" + jsTranslate('Loading...') + "</span></h1></div>");

	// Launch an ajax query for each graph
	selector.each(function(n){
		var data = [];
        var myrecord = this;
        var logtype = $(this).attr('logtype');
        var request = url + view + "/log/" + log + "/type/" + logtype

		$.ajax({
	        url: request,
	        method: 'GET',
	        dataType: 'json',
	        success: function(graphdata, type) {
               $(myrecord).onDataReceivedSmall(graphdata);
                // Open the 'all login' graph, zoomed at the top.
                if (logtype == '')
                {
                    zoomGraph(selectorBig, $(myrecord));
                }
			}
	    });

        // Now, bind when the user clicks!
        $(this).bind('click', function() {
            selectorBig.html("<div id='loading' style='top: 50%; position: relative;left: 50%;'><h1 class='loading-text'><img class='loadingimg' src='" + siteBaseUrl + "images/25.gif' width='28' height='28'/><span class='loading'>" + jsTranslate('Loading...') + "</span></h1></div>");
            zoomGraph(selectorBig, $(this));
        });

	});

}

$.fn.viewLogs = function(url, log, view) {
	
	// Don't enable log-search if Subadmin does not have the rights
	if( $("#dashboard_logs").size() == 0 ) {
		$(this).css('text-decoration', 'none');
		$(this).css('pointer', '');
		return;
		
	}
	
	$(this).attr('title', 'View expanded logs');
	
	$(this).bind('click', function() {
					
		id = $(this).parent().find('.statGraphSmall').attr('LogType');
				
		if(!id)
			id = 0;
			
		var navbar = $('#secondary', '#Dashboard').tabs();
		var tabLen = navbar.tabs( "length" ) - 1;
		
		// Check if we are the Subadmin user
		if( $("#account_profile").size() != 0 ) {
			tabLen = navbar.tabs( "length" ) - 1;
		}
		
		navbar.tabs( "url" , tabLen , url + '/dashboard/log/log/' + log + '/type/' + id + '/view/' + view);
		navbar.tabs('select', tabLen);

	});
	
}

$.fn.timePeriodLogs = function(url, id, log, view, timePeriod) {
	
	if(!id)
		id = 0;
		
	if(!timePeriod)
		timePeriod = 0;
		
	var navbar = $('#secondary', '#Dashboard').tabs();
	var tabLen = navbar.tabs( "length" ) - 1;
	
	// Check if we are the Subadmin user
	if( $("#account_profile").size() != 0 ) {
		tabLen = navbar.tabs( "length" ) - 1;
	}
	
	navbar.tabs( "url" , tabLen , url + '/dashboard/log/log/' + log + '/type/' + id + '/view/' + view + '/timePeriod/' + timePeriod);
	navbar.tabs('select', tabLen);

	
}
