/*


Dynamic Application of Functions to DOM
*/
var _debugMode = false;
document.observe('dom:loaded', init);

document.observe('map:complete', addAddressPoint);


document.observe('map:addressNotFound', function(e){
  $('geocode_error').show().update(e.memo.error);
});

function init () {
  handleTwoColumnUl();
  
  removeDoubleBRs();
  
  setupLocationsPage();
  
  handleByLocationForm();
}


// handles splitting one <ul> in to two
function handleTwoColumnUl() {
  var businessCat = $$('.business-cat');
  if (businessCat.length != 2) return;

  var liEls = businessCat[0].select('li');

  var evenEls = (liEls.size() / 2).ceil();
  // var splitEls = liEls.splice(evenEls);
  liEls = liEls.inGroupsOf(evenEls)
  
  //have to clear out what is in the old dom element to insert the new stuff in a loop
  // businessCat[0].update('');  

  for (var i=0; i < liEls[1].length; i++) {
    businessCat[0].insert({bottom: liEls[0][i]});
    businessCat[1].insert({bottom: liEls[1][i]});
  };
  //if the elements aren't even we gotta get the last one
  if (evenEls % 2 != 0) businessCat[0].insert({bottom: liEls[0].pop()});
}

function removeDoubleBRs() {
  var addresses = $$('.address');
  if (!addresses) return;
  addresses.each(function(el) {
    el.innerHTML = el.innerHTML.gsub('<br><br>', '<br>');
  })
}

function setupLocationsPage() {
  if (!window.location.href.include('/directory/')) return;
  
  tag = window.location.pathname.split('/directory/').pop().gsub('%20', ' ').gsub('%2F', '/').gsub('+', ' ');
  
  //add tag name to page
  $('tag-name').update(tag);
  
  // make sure current category is selected in select box
  $('business-category').childElements().find(function(el) { return el.value == tag }).selected = true;
  //if there is a search make sure it is in the address field
  if (window.location.search) {
    query = window.location.search.split('=').pop().gsub('%20', ' ');
    $('address').value = query;
  }
  
  //make sure links with no external site are modified
  var html;
  $$('a[href=""]').each(function(el) {
    html = el.innerHTML;
    el.up().update(html);
  });
  
  //hide view more if there is nothing more to see
  $$('.business > div').each(function(el) {
    if (!el.childElements().detect(function(el) {return !el.empty();}))
    el.previous('.view-more').hide();
  });
  
  $$('.content-col')[0].observe('click', function(e){
    var el = e.element();
    if (el.hasClassName('view-more')) {
      e.stop();
      el.blur();
      Effect.BlindDown(el.next('div'), {
        duration: .25,
        queue: {scope: 'blind_down', limit: 1},
        afterFinish: function() {
          el.removeClassName('view-more').addClassName('view-less').update('view less');
        }
      });
    }
    else if (el.hasClassName('view-less')) {
      e.stop();
      el.blur();
      Effect.BlindUp(el.next('div'), {
        duration: .25,
        queue: {scope: 'blind_up', limit: 1},
        afterFinish: function() {
          el.removeClassName('view-less').addClassName('view-more').update('view more');
        }
      });
    }
  });
  
  setupGoogleMap();

}

function handleByLocationForm() {
  if (!$('byLocation')) return;
  
  $('byLocation').observe('submit', function(e){
    if (window.location.pathname.split('/directory/').pop().gsub('%20', ' ') != $F('business-category')) {
      e.stop();
      window.location = '/directory/' + $F('business-category') + '?a=' + $F('address');
    }
    else if ($F('address') == window.defaultAddressValue || $F('address') == '') {
      document.fire('map:addressNotFound', { error: 'You gotta search for a real location!' });
      e.element().blur();
      e.stop();
    }
    else {
      document.fire('map:geoCodeAddress', {
        q: $F('address'),
        icon: {
          image: '/images/blue-dot.png',
          iconSize: new GSize(32, 32)
        }
      });
      e.element().blur();
      e.stop();
    }
  });
  
  window.defaultAddressValue = $F('address');
  $('address').observe('focus', function(e){
    if ($F(e.target) == window.defaultAddressValue)
      e.target.value = '';
  }).observe('blur', function(e){
    if ($F(e.target) == '')
      e.target.value = window.defaultAddressValue;
  });
}


function addAddressPoint() {
  if (!window.location.search) return;
  document.fire('map:geoCodeAddress', {
    q: window.location.search.split('=').pop().gsub('%20', ' '),
    icon: {
      image: '/images/blue-dot.png',
      iconSize: new GSize(32, 32)
    }
  });
}

function setupGoogleMap () {
  new Ajax.Request('/list/tag/' + window.tag.gsub('/', '%2F') + '.js', {
    method: 'get',
    onComplete: function(response){
      // manipulate that data
      var r = response.responseText.evalJSON()[0];
      var data = {};
      
      r.items.each(function(item, i){
        
        function getCustomField (name) {
          var customField = item.custom_fields.find(function(f){ return f.name == name });
          if (customField) {
            return customField.value;
          } else {
            return '';
          }
        }
        
        data[item.title] = {
          name: item.title,
          latitude: getCustomField('Latitude'),
          longitude: getCustomField('Longitude'),
          address: getCustomField('Address 1') + ' ' + getCustomField('Address 2'),
          phone: getCustomField('Phone')
        };
        
      });
      
      var gmap = new GoogleMap('map', {
        controls: [new GSmallMapControl()],
        infoWindowTemplate: new Template('<div class="googleMapsPopup"><strong>#{name}</strong><br />#{address}<br />Phone: #{phone}'),
        data: data,
        zoom: 11,
        embedEvent: false
      });
    }
  });
}


