var years = [1999, 2004, 2009, 2014];
var provinces = ['EASTERN CAPE', 'FREE STATE', 'GAUTENG', 'KWAZULU-NATAL', 'LIMPOPO', 'MPUMALANGA', 'NORTH WEST', 'NORTHERN CAPE', 'WESTERN CAPE'];

var partyImages = ['ANC', 'DA', 'IFP', 'NNP', 'EFF'];

function haveImage(party) {
	// for (var i in partyImages) {
	// 	if (party == partyImages[i])
	// 		return true;
	// }
	// return false;
	return exists(party, partyImages) != -1;
}

function exists(value, array) {
	for (var i in array) {
		if (value == array[i])
			return i;
	}
	return -1;
}
function getDataForProvince(type, province, callBack) {
  var data = {};
  var yearCount = 0;
  for (var i in years) {
    var name = years[i] + ' ' + type + ' ' + province;

    getCSVData(name, function(year) {
      return function(csv) {
        data[year] = csv;
        yearCount++;
        if (yearCount == years.length) {
        	callBack(data);
        }
      }
    }(years[i]));

  }
}

var baseColour = d3.scale.ordinal()
      .range(["#001c9c","#101b4d","#475003","#9c8305","#d3c47c"]);

if (typeof(varNames) != 'undefined') {
var color = d3.scale.ordinal()
  .range(varNames.map(function(name) {
    if (name == 'ANC') return 'lime';
    if (name == 'DA') return 'lightblue';
    if (name == 'EFF') return 'red';
    if (name == 'COTP') return 'yellow';
    if (name == 'NNP') return 'orange';
    return baseColour(name);
  }));
}

function getCSVData(name, callBack) {
  $.get( name + ".csv", function( data ) {
    var csved = $.csv.toObjects(data);

    var provinces = [];
    var words = [];
    var parties = {};

    for (var i = 0; i < csved.length; i++) {
      if (!parties[csved[i]['PARTY NAME']]) {
        parties[csved[i]['PARTY NAME']] = {'name':csved[i]['PARTY NAME'], total:0};
      }

      parties[csved[i]['PARTY NAME']].total += +csved[i]['VALID VOTES'];
    }

    var myWords = [];
    for (var i in parties) {
        myWords[parties[i].name] = parties[i].total;
    }

    callBack(myWords);
  });
};


function getDataFor(partySet, data) {
  var returnedData = [];

  for (var partyIndex in partySet) {
    var party = partySet[partyIndex];
    var partyData = [];
    var partyObject = {'name': party, 'values': partyData};
    for (var year in data) {
      var parties = data[year];

      partyData.push({'name':party, 'value': parties[party] ? parties[party] : 0, 'label':year});
    }
    returnedData.push(partyObject);
  }
  return returnedData;
}

function getAllParties(data) {
  var partyCheck = {};
  var allParties = [];

  for (var year in data) {
    var parties = data[year];
    for (var party in parties) {
      if (!(party in partyCheck)) {
        allParties.push(party);
        partyCheck[party] = true;
      }
    }
  }
  return allParties;
}