// provide a shorter version to listen for events (ike jQuery) but with a $-prefix
// so it won't conflict with the builtin click() submit() etc.
// $(element).$click(function() { ... });

(function() {
  
  // Alias events to work directly as methods on elments
  var methods = {};
  
  $w("blur focus load resize scroll unload click dblclick ready" +
     "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
     "change select submit keydown keypress keyup error").each(function(eventName) {
    methods['$' + eventName] = function(element, handler) {
      return Event.observe(element, eventName, handler);
    }
  });
  
  Element.addMethods(methods);
  
  // alias $(document).ready for dom:loaded
  Object.extend(document, {
    ready: Event.observe.curry(document, 'dom:loaded')
  });
})();

// ----------------------------------------------------------------------------

Page = window.Page || {};
Page.insertScript = function(src) {
  $(document.documentElement).down('head').insert(new Element('script', { src: src }));  
}

// ----------------------------------------------------------------------------

$("sidebar_tabs").$click(function(event) {
  if (event.findElement('.view-tab-unselected')) {
    var tabs = $('sidebar_tabs'), target = event.findElement('.view-tab'),
      selected = tabs.down(".view-tab-selected");
    
    selected.removeClassName('view-tab-selected').addClassName('view-tab-unselected');
    target.removeClassName('view-tab-unselected').addClassName('view-tab-selected');
    
    Element.hide(selected.id.split("_tab")[0]);
    Element.show(target.id.split("_tab")[0]);
  }
});

// ----------------------------------------------------------------------------

this.suggestSubmitted = function(data) {
  var form = $('suggest_form'), elements = form.getElements();
  elements.each(function(element) {
    element.removeClassName('invalid').removeClassName('disabled').enable();
  });

  $("form_loading").hide();
  $('submit_suggestion').show();

  if (data.created) {
    [form, $('suggest_thanks')].each(Element.toggle);
    form.select('input.text, textarea, #event_latlon').invoke('setValue', '');
    
  } else {
    data.errors.map(function(error) {
      return form.down('input[name=' + error[0] + ']').addClassName("invalid");
    }).first().focus();
  }
};

$("suggest_thanks").down('a').$click(function(event) {
  event.stop();
  $('suggest_form', 'suggest_thanks').each(Element.toggle);
});

$("event_notes").$focus(function() {
  this.removeClassName("empty");
}).$blur(function() {
  if (this.value.empty()) this.addClassName("empty");
});

function formSubmitHandler(event) {
  if (event) event.stop();
  if (Map.marker) $('event_latlon').setValue(Map.marker.getLatLng().toUrlValue());

  var form = $('suggest_form');
  
  form.request({
    parameters: 'jsoncallback=suggestSubmitted',
    onLoading: function() {
      $('submit_suggestion').hide();
      $('form_loading').show();
    }
  });
  
  form.getElements().invoke('disable').invoke('addClassName', 'disabled');
};

$("suggest_form").$submit(formSubmitHandler);

// ----------------------------------------------------------------------------

var Map = {
  DEFAULT_CENTER: location.href.include('tell.be') ? [50.846281, 4.354727] : 
                  location.href.include('tell.no') ? [59.9138204, 10.7387413] : 
                  [59.319489782591624, 18.072305917739868],
  DEFAULT_ZOOM: 11,

  KEYS: {
    'projects':          'ABQIAAAABQsJGy0yGbHykgGWs-F31RS1jZqVAWoeGahtV2yb6oFgPiRFAxRuQpRM7XujhCZNKmom7Z3JX9zyMg',
    'showtell.se':       'ABQIAAAABQsJGy0yGbHykgGWs-F31RToStj9holew5WD8kqxXTuZ9aOVURS6rkRBrgxbGotMjk2srLi8WLDsDg',
    'showandtell.se':    'ABQIAAAABQsJGy0yGbHykgGWs-F31RSSLPh_Uyu5zuDXZjQHJhKaYEMc3RQFh76Elmlwymhw3PT1H1VJwp74_w',
    'showtell.se.local': 'ABQIAAAABQsJGy0yGbHykgGWs-F31RTLM4HorgZx5NQp64hB_axmvU75lRSvkdQxCtkmE0k4yfgXvf6af_HgTA',
    'showtell.be':       'ABQIAAAABQsJGy0yGbHykgGWs-F31RR94DQZqoQFNisAVoJqgDYqP0c-6hTAw7q5Dhto9KJPq2fssMz1fUEppg',
    'showandtell.be':    'ABQIAAAABQsJGy0yGbHykgGWs-F31RQ69AgRLyG-6gYfQnSjmQsfrZYXWBSuwjXn5-Vx3tdEO2U3kTlViJ6XUg',
    'showtell.be.local': 'ABQIAAAABQsJGy0yGbHykgGWs-F31RSam9eKef9iX8hkVzuG5fC3zO65KBTesoGHUf-4wS3HGeM28_MozoEJsA',
    'showtell.no.local': 'ABQIAAAABQsJGy0yGbHykgGWs-F31RQsjuMLvDgpJTb-6KBjnw_FqEFYixSNg0-Q3UoRwCIEcFG844co6eh_dw',
    'showtell.no':       'ABQIAAAABQsJGy0yGbHykgGWs-F31RSYXIfbs0vegZ_0jDZUJKV7FMKVdRQLQoJN2aG2foKgBkKu_GqFTXTDpw'
  },
  
  load: function() {
    var key = this.KEYS[window.location.host.replace(/www\./, '')];
    Page.insertScript('http://maps.google.com/maps?file=api&v=2.x&key=' + key + '&async=2&callback=Map.loaded');
  },
  
  loaded: function() {
    var form = $('suggest_form');
    
    function cancelFormSubmission(event) {
      event.stop()
      Map.search();
    }
    
    function focusHandler(event) {
      form.$submit(cancelFormSubmission).stopObserving('submit', formSubmitHandler);
    }

    function blurHandler(event) {
      form.$submit(formSubmitHandler).stopObserving('submit', cancelFormSubmission);
    }

    $('event_location').$focus(focusHandler).$blur(blurHandler);
    
    this.map = new GMap2($('gmap'));
    this.map.addControl(new GSmallMapControl());
    this.map.setCenter(new GLatLng(this.DEFAULT_CENTER[0], this.DEFAULT_CENTER[1]), this.DEFAULT_ZOOM);
    this.geocoder = new GClientGeocoder();

    this.marker = new GMarker(this.map.getCenter(), { draggable: true });
    this.map.addOverlay(this.marker);
    
    // var self = this;
    
    // GEvent.addListener(this.map, 'click', function(overlay, point) { 
    //   self.marker.setLatLng(self.map.getCenter());
    //   return false;
    // });

    GEvent.addListener(this.map, 'dblclick', function(overlay, point) { 
      // if (!this.marker) this.createMarker(point);
      // this.marker.setLatLng(this.map.getCenter());
      return false;
    });
  },
  
  search: function(terms) {
    terms = terms || $F('event_location');
    this.geocoder.getLatLng(terms, function(point) {
      this._placeMarkerAndCenter(point);
    }.bind(this));
  },
  
  _placeMarkerAndCenter: function(point) {
    this.map.setCenter(point, 15);
    this.marker.setLatLng(point);
  }
};

Map.load();

// ----------------------------------------------------------------------------

(function(global) {
  function loaded(container, content) {
    container = $(container);
    container.removeClassName("loading").update(content);
    container.down("li:last-child").addClassName("last-child");
  }
  
  global.onlineLecturesLoaded = loaded.curry('online_lectures_content');
  global.editorsLoaded = loaded.curry('editors');
  
  $$('.async-content').each(function(elm) {
    Page.insertScript(elm.update("Loading&hellip;").addClassName("loading").readAttribute('data-uri'));
  });
})(this);