dojo.require("dojox.gfx");
dojo.require("dojox.gfx.fx");
dojo.require("dojox.fx.chain");

var map;
var state_label_cache = []

function flip_states(e) {

  if ( e.target.id.indexOf('map') != -1 ) {
    dojo.animateProperty({
      node:  dojo.byId('state_list'),
      duration: 600,
      properties: { 
        opacity: 0,  
        width:0
      }
    }).play();
  } else {
      dojo.animateProperty({
        node:  dojo.byId('state_list'),
        duration: 600,
        properties: { 
          opacity: 1,  
          width:690
        }
      }).play();
  }
}


// let's try caching the names instead of computing them
function cached_label(id ) {
  
  if (state_label_cache[id]) {
    return state_label_cache[id];
  }
  
  var tmp_id = id.split("_");
  // capitalize the first letter of each word
  for ( var i=0;i<tmp_id.length; i++) {
     tmp_id[i] = tmp_id[i].substr(0,1).toUpperCase() + tmp_id[i].substr(1);
  }
  state_label_cache[id] = tmp_id.join(" ");
  
  return state_label_cache[id];
}  

function show_regions_click(e) {
  e.preventDefault();
  var slug = e.target.id.split(/-/)[1];
  show_regions(slug);
}
  
function show_regions(slug) {
  dojo.query('.region').forEach( function(li) {
      dojo.animateProperty({
                  node:  li,
                  duration: 300,
                  properties: { 
                    opacity: 0,
                    height:0
                  }
              }).play();
  });
  
  dojo.xhrGet({
    url: "/location/children/" + slug,
    handleAs: "json",
    timeout: 5000,
    load: function(response, ioArgs) {
      dojo.byId('region_list').innerHTML = '';
      
      for ( var i=0; i<response.length;i++ ) {
        
        a = document.createElement('a');
        dojo.addClass(a, 'region_link');
        a.href =  '/location/set_location/' + response[i].slug;
        a.appendChild(document.createTextNode(response[i].name));
        
        li = document.createElement('li');
        dojo.addClass(li, "region")
        li.style.height = '0px';
        li.style.opacity = 0;
        li.appendChild(a)
        
        dojo.byId('region_list').appendChild(li);
        dojo.animateProperty({
          node:  li,
          duration: 500,
          properties: { 
            opacity: 1,  
            height:20
          }
        }).play();
        
      }
    },
    error: function(response, ioArgs) {
       console.log("Error Occured");
     }
   });
  
}

dojo.declare(
  "ff0000.StatesMap", 
  null, 
  {
    dom_node : null,
    data_url : null,
    width : null,
    height : null,
    svg : null,
    surface : null,
    shapes : [],
    data : [],
    events : [],
    
    constructor : function( dom_node, data_url) {
        this.dom_node = dom_node
        this.data_url = data_url
        this.load_data();
    },
    build_map : function(svg) {

      this.states = svg.getElementsByTagName('path');
      states = this.states

      width = svg.documentElement.getAttribute('width');
      height = svg.documentElement.getAttribute('height');

      // create the canvas
      this.surface = dojox.gfx.createSurface(dojo.byId('svg_map'), width, height);
      surface = this.surface;
      
      for (var i=0;i<states.length;i++) {
        var id;
        var d;

        try {
          d = dojo.attr(states[i], 'd');
          id = dojo.attr(states[i], 'id');
        } catch (e) {
          d = states[i].getAttribute("d");
          id = states[i].getAttribute("id");
        }

        path = surface.createPath();
        path.setShape(d).setStroke("#93a067")

        this.shapes[id] = path;

        if (id.length != 1 ) {
          path.setFill("#bdca90");
          node = path.getNode()
          dojo.attr(node, "id", id);
          this.rig_state_events(id)
        }
      }
    },
    load_data : function() {
        dojo.xhrGet({
          url: this.data_url,
          handleAs: "xml",
          timeout: 5000,
          load: dojo.hitch( this, function(response, ioArgs) {
              svg = response;
              this.build_map(svg);
            }
          ),
          error: function(response, ioArgs) {
             console.log("Error Occured");
             console.log(response);
             console.log(ioArgs);
           }
        });
    },
    highlight : function(e) {
      id = e.target.getAttribute('id')
      this.shapes[id].setFill("#FFF");
      dojo.byId('state_tip').style.display = 'block';
      dojo.byId('state_tip').innerHTML = "&nbsp;" + cached_label(id) + "&nbsp;";
      dojo.byId('state_tip').style.left = e.clientX + 15 + 'px';
      dojo.byId('state_tip').style.top = e.clientY - 15 + 'px';
      document.body.style.cursor = 'pointer'
    },
    lowlight : function(e) {
      this.shapes[e.target.getAttribute('id')].setFill("#bdca90");
      dojo.byId('state_tip').style.display = 'none';
      dojo.byId('state_tip').innerHTML = '';
      document.body.style.cursor = 'default'
    },
    select_state : function(e) {
      dojo.byId('state_tip').style.display = 'none';
      dojo.byId('state_tip').innerHTML = '';
      var id = e.target.id;
      if (this.raised != null) {
        this.raised.removeShape();
        this.rig_state_events(this.active_state_id);
        dojox.gfx.fx.animateFill({
                            shape : this.shapes[this.active_state_id],
                            duration : 300,
                            color: { 'start': '#5e6546', 'end':  '#bdca90'}
                        }).play();
      }
      show_regions(id);

      this.flip_state_label(id);
      
      this.unrig_state_events(id)
      
      p = surface.createPath();
      p.setShape(this.shapes[id].getShape().path).setStroke("#93a067");
      p.setFill("#FFFFFF");

      dojox.gfx.fx.animateTransform({
                          shape : p,
                          duration : 500, 
                          transform: [
                              {name : "translate", start : [0, 0], end:[8,-8]}
                          ]
                      }).play();
                      
      dojox.gfx.fx.animateFill({
                          shape : this.shapes[e.target.id],
                          duration : 500,
                          color: { 'start': '#bdca90', 'end': '#5e6546' }
                      }).play();
      
      this.active_state_id = id;
      this.raised = p;
    },
    flip_state_label : function(id) {
      var inward = dojo.animateProperty({
        node:  dojo.byId('state_name_wrapper'),
        duration: 300,
        onEnd: function(e) {
          dojo.byId('state_name').innerHTML = cached_label(id);
        },
        properties: { 
          opacity: 0,  
          top:228
        }
      });
      var outward = dojo.animateProperty({
        node:  dojo.byId('state_name_wrapper'),
        duration: 300,
        properties: { 
          opacity: 1,  
          top:200
        }
      });
      dojo.fx.chain([inward,outward]).play();
    },
    rig_state_events : function(id) {
      path = this.shapes[id]
      this.events[id + '-click'] = path.connect('click', this, 'select_state');
      this.events[id + '-onmouseover'] = path.connect('onmouseover', this, 'highlight');
      this.events[id + '-onmouseout'] = path.connect('onmouseout', this, 'lowlight');
    },
    unrig_state_events : function(id) {
      dojo.disconnect(this.events[id + '-click']);
      dojo.disconnect(this.events[id + '-onmouseover']);
      dojo.disconnect(this.events[id + '-onmouseout']);
    }
});



  
function page_init() {
  try {
    map = new ff0000.StatesMap(dojo.byId('svg_map'), 'map2.svg');
    dojo.byId('state_list').style.width = '0px';
    dojo.byId('select_state').style.display = 'block';
    dojo.byId('state_name_wrapper').style.display = 'block';
    dojo.byId('map').style.height = '275px';
    
    dojo.connect( dojo.byId('text_button'), 'click', flip_states);
    dojo.connect( dojo.byId('map_button'), 'click', flip_states);
    
    dojo.query("a.state_link").forEach( function (state_link ) {
      dojo.connect(state_link, 'click', show_regions_click);
    });
  } catch (err ) {
    dojo.query("a.state_link").forEach( function (state_link ) {
      dojo.connect(state_link, 'click', show_regions_click);
    });
  }
  
}
  
dojo.addOnLoad(page_init)
