/*


Dynamic Application of Functions to DOM
*/
var _debugMode = false;
document.observe('dom:loaded', init);
Event.observe(window, 'load', initAfterImages);

function init () {
  if (Prototype.Browser.IE) applyIEStyles();
  
  formatMunicipalitiesHeader();
  
  formatServicesTable();
  
  insertRandomTestimonial();
}

function initAfterImages () {
  
}

function applyIEStyles() {
  $$('#feature-content ul li:last-child').invoke('addClassName', 'last-child');
}

function formatMunicipalitiesHeader() {
  var muniList = $('muni-list');
  if (!muniList) return;
  
  var munis = muniList.select('li');
  var columnList = $$('#municipalities ul.four-column');

  // group the municipalities in groups of 5 [[li,li,li,li,li], [li,li,li,li,li]]
  munis = munis.eachSlice(5);
  
  for (var i=0; i < munis.length; i++) {
    munis[i].each(function(el){
      columnList[i].insert(el);
    });
  }
}

function formatServicesTable() {
  if (!$('services') || !window.XMLHttpRequest) return;
  var yImage = '<img src="/images/y.png" />';
  var nImage = '<img src="/images/n.png" />';
  var wImage = '<img src="/images/w.png" />';
  
  $$('table tr td').each(function(el){
    if (el.innerHTML.toLowerCase() == 'y') el.update(yImage);
    else if (el.innerHTML.toLowerCase() == 'n') el.update(nImage);
    else if (el.innerHTML.toLowerCase() == 'w') el.update(wImage);
  });
  
  var legend = '<tr><td colspan="7" style="text-align: right;">Services Provided: ' + yImage + ' (Yes) or ' + nImage + ' (no) ' + wImage + ' (Would Take Opportunity)</td></tr>';
  $$('table tbody').invoke('insert', {bottom: legend});
}

function insertRandomTestimonial() {
  var insert = $('test-insert');
  if (!insert) return;
  new Ajax.Request('/random-testimonial', {
    method: 'get',
    onSuccess: function(transport) {
      var text = transport.responseText.split('-SPLIT-');
      //get rid of last element in array becuase it will always be empty
      text.pop();
      var index = text.length.rand() - 1;
      insert.update(text[index]);
    }
  })
}