#!/usr/bin/env python

import simplejson, urllib, os
from xml.dom import minidom

if os.path.exists("us-pres.json"):
  fp = open("us-pres.json")
else:
  fp = urllib.urlopen("http://election2008.s3.amazonaws.com/votes/us-pres.json")

data = simplejson.loads(fp.read())
fp.close()

candidates = data["candidates"].items()

MCCAIN=[x[0] for x in candidates if x[1] == "GOP|McCain|John McCain"][0]
OBAMA=[x[0] for x in candidates if x[1] == "Dem|Obama|Barack Obama"][0]

fp = open("Map_of_USA_with_state_names.svg")
svg = minidom.parseString(fp.read())
fp.close()

states = data['locals'].keys()

for state in states:
  abbr = data['locals'][state]['abbr']
  mcc = [x['votes'] for x in data['locals'][state]['races']['President']['']['votes']
         if x['id'] == MCCAIN][0]
  oba = [x['votes'] for x in data['locals'][state]['races']['President']['']['votes']
         if x['id'] == OBAMA][0]
  ratio = float(mcc) / float(oba)
  if ratio > 1: 
    ratio = 1/ratio
    r = 255
    b = int(r * ratio)
  else:
    b = 255
    r = int(b * ratio)
  hexcol = "#%s00%s" % (hex(r)[2:],hex(b)[2:])
  #print "State: %s, McCain: %s, Obama: %s, ratio: %s, r: %s, b: %s, hex: %s" % (state, mcc,oba,ratio,r,b,hexcol)
  svgstates = [x for x in svg.getElementsByTagName("path") if x.getAttribute("id") == abbr]
  if svgstates:
    svgstates[0].setAttribute("style","fill:%s" % hexcol)

print svg.toxml()

