Ext.BLANK_IMAGE_URL = '../calculator/ext/resources/images/default/s.gif';
Ext.Element.prototype.visibilityMode = Ext.Element.DISPLAY;

Ext.onReady(function() {  
  Ext.get('mapdata').hide();
  Ext.get('ctpinit').show();

  var params = { play: "true", menu: "false", base: ".", allowscriptaccess: "always", quality: "high", wmode: "transparent", allowfullscreen: "true"};
  var attributes = { id: "fmASEngine", name: "fmASEngine" };
  var flashvars = { };
  swfobject.embedSWF("fmASMap/fmASContainer.swf", "map", "700", "300", "9.0.0", "", flashvars, params, attributes);
  
  Ext.select('#ctpdata img.more', true).each(function(el, comp, idx) {
    var parent = el.parent('li');
    var child = parent.child('ul');
    var parentIsLast = parent.hasClass('last');
    
    child.hide();
    el.set({'src':'img/plus.png'});
    el.on('click', function(mEvt, mEl) {
      child.toggle();
      if (child.isVisible()) {
        el.set({'src':'img/minus.png'});
      } else {
        el.set({'src':'img/plus.png'});
      }
      
      if (parentIsLast) {
        parent.toggleClass('last');
      }
    });
  });

  if (!Ext.isIE7 && !Ext.isIE6) {
    var loadMask = new Ext.LoadMask(Ext.get('mapdata'), {msg:"Please wait, loading..."});
    Ext.Ajax.on('beforerequest', loadMask.show, loadMask);
    Ext.Ajax.on('requestcomplete', loadMask.hide, loadMask);
    Ext.Ajax.on('requestexception', loadMask.hide, loadMask);
  }
  
  Ext.select('#ctphelp .help', true).each(function(e, c, i) {
    var id = e.dom.id.substr(e.dom.id.indexOf('_') + 1);
    var el = Ext.get(id);
    if (el) {
      var nameEl = el.child('div.item .name');
      var imgEl = Ext.get(Ext.DomHelper.append(nameEl, {tag:'img', cls:'help', src:'img/question.png', alt:'Help'}, true));
      imgEl.on('click', function() {
        if (!this.win) {
          var txt = getTxt(nameEl.dom).trim();
          this.win = new Ext.Window({
            renderTo: Ext.getBody(),
            title: "Help: " + txt,
            width: 400, height: 375,
            closable: true,
            contentEl: e.dom.id,
            modal: true,
            bodyStyle: {padding:'10px', fontSize:'1.2em', lineHeight:1.6, backgroundColor:'#ffffff'},
            closeAction: 'hide',
            autoHeight: true
          })
        }
        this.win.show();
      });
    }
  });
});

function getTxt(el) {
  if (typeof(el.textContent) != "undefined") {
    return el.textContent;
  }
  return el.innerText;
}

// Array Remove - By John Resig (MIT Licensed)
// http://ejohn.org/blog/javascript-array-remove/
// Renamed to removeAt because conflicts with Ext.
Array.prototype.removeAt = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

function kdotMoney(val) {
  if (val < 1) {
    val = val * 1000000;
    var money = Ext.util.Format.usMoney(val);
    return money.split('.')[0];
  }
  // Millions with 1 decimal place.
  // $1,101.1m
  val = round(val, 1);
  m = Ext.util.Format.usMoney(val);
  pts = m.split('.');
  if (pts.length == 2) {
    d = pts[1].split('');
    if (d.length > 0) {
      m = pts[0] + '.' + d[0];
    }
  }
  return m + 'm';
}

function getSelectedValues(el) {
  var vals = [];
  for (var i = 0; i < el.options.length; i++) {
    if (el.options[i].selected) {
      vals.push(el.options[i].value);
    }
  }
  return vals;
}

function cleanValues(ids) {
  for (var i = 0; i < ids.length; i++) {
    if (ids[i] == 'all') {
      ids.removeAt(i);
    }
  }
}

function round(value, precision) {
  var result = Number(value);
  precision = Math.pow(10, precision);
  result = Math.round(value * precision) / precision;
  return result;
}

function formatNumber(value) {
  var isBig = false;
  if (value > 1000000) {
    value = value / 1000000;
    isBig = true;
  }
  var rv = round(value, 1);
  var f = rv.toString().split('.');
  var rs = f[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
  if (f.length == 2) {
    rs = rs + '.' + f[1];
  }
  return isBig ? rs + 'm' : rs;
}

function initSummaryData(map) {
  Ext.select('#sum_pop').update(formatNumber(map.summary.residents_sum));
  Ext.select('#sum_bridges').update(formatNumber(map.summary.total_bridges_sum));
  Ext.select('#sum_pop_growth').update(round(map.summary.population_growth_weighted * 100.0, 2) + '%');
  Ext.select('#sum_miles_driven').update(formatNumber(map.summary.miles_driven_sum));
  Ext.select('#sum_res_65').update(round(map.summary.residents_65_weighted * 100.0, 2) + '%');
  Ext.select('#sum_growth_miles_driven').update(round(map.summary.miles_driven_change * 100.0, 2) + '%');
  Ext.select('#sum_road_miles').update(formatNumber(map.summary.total_highway_miles_sum));
}

function initMapData(map) {
  var data = map.map
  // Shortcuts
  var money = kdotMoney;
  var num = Ext.util.Format.number;
  var sel = Ext.select;
  // Names
  if (map.state == '1') {
    sel('.selected_names').update('State of Kansas');
  } else {
    var key = map.district == '1' ? 'district_names' : 'county_names';
    var names = data[key].split(';');
    var type = 'county';
    if ((names.length == 1 || names.length == 5) && map.district == '1') {
      type = 'district';
    } else if (names.length != 1 && map.district == '1') {
      type = 'districts';
    } else if ((names.length != 1 && names.length != 5) && map.county == '1') {
      type = 'counties';
    }
    
    if (names.length > 4) {
      sel('.selected_names').update(names.slice(0, 4).join(', ') + '... ' + (names.length - 4).toString() + ' more ' + type);
    } else {
      if (names.length == 1) {
        sel('.selected_names').update(names[0] + ' ' + type);
      } else {
        sel('.selected_names').update(names.join(', ') + ' ' + type);
      }
    }
  }
  sel('.ctp_total_amount').update(money(data.ctp_total_amount_sum));
  sel('#state_highways_amount').update(money(data.state_highways_amount_sum));
  sel('#preservation_amount').update(money(data.preservation_amount_sum));
  sel('#preservation_miles').update(formatNumber(data.preservation_miles_sum));
  sel('#preservation_bridges').update(formatNumber(data.preservation_bridges_count_sum));
  sel('#reconstruction_amount').update(money(data.reconstruction_amount_sum));
  sel('#reconstruction_miles').update(formatNumber(data.reconstruction_miles_sum));
  sel('#reconstruction_bridges').update(formatNumber(data.reconstruction_bridges_sum));
  sel('#modernization_amount').update(money(data.modernization_total_amount_sum));
  sel('#modernization_miles').update(formatNumber(data.modernization_total_miles_sum));
  sel('#modernization_highway_amount').update(money(data.modernization_highway_amount_sum));
  sel('#modernization_highway_miles').update(formatNumber(data.modernization_total_miles_sum));
  sel('#rehab_amount').update(money(data.rehab_amount_sum));
  sel('#rehab_miles').update(formatNumber(data.rehab_miles_sum));
  sel('#rehab_bridges').update(formatNumber(data.rehab_bridges_sum));
  sel('#expansion_amount').update(money(data.expansion_total_amount));
  sel('#expansion_miles').update(formatNumber(data.expansion_state_highway_miles_sum));
  sel('#expansion_interchanges').update(formatNumber(data.expansion_interchanges_count_sum));
  sel('#expansion_highway_amount').update(money(data.expansion_highway_amount_sum));
  sel('#expansion_highway_miles').update(formatNumber(data.expansion_state_highway_miles_sum));
  sel('#expansion_highway_interchanges').update(formatNumber(data.expansion_interchanges_count_sum));
  sel('#local_roads_amount').update(money(data.local_construction_total_amount_sum));
  sel('#kdot_amount').update(money(data.local_construction_kdot_amount_sum));
  sel('#kdot_miles').update(formatNumber(data.local_construction_kdot_miles_sum));
  sel('#kdot_state_highway_amount').update(money(data.local_construction_on_highway_amount_sum));
  sel('#kdot_state_highway_miles').update(formatNumber(data.local_construction_on_highway_miles_sum));
  sel('#kdot_local_road_amount').update(money(data.local_construction_roads_amount_sum));
  sel('#kdot_local_road_miles').update(formatNumber(data.local_construction_roads_miles_sum));
  sel('#scchf_amount').update(money(data.local_construction_scchf_amount_sum));
  sel('#ccl_amount').update(money(data.local_construction_ccl_amount_sum));
  sel('#modes_amount').update(money(data.modal_spending_total_amount_sum));
  sel('#public_transit_amount').update(money(data.transit_total_amount_sum));
  sel('#public_transit_rides_given').update(formatNumber(data.transit_rides_given_sum));
  sel('#public_transit_state_amount').update(money(data.transit_state_amount_sum));
  sel('#public_transit_federal_amount').update(money(data.transit_federal_amount_sum));
  sel('#aviation_amount').update(money(data.aviation_amount_sum));
  sel('#aviation_airports_improved').update(formatNumber(data.aviation_airports_improved_count_sum));
  
  // sel('#rail_amount').update(money(data.rail_total_amount_sum));
  // sel('#rail_crossing_improvements').update(formatNumber(data.rail_total_crossings_count_sum));
  sel('#rail_track_improvements').update(formatNumber(data.rail_track_improvements_miles_sum));
  sel('#crossing_improvements_amount').update(money(data.rail_crossing_improve_amount_sum));
  sel('#crossing_improvements_count').update(formatNumber(data.rail_crossing_improve_count_sum));
  sel('#crossing_improvements_local_road_amount').update(money(data.rail_local_crossing_amount_sum));
  sel('#crossing_improvements_local_road_count').update(formatNumber(data.rail_local_crossing_count_sum));
  sel('#crossing_improvements_state_highway_amount').update(money(data.rail_highway_crossing_amount_sum));
  sel('#crossing_improvements_state_highway_count').update(formatNumber(data.rail_highway_crossing_improve_count_sum));
  
  sel('#grade_separations_amount').update(money(data.rail_system_amount_sum));
  sel('#grade_separations_count').update(formatNumber(data.rail_system_count_sum));
  sel('#grade_separations_local_road_amount').update(money(data.rail_off_system_amount_sum));
  sel('#grade_separations_local_road_count').update(formatNumber(data.rail_off_system_count_sum));
  sel('#grade_separations_state_highway_amount').update(money(data.rail_on_system_amount_sum));
  sel('#grade_separations_state_highway_count').update(formatNumber(data.rail_on_system_count_sum));
  
  // sel('#track_improvements_amount').update(money(data.rail_track_improvements_amount_sum));
  sel('#rail_amount').update(money(data.rail_track_improvements_amount_sum));
  // sel('#track_improvements_count').update(formatNumber(data.rail_track_improvements_miles_sum));
  
  sel('#bike_amount').update(money(data.bike_amount_sum));
  sel('#bike_miles').update(formatNumber(data.bike_miles_sum));
  
  shhd();
  Ext.get('ctpinit').hide();
  Ext.get('mapdata').show();
}

function shhd() {
  // Select all items.
  Ext.select('#ctpdata li > div.item', true).each(function(el, cel, idx) {
    // Get all the innerHTML for .total and .value.
    var els = el.query('.total').concat(el.query('.value'));
    var isEmpty = true;
    // Check to see if any of the selected items have a value set on them.
    for (var i = 0; i < els.length; i++) {
      var val = els[i].innerHTML.replace(/[^1-9]/g, '');
      if (val.length > 0) {
        isEmpty = false;
        break;
      }
    }
    if (isEmpty) {
      // Hide any items have all the values blank (the parent is the li element).
      el.parent().hide();
      if (el.parent().hasClass('last')) {
        var prev = el.parent().prev();
        if (prev) prev.addClass('last');
      }
    } else {
      // Show / unhide element.
      el.parent().show();
      // Note: Remember these are the div.item elements.
      // Check if the previous element has the .last class (it was previously the last element) and remove it.
      var prev = el.parent().prev();
      if (prev && prev.hasClass('last')) prev.removeClass('last');
    }
  });
  
  // If all the children of a parent are hidden, hide the more image.
  Ext.select('#ctpdata li.parent').each(function(e, c, i) {
    var visibleChildren = e.query('li{display!=none}');
    if (visibleChildren.length <= 1) {
      if (visibleChildren.length > 0) {
        Ext.get(visibleChildren[0]).hide();
      }
      e.select('.more').hide();
    } else {
      e.select('.more').show();
    }
  });
}

/**
 * key == '2'=> county
 * key == '3' => district
 * key == '1' => state
 */
function mapList(key, ids) {
  /* 
  if (ids.trim().length == 0 || (key == '1' && ids == '0')) {
    Ext.get('ctpinit').show();
    Ext.get('mapdata').hide();
    return;
  }
  */
  // When no states or districts are selected show whole state.
  if ((key == '2' || key == '3') && ids.trim().length == 0) {
    key = '1';
  }

  var params = {};
  if (key == '2') {
    params = {county_ids:Ext.encode(ids.split(','))};
  } else if (key == '3') {
    params = {district_ids:Ext.encode(ids.split(','))};
  } else {
    params = {state:'1'};
  }
  Ext.Ajax.request({
    url: 'flashmap.php',
    method: 'post',
    params: params,
    callback: function(opt, suc, res) {
      data = Ext.decode(res.responseText);
      initMapData(data);
      initSummaryData(data);
    }
  });
}
