///
// Load'em Up
$(document).ready(function($) {
  // Hide the address boxes onload.
  $(".address").hide();
  
  textboxes = $("input:text");

  if ($.browser.mozilla) {
     $(textboxes).keypress(checkForEnter);
  } else {
     $(textboxes).keydown(checkForEnter);
  }  
  
  // Toggle the class from anywhere on the row.
  $('a.help').toggle( 
    function () {
      var id = $(this).attr('id');
      $('#address-' + id).show();
    },
    function () {
      var id = $(this).attr('id');
      $('#address-' + id).hide();
    }
  );
  
  // Clear and close the contact form from the cancel link.
  $('#cancel').click(function() {
    document.forms['contactForm'].reset();
    $('.form-error').remove();
    $('#contact').data("state", 0);
    $("#contact").animate({"height": "toggle"}, { duration: 600 });
    $('#contact-switch').html('<img src="../img/icons/16x16-mail.png" />&nbsp;Contact Instructor');
  });
  
  // Disable the contact button during form submission.
  $('button#submit').click(function(){
    $('#cancel').hide();
    $('.positive').hide();
    $('.disabled').show();
    $('.disabled').attr('disabled', 'disabled'); 
  });
  
  
  $(window).bind("keypress", function(e) {
   if (e.keyCode == 34) return false;
  });
  
  // Hide the contact form on load.
  $("#contact").hide();
  $("#contact-thankyou").hide();
  
  // Toggle the contact instructor button.
  $('#contact-switch').click(function() {
    
    $("#contact-thankyou").hide();
    
    if ($('#contact').data("state") != 1 ) {
      $('#contact').data("state", 1);
      $("#contact").animate({"height": "toggle"}, { duration: 600 });
      $('#contact-switch').html('<img src="../img/icons/16x16-mail.png" />&nbsp;Hide Contact Form');
    } else {
      $('#contact').data("state", 0);
      $("#contact").animate({"height": "toggle"}, { duration: 600 });
      $('#contact-switch').html('<img src="../img/icons/16x16-mail.png" />&nbsp;Contact Instructor');
    }
  }
  );
  
  // Toggle the class details row.
  $('.detail-switch').click(function() {
      var linkId = $(this).attr('id').replace("ds-","");
      
      $('.view-detail').hide(600);
      $('.detail-switch-link').html('View Details +');
      if ($('#ds-' + linkId).data("state") != 1 ) {
        $("#class-detail-" + linkId).animate({"height": "toggle"}, { duration: 600 });
        showMap(linkId);
        $('#ds-' + linkId).data("state", 1);
        $('#link-' + linkId).html('Close Details &#8722;');
      } else {
        $('#ds-' + linkId).data("state", 0);
      }
    }
  );
  
  // Regresh the capctha image with a nice spinner.
  $('#refresh-captcha').click( function () {
    $('#refresh-captcha').html('<img src="/img/loaders/spinner-transparent.gif" width="16" height="16" />');
    $('#captcha').attr('src', '/contacts/securimage/' + Math.random());
    setTimeout( " $('#refresh-captcha').html('Refresh'); " , 1000);
  });
  
  // Validate the contact form.
  $('#submit').click( function () {
    $('.form-error').remove();
    $.post('/contacts/validate_form', $("#ContactAddForm").serialize(), 
      function(data){
        if (data.success == 'success') {
          $("#contact").hide();
          $('#contact-thankyou').show(1, fadeThankYou);
          $('.disabled').hide();
          $('.positive').show();
          $('#cancel').show();
          document.forms['contactForm'].reset();
          $('#contact').data("state", 0);
          $('#contact-switch').html('<img src="../img/icons/16x16-mail.png" />&nbsp;Contact Instructor');
        } 
        else {
          $.each(data, function (i, val) {
            $("#Contact" + ucfirst(i)).after('<div class="form-error">' + val + '</div>');
            $('.disabled').hide();
            $('.positive').show();
            $('#cancel').show();
          });
        }
      }, 'json'
    );
  });
  
  // Setup the tooltip class.
  $('.qt').qtip({
    content: $(this).attr('alt'),
    style: 'cream' // Give it some style
  });
  
});

function checkForEnter(event) {
   if (event.keyCode == 13) {
      currentTextboxNumber = textboxes.index(this);

      if (textboxes[currentTextboxNumber + 1] != null) {
        nextTextbox = textboxes[currentTextboxNumber + 1];
        nextTextbox.select();
   }

      event.preventDefault();
      return false;
   }
}

function fadeThankYou() {
  setTimeout(function(){$('#contact-thankyou').fadeOut(2000);},5000);
}

// TODO: Move this into the application wide .js file.
////
// Capitalize the first letter of a string.
function ucfirst(str) {
  var firstLetter = str.substr(0, 1);
  return firstLetter.toUpperCase() + str.substr(1);
}

////
// Google Maps
function showMap(linkId) {
  var loc = $("#loc-"+linkId).attr("value");
  var lat = $("#lat-"+linkId).attr("value");
  var lng = $("#lng-"+linkId).attr("value");
  var myLatLng = new google.maps.LatLng(lat, lng);
  var myOptions = {
    zoom: 14,
    center: myLatLng,
    mapTypeControl: true,
    mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
    navigationControl: true,
    navigationControlOptions: {style: google.maps.NavigationControlStyle.DEFAULT},
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById("map-canvas-"+linkId), myOptions);
  
  var image = new google.maps.MarkerImage('/img/icons/25x40-pointer.png',
    // This marker is 20 pixels wide by 32 pixels tall.
    new google.maps.Size(25, 40),
    // The origin for this image is 0,0.
    new google.maps.Point(0,0),
    // The anchor for this image is the base of the flagpole at 0,32.
    new google.maps.Point(12, 40));
  var shadow = new google.maps.MarkerImage('/img/icons/47x40-pointer-shadow.png',
    // The shadow image is larger in the horizontal dimension
    // while the position and offset are the same as for the main image.
    new google.maps.Size(47, 40),
    new google.maps.Point(0,0),
    new google.maps.Point(17, 40));
    // Shapes define the clickable region of the icon.
    // The type defines an HTML &lt;area&gt; element 'poly' which
    // traces out a polygon as a series of X,Y points. The final
    // coordinate closes the poly by connecting to the first
    // coordinate.
  // var shape = {
  //     coord: [1, 1, 1, 20, 18, 20, 18 , 1],
  //     type: 'poly'
  // };
  // 
  var Marker = new google.maps.Marker({
       position: myLatLng,
       map: map,
       // shape: shape,
       icon: image,
       shadow: shadow,
       title: loc
  });
  
  var contentString = '<div id="content1">'+
      '<p>'+loc+'</p>'+
      '</div>';
  
  var infowindow = new google.maps.InfoWindow({
      content: contentString
  });
  
  google.maps.event.addListener(Marker, 'click', function() {
    infowindow.open(map, Marker);
  });

}