// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
function initialize_maps(){
  if(GBrowserIsCompatible() && typeof events != 'undefined'){
    var map = new GMap2(document.getElementById("map"));
    map.setCenter(new GLatLng(-36.52, 147.47),10);
    map.addControl(new GLargeMapControl());

    //clicking the marker will hide it
    function createMarker(latlng, event){
      var marker = new GMarker(latlng);
      var html = "<strong>" + event.title + "</strong><br />" + event.address;
      GEvent.addListener(marker, "click", function(){
        map.openInfoWindowHtml(latlng, html);
      });
      return marker;
    }

    var bounds = new GLatLngBounds;
    for( var i = 0; i < events.length; i++ ){
      var latlng = new GLatLng( events[i].event.lat, events[i].event.lng );
      bounds.extend(latlng);
      map.addOverlay(createMarker(latlng, events[i].event));
    }
    map.setCenter(bounds.getCenter(), 13);
  }
}

function validate_contact_form(){
  var valid = true;
  $('contact-form').getInputs().each(function(input){
    valid = valid && (input.getValue().length > 0);
  });
  if( valid == false ){
    alert('Please fill in all the fields.');
  }else{
    $('contact-form').submit();
  }
}

function validate_order_form(){
  var valid = true;
  valid = valid && ($('order_name').getValue().length > 0);
  valid = valid && ($('order_email').getValue().length > 0);
  valid = valid && ($('order_phone_number').getValue().length > 0);
  valid = valid && ($('order_postal_address').getValue().length > 0);
  if(!valid){
    alert('You have missed some important information!\nPlease make sure to input your:\n- Name\n- Email Address\n- Phone Number\n- Postal Address');
  } else {
    $('order-form').submit();
  }
}


document.observe('dom:loaded', function() {
  when('notice', function(notice) {
    new Effect.Fade(notice, {delay: 5});
    }
  );

  when('error', function(error) {
    new Effect.Fade(error, {delay: 5});
    }
  );

  when('map', function(map){
    initialize_maps();
  });

});
// When object is available, do function fn.
function when(obj, fn) {
  if (Object.isString(obj)) obj = /^[\w-]+$/.test(obj) ? $(obj) : $(document.body).down(obj);
  if (Object.isArray(obj) && !obj.length) return;
  if (obj) fn(obj);
}
