// Bandwidth data
function getBandwidthData(navDate,username) 
{
    var tbl = document.getElementById('xmltable');
    clearRows(tbl);

    clearNav();

    $("#datetxt2").html("Loading..");


    var thisDateObj = navDate.split(" ")[0].split("-");
    var thisDateYear = thisDateObj[0];
    var thisDateMonth = parseFloat(thisDateObj[1]);

    var theUrl = "modules/servers/axxessReseller/calls/bwusage.php?username="+username+"&year="+thisDateYear+"&month="+thisDateMonth;
    loaddataDoc(theUrl);
}





function loaddataDoc(url) 
{

  $.ajax({
    type: "GET",
    url: url,
	cache: false,
	dataType: "json",
   	//dataType: "text",
	//converters: {"text xml": jQuery.parseXML},
	timeout: 30000,
	error: function(request,error,errorThrown) {


		alert('Data cannot be loaded.');
		/*
		if (error == "timeout") {
			//alert('timeout');
		} else {
			//alert(errorThrown);
		}
		*/
	},
	
	success: function(data)
        {
            var thisDate = data.Date;
            var dateArr = thisDate.split(" ");

            var thisDateArr = thisDate.split(" ");
            var thisMonth = thisDateArr[0];
            var thisYear = thisDateArr[1];

            var chkVal = 0;
            
            $.each(data.Usage,function(index,item){
                    chkVal += parseFloat(item.up) + parseFloat(item.down);
            });

            var navArr = data.navigation.split(",");
			
            // change main date
            $("#datetxt2").html(thisMonth+" "+thisYear);

            navControl(thisDate,navArr);

            // no data
            if (chkVal == 0) 
            {
                $("#nodatatxt2").html("No current data available for "+thisDate);
                $("#nodata2").show();
                $("#axtablediv").hide();
                return;
            }
		
            $("#nodata2").hide();
            $("#axtablediv").show();

            var tbl = document.getElementById('xmltable');
            //addRows(dateArr, inArr, outArr, navArr, tbl);
            addRows(data, dateArr, navArr, tbl);

    }

  });

}


function changeMonth2(dir)
{

    var thisDate = $("#datetxt2").html();
    var thisDateArr = thisDate.split(" ");
    var thisMonth = thisDateArr[0];
    var thisYear = thisDateArr[1];

    if (dir == "prev") 
    {
        prevObj = new Date (thisYear, findMonth(thisMonth), 1); 
        prevObj.setMonth(prevObj.getMonth()-1);
        var newDate = prevObj.getFullYear() +"-"+parseInt(prevObj.getMonth()+1) +"-01";
    } 
    else if (dir == "next")
    {
        nextObj = new Date (thisYear, findMonth(thisMonth), 1);
        nextObj.setMonth(nextObj.getMonth()+1);
        var newDate = nextObj.getFullYear() +"-"+parseInt(nextObj.getMonth()+1) +"-01";
    }

    storedDate = newDate;
    getBandwidthData(newDate,$("#usernamedata").val());
}


function navControl(thisDate,navArr)
{
    // show date
    $("#datetxt2").html(thisDate);

    // create/show navigation
    var navButtons = "";
    // previous
    if (navArr[0] == 1)
    {
        // active
        navButtons += '<a href="javascript://" onclick="changeMonth2(\'prev\');" class="graphnav" style="background:url(\'modules/servers/axxessReseller/assets/img/graphnav_bg.png\') 0 0;" title="Previous Month"></a>';
    } 
    else if (navArr[0] == 0) 
    {
        //disabled
        navButtons += '<div class="graphnav" style="background:url(\'modules/servers/axxessReseller/assets/img/graphnav_bg.png\') -21px 0;"></div>';
    }
    // next
    if (navArr[1] == 1)
    {
        // active
        navButtons += '<a href="javascript://" onclick="changeMonth2(\'next\');" class="graphnav" style="background:url(\'modules/servers/axxessReseller/assets/img/graphnav_bg.png\') -42px 0;" title="Next Month"></a>';
    } 
    else if (navArr[1] == 0)
    { 
        //disabled
        navButtons += '<div class="graphnav" style="background:url(\'modules/servers/axxessReseller/assets/img/graphnav_bg.png\') -63px 0;"></div>';
    }
    
    $("#graphnavdiv2").html(navButtons);
		
}

function clearNav() 
{
    // clear navigation
    $("#graphnavdiv2").html("");
}



function clearRows(tbl) 
{
    // CLEAR DAYS
    $(".dummyrow").hide();
    for (var i = 0; i<32; i++)
    {
	var lastRow = tbl.rows.length;
	if (lastRow != 0 && lastRow != 1 && lastRow != 2) 
        {
            tbl.deleteRow(lastRow-1);
	}
    }
}



function checkZero(totalDays,inArr,outArr) 
{
    var mainTotal = 0;
    for (var i = 0; i<totalDays; i++)
    {
	var thisTotal = parseFloat(inArr[i])+parseFloat(outArr[i]);
	mainTotal += thisTotal;	
    }

    if (mainTotal == 0) 
    {
        return true;
    }

    return false;
}



function addRows(data, dateArr, navArr, tbl)
{
    var mainTotal = 0;
	
    $.each(data.Usage,function(index,item)
    {
        if (!checkDate(index, dateArr))
        {
            return;
	}
		
        var lastRow = tbl.rows.length;
        var row = tbl.insertRow(lastRow);

        if (isEven(lastRow)) {
                row.className = "even";
        } else {
                row.className = "odd";
        }

        row.onmouseover = function() {rowHilight(this, 'over');};
        row.onmouseout = function() {rowHilight(this, 'out');};

        var dateCell = row.insertCell(0);
        dateCell.id = "dcell"+index;

        var outCell = row.insertCell(1);
        outCell.id = "ocell"+index;
        outCell.align = "right";

        var inCell = row.insertCell(2);
        inCell.id = "icell"+index;
        inCell.align = "right";

        var totalCell = row.insertCell(3);
        totalCell.id = "tcell"+index;
        totalCell.align = "right";

        var cumulativeCell = row.insertCell(4);
        cumulativeCell.id = "ccell"+index;
        cumulativeCell.align = "right";
        cumulativeCell.style.width = "100%";

        $("#dcell"+index).html(index+" "+dateArr[0]+" "+dateArr[1]);
       
        // uploaded
        if (item.up != undefined) {
                $("#ocell"+index).html(parseFloat(item.up).toFixed(2));
        }

        // downloaded
        if (item.down != undefined) {
                $("#icell"+index).html(parseFloat(item.down).toFixed(2));
        }

        if (item.up != undefined && item.down != undefined) {
                //var thisTotal = parseFloat(item.up)+parseFloat(item.down);
                var thisTotal = item.total;
                mainTotal += thisTotal;

                //total
                $("#tcell"+index).html(thisTotal.toFixed(2));
                //cumulative
                $("#ccell"+index).html(mainTotal.toFixed(2));
        }
		
    });
	
}



function checkDate(index,dateArr) {
		// function to match index to date
		var thisDateObj = getNow().split(" ")[0].split("-");
		var thisDateYear = thisDateObj[0];
		var thisDateMonth = parseFloat(thisDateObj[1])-1;
		var thisDateDay = parseFloat(thisDateObj[2]);
	
		if (dateArr[1] == thisDateYear && findMonth(dateArr[0]) == thisDateMonth) {
			if (index > thisDateDay) {
				return false;
			}
		}
	return true;
}






function isEven(x) { return (x%2)?false:true; }

function daysInMonth(month,year) {
var dd = new Date(year, month, 0);
return dd.getDate();
} 


function findMonth(month) {
	monthArr = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
	for (var i = 0; i<monthArr.length; i++) {
		if (month == monthArr[i]) {
			return i;
		}
	}
}


function trueYear(theDate) {
	x = theDate.getYear();
	var y = x % 100;
	y += (y < 38) ? 2000 : 1900;
	return y;
}



function rowHilight(obj, bcol) {
	if (obj.className.indexOf('odd') != -1) {

		if (bcol == 'over') {
			obj.className = 'oddblue';
		} else if (bcol == 'out') {
			obj.className = 'odd';
		}

	} else if (obj.className.indexOf('even') != -1) {

		if (bcol == 'over') {
			obj.className = 'evenblue';
		} else if (bcol == 'out') {
			obj.className = 'even';
		}

	}
}
