//BigDipper
//Written by Samir

//Variables, we'll need
var url = '/labs/test_ericdb';
var all_metrics = "delta_plays,delta_fans,delta_views,delta_comments";
var current_metric = "delta_fans";
var current_range = "month";
var current_bands = new Array();
var all_bands = new Hash();
var singleArtistNetworkBoxes = new Hash();
var max_bands = 4;
var array_of_checked = new Array('TOTAL');

//Let's grab all the data possible going back to June 6, 2009
var end_date = Math.round(new Date().valueOf()/86400000)-1; //till yesterday
var start_date = Math.floor(new Date(2009,5,6).valueOf()/86400000); //This is June 6, 2009

//newBandString is comma delimited
function newBandList(newBandString)
{
	var bands = newBandString.split(",");
	bands.reverse();
		
	//Check that the band_id is valid
	//The check if it doesn't exist and add it
	for(var i = 0; i< bands.length; i++)
	{
		if(!doesBandExist(bands[i]) && bands[i] !=null && bands[i] !=undefined && bands[i] >0)
		{
			createNewArtist(bands[i]);
			current_bands.unshift(bands[i]);
		}
	}
	
	current_bands = new Array();
			
	//adds the bands to the front of the current_bands array
	for(var j = 0; j< bands.length; j++)
		current_bands.unshift(bands[j]);
	
	
	$.post("/ajax/search_volume/", {ids: newBandString});
	
	
	var highlight = current_bands.length;
	Loaded_Chart('chart_my');
}

function dataIsReady()
{
	if(current_bands.length ==0)
		return false;
	
	for(var i=0; i< current_bands.length; i++)
	{
		if(!all_bands.hasItem(current_bands[i]))
			return false;
	}
	
	return true;
}


function doesBandExist(band_id)
{
	return all_bands.hasItem(band_id);	
}

function createNewArtist(band_id)
{
	$.getJSON(url+"/"+band_id+"/"+all_metrics+"/"+start_date+"/"+end_date, 
		function(data)
		{
			$.each(data.groups, function(index, val){
				//is there enough data?
				var enough = false;
				//Get the artist name
				var name = val.name.replace("'","");
				var verified = val.verified;
				var metrics = val.metrics;
				var all_metrics = new Hash();
				$.each(metrics, function(index, metric){
					
					//Get the services associated with this metric
					var services = metric.services;
					
					//Let's create a 'dictionary' object that will store this data
					// total, service1, service2, etc.
					var metric_data = new Hash();
					
					//This will store the total values summed across the services
					var total = new Hash();
					
					$.each(services, function(index1, service){
						var date = service.start_day;
						var service_data = service.data;
						var final_value = parseInt(service.final_total);
						
						var service_dictionary = new Hash();
			
				
						$.each(service_data, function(index2, value){
							
							service_dictionary.setItem(date, value);
							
						
							if(!total.hasItem(date))
							{
								if(value != "null")
								{
									/*
									if((services.length-1)==index1 && value==0)
									{
										total.setItem(date, "null");
									}
									else
									{
									*/	
									total.setItem(date, parseInt(value));
									
								}
								
								
							}
							else
							{
								var val1 = total.getItem(date);
								var val2 = parseInt(value);
								
								
								if(isNaN(val1) && isNaN(val2))
								{
									
									total.setItem(date, "null");
								}
								else if(isNaN(val1) && !isNaN(val2))
									total.setItem(date, val2);
								else if(!isNaN(val1) && isNaN(val2))
									total.setItem(date, val1);
								else
									total.setItem(date, val1 + val2);
							}
							
							date++;
						});
						
						metric_data.setItem('final_'+service.service, final_value);
						metric_data.setItem(service.service, service_dictionary);
						metric_data.setItem('TOTAL', total);
						
						if(total.length>0)
							enough = true;						
					});
					all_metrics.setItem(metric.metric, metric_data);					
				});
				
				//Now that the data is organized, create the new Artist!				
				var newArtist = new Artist(band_id, name, all_metrics, enough, verified);
				all_bands.setItem(band_id, newArtist);
			});
			
			
		}
	);
}


function getSingleArtistNetworkBoxes()
{
	if(current_bands.length==1)
	{
		var b_id = current_bands[0];
		var met = current_metric.substring(6);
		
		
		if(!$("#netBreakDownCheckBoxes #booya").hasClass("nb"+b_id))
		{
			$.post("/ajax/get_network_toggles/"+b_id+"/"+met, function(netHTML){
				$("#netBreakDownCheckBoxes").html(netHTML);
				$("#netBreakDownCheckBoxes").slideDown(100);
			});
			
			array_of_checked = new Array('TOTAL');
			
		}
		else
		{
			$("#netBreakDownCheckBoxes .nb"+b_id+" .oneResultToggleNetworks").hide();
			$("#toggle_"+met).show();
			$("#netBreakDownCheckBoxes").slideDown(100);
		}
	}
	else
		$("#netBreakDownCheckBoxes").slideUp(100);
}

function prettyArtistName(name)
{
	return name.replace(" ", "+");
}

/*
	This function generates the inPlainText Legend for the graph
	**To Do**
	For only one artist, the Legend should also show which service is currently being displayed
*/

function inPlainText()
{
	if(current_bands.length > 1)
		var ing = "Comparing";
	else
		var ing = "Showing";
	
	switch(current_metric)
	{
		case "delta_plays":
			var newwhat = "<span class='metric'> new plays </span> for ";
			break;
		case "delta_fans":
			var newwhat = "<span class='metric'> new fans </span> for ";
			break;
		case "delta_views":
			var newwhat = "<span class='metric'> new views </span> for ";
			break;
		case "delta_comments":
			var newwhat = "<span class='metric'> new comments </span> for ";
			break;
		default:
			var newwhat = "";
	}
	
	//get Artists!
	var names = new Array();
	var count = 0;
	var colors = new Array('green', 'blue', 'orange', 'red');
	
	var names_title = new Array();
	
	for(var i =0; i< current_bands.length; i++)
	{
		if(all_bands.hasItem(current_bands[i]))
		{
			var data = all_bands.getItem(current_bands[i]);
			
			var artist_name = unescape(data.name);
			var artist_id = data.band_id;
			
			var verified = '';

			if(data.verified)
				verified = '<a href="/verify/directory"><img style="position:relative; bottom:-9px; margin-left:4px;" src="/images/plainTextVerified.png"></a>';
				
			if(current_bands.length > 1)
				names.push('<a onclick="javascript:compareArtists('+artist_id+'); return false;" href="#'+prettyArtistName(artist_name)+'"><span class="' + colors[count % 4] + '">' + artist_name + '</span></a>'+verified);
			else
				names.push('<span class="' + colors[count % 4] + '">' + artist_name + '</span>'+verified);
			count++;
		}
		names_title.push(artist_name);
	}
	
	setTitle(names_title);
	//get time Range!
	var today = new Date(end_date*86400*1000);
	
	switch(current_range)
	{
		case "week":
			var range = " from <span class='range'>" + (new Date(today.valueOf() - 7*86400000)).format('F j') + "</span> to <span class='range'>" + today.format('F j') + ".</span>";
			break;
		case "month":
			var range = " from <span class='range'>" + (new Date(today.valueOf() - 30*86400000)).format('F j') + "</span> to <span class='range'>" + today.format('F j') + ".</span>";
			break;
		case "all_time":
			var range = " for <span class='range'>as far back as we can go.</span>";
			break;
		default:
			var range = "";
	}
	
	return ing + newwhat + arrayToList(names) + range;
}


function arrayToList(array)
{
	
	
	
	if(array.length==0)
		return "";
	else if(array.length==1)
		return array[0] + ' ';
	else if(array.length==2)
		return array[0] + ' and ' + array[1] + ' ';
	else
	{
		var string = '';
	
		for(var i = 0; i < array.length; i++)
		{
			if(i < array.length - 1)
				string += array[i] + ', ';
			else
				string += ' and ' + array[i] + ' ';
		}
	
		return string;
	}
	
	//set Title
	
	
}

function setTitle(array)
{
	if(array.length==1)
		document.title = array[0] + " - Next Big Sound";
	else
	{
		var string = '';
	
		for(var i = 0; i < array.length; i++)
		{
			if(i==0)
				string += array[i] + ' ';
			else
				string += ' vs ' + array[i] + ' ';
		}
		
		document.title = string + " - Next Big Sound";
	}
}

//Know which tiles to show and the break down
//Need to make it work for single artist

function getSingleArtistTile()
{
	for(var i = 0; i< current_bands.length; i++)
		$("#artistTileNum"+i).show();
	
	for(var j = current_bands.length; j < max_bands; j++)
		$("#artistTileNum"+j).hide();
	
	
	$(".artistTile").css("width", "857px");
	
	$("#removeSingleArtist").hide();
	$("#singleArtistTile").show();
	
	//now let's fill in the single artist-ish
	
	switch(current_range)
	{
		case "week":
			$("#singleArtistTile .rangeIs").html(" this Week <a class='explainInfo' href='javascript:showHelp();'>&nbsp;</a>");
			break;
		case "month":
			$("#singleArtistTile .rangeIs").html(" this Month <a class='explainInfo' href='javascript:showHelp();'>&nbsp;</a>");
			break;
		case "all_time":
			$("#singleArtistTile .rangeIs").html(" All Time <a class='explainInfo' href='javascript:showHelp();'>&nbsp;</a>");
			break;
		default:
			$("#singleArtistTile .rangeIs").html(" <a class='explainInfo' href='javascript:showHelp();'>&nbsp;</a>");
	}
	
	
	var fourMetricsWeWant = new Array('delta_fans', 'delta_plays', 'delta_views', 'delta_comments');
	
	for(var q=0; q<fourMetricsWeWant.length; q++)
	{
		var valChangeArr = calculateValueChange(current_bands[0], fourMetricsWeWant[q]);
		
		var newValChild	 = "<div class='valChild'>";
		newValChild		+= "<h3>"+valChangeArr[0]+"</h3>";
		newValChild		+= "<p class='"+valChangeArr[2]+"'>"+valChangeArr[1]+"</p>";
		newValChild		+= "</div>";
		
		$("#valChange"+q).html(newValChild);
		
		
		var newBreakChild = generateSingleArtistNetworkBreakDown(fourMetricsWeWant[q], current_bands[0], valChangeArr[3]);
		
		$("#netBreak"+q).html(newBreakChild);
		$('span.theBar').tipsy({gravity: 's'});
		
	
	}

	
}
function generateSingleArtistNetworkBreakDown(metric, band_id, breakdown)
{
	//This function will generate the network breakdown bar graphs for each artist Tile
	var active_services = getCurrentActiveServices();
	var services = active_services[0]; 
	var services_pretty = active_services[1]; 
	
	var newBreakChild = "";
	
	for(var i=0; i< services.length; i++)
	{
		
		if(breakdown.hasItem('per_'+services[i]))
		{
			var per = breakdown.getItem('per_'+services[i]);
			var val = breakdown.getItem('val_'+services[i]);
			
			if(per > 0)
			{
				
				per = Math.round(per);
				
				var barWidth = (per/100)*getBarWidth(4);
				
				if(barWidth<1)
					barWidth = 1;
				
				var newOrTotal = "new";
				
				if(current_range == "all_time")
					newOrTotal = "total"
					
				var p_name = services_pretty[i];
				if(p_name.length>8)
					p_name = p_name.substring(0,7)+'&hellip;';
					
					
				
				newBreakChild += "<li style='clear:both'>";
				newBreakChild += "<span class='network'>"+p_name+"</span>";
				newBreakChild += "<span class='theBar' title='"+commaCoder(parseInt(val))+" "+newOrTotal+" "+services_pretty[i]+" "+getMetricByNetwork(metric, services[i])+"' style='width:"+barWidth+"px !important;'>&nbsp;</span>";
				newBreakChild += "<span class='value'>"+per+"%</span>";
				newBreakChild += "</li>";

			}
		}
		
	}
	
	return newBreakChild;
	
	
}


function getTiles()
{
	if(current_bands.length == 1)
	{
		var oneData = all_bands.getItem(current_bands[0]);
		getTileHeader(0, oneData.band_id);
		getProfilePages(0, oneData.band_id);
		getSingleArtistTile();
		return;
	}
	
	$("#removeSingleArtist").show();
	$("#singleArtistTile").hide();

	//First figure out how many tiles to show, and assign the right widths to them so they look right.
	switch(current_bands.length)
	{
		case 1:
			var tile_width = "857px";
			break;
		case 2:
			var tile_width = "423px";
			break;
		case 3:
			var tile_width = "279px";
			break;
		case 4:
			var tile_width = "205px";
			break;
		default:
			var tile_width = "205px";
	}
	
	
	//Set all the tiles to the width and then show and hide.
	for(var i = 0; i< current_bands.length; i++)
	{
		$("#artistTileNum"+i).css({"width": tile_width},500);
		$("#artistTileNum"+i).show();
		
	}
		
	for(var j = current_bands.length; j < max_bands; j++)
		$("#artistTileNum"+j).hide();
	

	
	//Now lets fill the tiles.
	
	
	for(var i =0; i< current_bands.length; i++)
	{
		if(all_bands.hasItem(current_bands[i]))
		{
			var data = all_bands.getItem(current_bands[i]);
			getTileHeader(i, data.band_id);
			getProfilePages(i, data.band_id);
			generateValueChange(i, data.band_id);
		}
	}
}

function setTileHeights()
{
	var max_prof_height =0;
	var max_net_height = 0;
	for(var i =0; i< current_bands.length; i++)
	{
		var prof_height = $("#artistTileNum"+i+" .profilesVerified .profilePages").height();			
		var net_height = $("#artistTileNum"+i+" .breakdownModule .netBreakdown").height();			

		if(prof_height > max_prof_height)
			max_prof_height = prof_height;
			
		if(net_height > max_net_height)
			max_net_height = net_height;
		
	}
	$(".artistTile .profilesVerified .profilePages").css('height', max_prof_height);
	$(".artistTile .breakdownModule .netBreakdown").css('height', max_net_height);	

}

function getTileHeader(tileNum, band_id)
{
	//Check if the profile section for this tileNum and is empty or not!
	//If its empty, go fetch the header.
	
	if(!$("#artistTileNum"+tileNum+" .header .headerTile").hasClass(".g"+band_id))
	{
		$("#artistTileNum"+tileNum+" .header .name").html('Loading...');
		$.post("/ajax/get_tile_header/"+band_id, function(header){
			$("#artistTileNum"+tileNum+" .header").html(header);
			
			if(current_bands.length==1)
			{
				$(".artistTile a.close").css('visibility', 'hidden');
			}
			else
			{
				$(".artistTile a.close").css('visibility', 'visible');
			}
		});
		
		
		
	}
	
	if(current_bands.length==1)
	{
		$(".artistTile a.close").css('visibility', 'hidden');
	}
	else
	{
		$(".artistTile a.close").css('visibility', 'visible');
	}
	
	
	
	
}

function getProfilePages(tileNum, band_id, refresh)
{
	if(refresh==undefined)
		refresh=false;
	//Check if the profile section for this tileNum and is empty or not!
	//If its empty, go fetch the profiles.
	if(!$("#artistTileNum"+tileNum+" .profilesVerified .profilePages .profileUrls").hasClass("g"+band_id) || refresh==true)
	{
		$("#artistTileNum"+tileNum+" .profilesVerified").html('');
		$.post("/ajax/get_profile_urls/"+band_id, function(profiles){
			$("#artistTileNum"+tileNum+" .profilesVerified").html(profiles);
			setTileHeights();
		});
	}
	
	$("#artistTileNum"+tileNum+" .footer a").attr('href', '/rss/stats/'+band_id);
	
}


function generateNetworkBreakDown(metric, tileNum, band_id, breakdown)
{
	$("#artistTileNum"+tileNum+" .notEnoughY").hide();
	$("#artistTileNum"+tileNum+" .breakdownModule h4").show();
	$("#artistTileNum"+tileNum+" .breakdownModule .netBreakdown").show();
	
	if(tileNum==0)
		singleArtistNetworkBoxes = breakdown;

	//This function will generate the network breakdown bar graphs for each artist Tile
	
	var active_services = getCurrentActiveServices();
	var services = active_services[0]; 
	var services_pretty = active_services[1]; 
	
	$("#artistTileNum"+tileNum+" .breakdownModule h4").html(metric + " Breakdown");
		
		var newBreakChild = "";
		var googleNums ="";
		var googleNames = "";
		for(var i=0; i< services.length; i++)
		{
			if(breakdown.hasItem('per_'+services[i]))
			{
				newBreakChild += "<li>";
				var per = breakdown.getItem('per_'+services[i]);
				var val = breakdown.getItem('val_'+services[i]);
				if(per > 0)
				{
					
					per = Math.round(per);
					
					var barWidth = (per/100)*getBarWidth(current_bands.length);
					
					if(barWidth<1)
						barWidth = 1;
					
					var newOrTotal = "new";
					
					if(current_range == "all_time")
						newOrTotal = "total"
					
					var p_name = services_pretty[i];
					if(p_name.length>8)
						p_name = p_name.substring(0,7)+'&hellip;';
					
					newBreakChild += "<span class='network'>"+p_name+"</span>";
					newBreakChild += "<span class='theBar' title='"+commaCoder(parseInt(val))+" "+newOrTotal+" "+services_pretty[i]+" "+getMetricByNetwork(metric, services[i])+"' style='width:"+barWidth+"px !important;'>&nbsp;</span>";
					newBreakChild += "<span class='value'>"+per+"%</span>";
				}
				newBreakChild += "<\/li>";
			}
			
		}
		
		$("#artistTileNum"+tileNum+" .breakdownModule .netBreakdown").html(newBreakChild);
		$('span.theBar').tipsy({gravity: 's'});
		
		if(all_bands.hasItem(band_id))
		{
			var bandNotEnough = all_bands.getItem(band_id);
			
			if(!bandNotEnough.enough)
			{
				$("#artistTileNum"+tileNum+" .breakdownModule h4").hide();
				$("#artistTileNum"+tileNum+" .breakdownModule .netBreakdown").hide();
				
				
				var nameDude = all_bands.getItem(band_id).name;
				
				$("#artistTileNum"+tileNum+" .notEnoughY .gE").html(all_bands.getItem(band_id).name);
				$("#artistTileNum"+tileNum+" .notEnoughY").show();
			}
		}
}

function getMetricByNetwork(metric, network)
{
	if(metric=="Fans" || metric=='delta_fans')
	{
		switch(network)
		{
			case "MYSPACE":
				return "Friends";
			case "LASTFM":
				return "Listeners";
			case "ILIKE":
			case "FACEBOOK":
				return "Fans";
			case "TWITTER":
				return "Followers";
			case "TOTAL":
			default:
				return "Fans";
		}
	}
	
	
	if(metric=="Comments" || metric=='delta_comments')
	{
		switch(network)
		{
			case "LASTFM":
				return "Shouts";
			case "ILIKE":
				return "Wall Posts";
			case "MYSPACE":
			default:
				return "Comments";
		}
	}
	
	
	if(metric=='Views' || metric=='delta_views')
		return 'Views';
	
	if(metric=='Plays' || metric=='delta_plays')
		return "Plays";
	
	
	return metric;
}

function googlePieChart(googleNums, googleNames, tileNum)
{
	
	var gWidth = 0;
	var gHeight = 0;
	switch(current_bands.length)
	{
		case 1:
		case 2:
			//gWidth = 150;
			//gHeight = 125;
			//break;
		case 3:
			gWidth = 100;
			gHeight = 115;
			break;
		case 4:
		default:
			gWidth = 60;
			gHeight = 80;
	}
	
	switch(tileNum)
	{
		case 0:
			var gColor = '5BAB33';
			break;
		case 1:
			var gColor = '3972cd';
			break;
		case 2:
			var gColor = 'FF7439';
			break;
		case 3:
			var gColor = 'CC2B41';
			break;
		default:
			var gColor = '000000';
	}
	
	googleNames ="";
	
	/*
	$("#artistTileNum"+tileNum+" .breakdownModule").css({
		'background': "url(http://chart.apis.google.com/chart?cht=p&chd=t:"+googleNums+"&chco="+gColor+"&chs="+gWidth+"x"+gHeight+"&chl="+googleNames+") no-repeat",
		'background-position': 'bottom right'
	});
	*/
	//return "http://chart.apis.google.com/chart?cht=p&chd=t:"+googleNums+"&chco="+gColor+"&chs="+gWidth+"x"+gHeight+"&chl="+googleNames;
}

function getBarWidth(numTiles)
{
	switch(numTiles)
	{
		case 1:
			return 765;
		case 2:
			return 285;
		case 3:
			return 155;
		case 4:
			return 95;
		default:
			return 95;
	}
}

function generateValueChange(tileNum, band_id)
{
	//Check if the profile section for this tileNum and is empty or not!
	//If its empty, go fetch the profiles.
	
	var valChangeString = "";
	
	switch(current_metric)
	{
		case "delta_plays":
			var met = "Plays";
			break;
		case "delta_fans":
			var met = "Fans";
			break;
		case "delta_views":
			var met = "Views";
			break;
		case "delta_comments":
			var met = "Comments";
			break;
		default:
			var met = "";
	}
	
	valChangeString +=  met;
	
	switch(current_range)
	{
		case "week":
			valChangeString += " this Week <a class='explainInfo' href='javascript:showHelp();'>&nbsp;</a>";
			break;
		case "month":
			valChangeString += " this Month <a class='explainInfo' href='javascript:showHelp();'>&nbsp;</a>";
			break;
		case "all_time":
			valChangeString += " All Time <a class='explainInfo' href='javascript:showHelp();'>&nbsp;</a>";
			break;
		default:
			valChangeString += "<a class='explainInfo' href='javascript:showHelp();'>&nbsp;</a>";
	}
	
	
	$("#artistTileNum"+tileNum+" .valueChangeHolder h4").html(valChangeString);
	
	//if(!$("#artistTileNum"+tileNum+" .valueChangeHolder .valueChange .valChild").hasClass(".g"+band_id+current_metric+current_range))
	
		var valChangeArr = calculateValueChange(band_id);
		
		generateNetworkBreakDown(met, tileNum, band_id, valChangeArr[3]);
		
		var newValChild	= "<div class='valChild g"+band_id+current_metric+current_range+"'>";
		newValChild		+= "<h3>"+valChangeArr[0]+"</h3>";
		newValChild		+= "<p class='"+valChangeArr[2]+"'>"+valChangeArr[1]+"</p>";
		newValChild		+= "</div>";
		
		$("#artistTileNum"+tileNum+" .valueChangeHolder .valueChange").html(newValChild);
		
		
	
}

/*
	This function calculates the value and change for the given range and metric
	Returns an array. arr[0] = Value, arr[1] = %Change, arr[2] = Class w/ color
	arr[3] = returns a Hash of % breakdown by service
*/
function calculateValueChange(band_id, metric)
{
	
	if(metric==undefined)
		metric = current_metric;
	
	//.positive, .negative, .neutral
	
	var active_services = getCurrentActiveServices();
	var services = active_services[0];
	
	var valChangeArr = new Array();
	if(all_bands.hasItem(band_id))
	{
		var band_data = all_bands.getItem(band_id);
		var metrics = band_data.metrics;
		if(metrics.hasItem(metric))
		{
			var cur_metric = metrics.getItem(metric);
			
			switch(current_range)
			{
				case "all_time":
					{
						var all_time = 0;			
						
						for(var i=0; i<services.length; i++)
							if(cur_metric.hasItem('final_'+services[i]) && cur_metric.getItem('final_'+services[i]) > -1)
								all_time += cur_metric.getItem('final_'+services[i]);
						
						// Get Breakdown!
						var breakdown = new Hash();
						for(var i=0; i<services.length; i++)
						{
							if(cur_metric.hasItem('final_'+services[i])  && cur_metric.getItem('final_'+services[i]) > -1)
							{
								breakdown.setItem('per_'+services[i],  100*(cur_metric.getItem('final_'+services[i])/all_time));
								breakdown.setItem('val_'+services[i],  cur_metric.getItem('final_'+services[i]));
							}
						}
						valChangeArr[0] = commaCoder(all_time);
						valChangeArr[1] = "";
						valChangeArr[2] = "neutral";
						valChangeArr[3] = breakdown;
					}
					break;
				case "month":
					{
						var first_x_days = 0; //end_date minus 30 to 0
						var secnd_x_days = 0; //end_date minus 60 to 30
						
						for(var i=0; i<services.length; i++)
						{
							if(cur_metric.hasItem(services[i]))
							{
								//let's start 60 days ago.
								var start_60 = end_date - 60;
								
								var service_data = cur_metric.getItem(services[i]);
								
								for(var j=start_60; j < end_date; j++)
								{
									if(service_data.hasItem(j) && service_data.getItem(j) >=0)
										if(j< end_date - 30)
											secnd_x_days += service_data.getItem(j);
										else
											first_x_days += service_data.getItem(j);
								}
							}
						}
						
						
						//Get Breakdown!
						var breakdown = new Hash();
						if(first_x_days > 0)
							for(var i=0; i<services.length; i++)
							{
								if(cur_metric.hasItem(services[i]))
								{
									//let's start 30 days ago.
									var start_30 = end_date - 30;
									
									var service_data = cur_metric.getItem(services[i]);
									
									var tot_for_service =0;
									for(var j=start_30; j < end_date; j++)
										if(service_data.hasItem(j) && service_data.getItem(j) >=0)
											tot_for_service += service_data.getItem(j);
									
									breakdown.setItem('per_'+services[i],  100*(tot_for_service/first_x_days));
									breakdown.setItem('val_'+services[i],  tot_for_service);
								}
							}
						
						valChangeArr[3] = breakdown;
						
						
						valChangeArr[0] = commaCoder(first_x_days);
						
						if(secnd_x_days >0)
							var perChange = Math.round((100*(first_x_days - secnd_x_days)/ secnd_x_days)*10)/10;
						else
							var perChange = "-";
							
						valChangeArr[1] = perChange+"%";
						
						if(perChange < 0)
							valChangeArr[2] = "negative";
						else if(perChange>0)
						{
							valChangeArr[1] = "+"+perChange+"%";
							valChangeArr[2] = "positive";
						}
						else
						{
							valChangeArr[1] = "-";
							valChangeArr[2] = "neutral";
						}
						
				
					}
					break;
				case "week":
					{
						var first_x_days = 0; //end_date minus 7 to 0
						var secnd_x_days = 0; //end_date minus 14 to 7
						
						for(var i=0; i<services.length; i++)
						{
							if(cur_metric.hasItem(services[i]))
							{
								//let's start 14 days ago.
								var start_14 = end_date - 14;
								
								var service_data = cur_metric.getItem(services[i]);
								
								for(var j=start_14; j < end_date; j++)
								{
									if(service_data.hasItem(j) && service_data.getItem(j) >=0)
										if(j< end_date - 7)
											secnd_x_days += service_data.getItem(j);
										else
											first_x_days += service_data.getItem(j);
								}
							}
						}
						
						
						//Get Breakdown!
						var breakdown = new Hash();
						if(first_x_days > 0)
							for(var i=0; i<services.length; i++)
							{
								if(cur_metric.hasItem(services[i]))
								{
									//let's start 7 days ago.
									var start_7 = end_date - 7;
									
									var service_data = cur_metric.getItem(services[i]);
									
									var tot_for_service =0;
									for(var j=start_7; j < end_date; j++)
										if(service_data.hasItem(j) && service_data.getItem(j) >=0)
											tot_for_service += service_data.getItem(j);
									
									breakdown.setItem('per_'+services[i],  Math.round(100*(tot_for_service/first_x_days)));
									breakdown.setItem('val_'+services[i], tot_for_service);
								}
							}
						
						valChangeArr[3] = breakdown;
						
						
						
						valChangeArr[0] = commaCoder(first_x_days);
						
						if(secnd_x_days >0)
							var perChange = Math.round((100*(first_x_days - secnd_x_days)/ secnd_x_days)*10)/10;
						else
							var perChange = "-";
						
						valChangeArr[1] = perChange+"%";
						
						if(perChange < 0)
							valChangeArr[2] = "negative";
						else if(perChange>0)
						{
							valChangeArr[1] = "+"+perChange+"%";
							valChangeArr[2] = "positive";
						}
						else
						{
							valChangeArr[1] = "-";
							valChangeArr[2] = "neutral";
						}
					
					}
					break;
				default:
					valChangeArr[0] = "-";
					valChangeArr[1] = "-";
					valChangeArr[2] = "neutral";
			}
		}
	}

	return valChangeArr;
	
}

/*
	This function goes through the current_bands array and gets the artist names
	Puts the artist names in the search queries.
*/

function getArtistNames()
{
	$(".compareInput").val('');
	$(".combands").val('');
	
	for(var i =0; i< current_bands.length; i++)
	{
		if(all_bands.hasItem(current_bands[i]))
		{
			var data = all_bands.getItem(current_bands[i]);
			
			$("#query"+(i+1)).val(unescape(data.name));
			$("#band"+(i+1)).val(data.band_id);
			
		}
	}
}

function toggleNetworkBoxes()
{
	var count_num_checked =0;
	array_of_checked = new Array();
	var met = current_metric.substring(6);
	$("#toggle_"+met+" .toggleHolder").children("input").each(function(){
		
		if($(this).attr('checked'))
		{
			array_of_checked[count_num_checked] = $(this).attr('id').substring(met.length+1).toUpperCase();
			count_num_checked++;
			
		}
	});
	
	if(count_num_checked == 1)
	{
		$("#toggle_"+met+" .toggleHolder").children("input").each(function(){
			if($(this).attr('checked'))
				$(this).attr('disabled', true);
		});
	}
	else
	{
		$("#toggle_"+met+" .toggleHolder").children("input").each(function(){
			$(this).attr('disabled', false);
		});
	}
}

function Artist(band_id, name, metrics, enough, verified)
{
	this.band_id = band_id;
	this.name = name;
	this.metrics = metrics;
	this.enough = enough;
	this.verified = verified;
}

Artist.prototype.getName = function(){
	return this.name;
}

Array.prototype.unique = function () {
	var r = new Array();
	o:for(var i = 0, n = this.length; i < n; i++)
	{
		for(var x = 0, y = r.length; x < y; x++)
		{
			if(r[x]==this[i])
			{
				continue o;
			}
		}
		r[r.length] = this[i];
	}
	return r;
}
