// -- Javascript pertaining only to the front page


// image rotation handler
function scrollImage() {
  ++imgIndex;

  if ( imgIndex >= frontPageImages.length )
    imgIndex = 0;

  var newLink = "<a target='_blank' href=\"" + frontPageImages[imgIndex][1] + "\">"
    + frontPageImages[imgIndex][1] + "</a>";

  // fade out the image and swap sources
  $("img#frontImage").fadeOut( 300, function() {
				 $("img#frontImage")[0].src = frontPageImages[imgIndex][0];
				 $("span#artistLink").html( newLink );
			       }
			     );
  $("img#frontImage").fadeIn( 300 );

}


// initializes animation
function startAni() {
  if ( typeof frontPageImages == 'undefined' )
    return;

  var numImages = frontPageImages.length;

  //  var ms = new Date().getTime();
  //  imgIndex = ms % numImages;

  // preload images
  var i = 0;
  for ( i; i < frontPageImages.length; ++i ) {
    var img = new Image();
    img.src = frontPageImages[i][0];
  }

  setInterval( scrollImage, 4000 );
}




// mailing list signup handler
function subscribeML( e ) {

  // validate email address
  var email = $("#email").val();
  if ( ! email.match( /^[a-z0-9\._\-\,]+\@(?:[a-z\-]+\.)+[a-z]+$/i ) ) {
     alert( "Please enter a valid email address (ex: 'you@domain.com')");
     return false;
  }

  // disable button and show the spinner
  $("#mlSub").attr( "disabled", "true" );
  $("#mlBusy").show();

  var errorTxt = "Error encountered during signup!<br>" +
                 "Please try again later or contact " +
                 "<a class='underline' href='mailto:alison@velvetgarden.net?subject=Mailing list signup error'>" +
                 "alison@velvetgarden.net</a>";

  // send the ML subscribe request
  $.ajax( {
      url: '/cgi-bin/vglist.pl',
      data: "user=" + email,
      type: 'POST',
      cache: false,
      timeout: 5000,

      error: function( req, status, e ) {
        $("#mlBusy").hide();
        $("#mlText").html( errorTxt );
        return true;
      },

      success: function( data ) {
        $("#mlBusy").hide();

        // does the response look successful?
        if ( ! data.match( /request successful/i ) ) {
          $("#mlText").html( errorTxt );
        } else {
          $("#mlText").html( "Mailing list subscription successful!" );
        }

        return true;
      }

	  } );

}



$(document).ready( 
  function() {

    // bind the mailing list handler 
    $("#mlSub").bind( "click", subscribeML );

    // and start the front page animation
    startAni();
  } );


