//*****Replace align attribute with class**************************************************//
function replaceAlign() {
  if (!document.getElementsByTagName('img')) return false;
  $('img[align="left"]').addClass('left').removeAttr('align');
  $('img[align="right"]').addClass('right').removeAttr('align');
  $('img[align="middle"]').addClass('middle').removeAttr('align');
}
//*****Replace target attribute with class**************************************************//
function replaceTarget() {
  if (!document.getElementsByTagName('a')) return false;
  $('a[target]').addClass('newwindow').removeAttr('target');
}
//*****The following function make it possible to have web standard popups**************************************************//
function strictNewWindow() {
  if (!document.getElementsByTagName('a')) return false;
  $('a.newwindow').click(function() {
    window.open($(this).attr('href'));
    return false;
  });
  $('p#viewTimeline a').click(function() {
    window.open($(this).attr('href'),'timeline','toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,width=680,height=360');
    return false;
  });
}
//*****Add swfobject flash call**************************************************//
function initializeFlash() {
  if (!document.getElementById('flash-content')) return false;
  var flashvars = {};
  var params = {wmode: 'transparent'};
  var attributes = {};
  attributes.id = "flash";
  swfobject.embedSWF("swf/bg-flash.swf", "flash", "808", "222", "8.0.0", "swf/expressInstall.swf", flashvars, params, attributes);
}
//*****jQuery clear value from july 21st 2009 comment on http://www.joesak.com/2008/11/19/a-jquery-function-to-auto-fill-input-fields-and-clear-them-on-click*****//
function clearDefaultValue() {
  $(':input').focus(function() {
    if($(this).val() == $(this).attr('title')) {
      $(this).val('');
    }
  }).blur(function() {
    if($(this).val() == '') {
      $(this).val($(this).attr('title'));
    }
  });
}
//*****View and hide image info for the home page film strip****************************************//
function toggleImageStripInfo() {
  wrapper = $('div.scrollerWrap');
  // The following goes through each .infoWrapper div and gets the height of each child img element and saves it in a variable called imageHeight.  We then assign the height of that .toggleInfo div within .infoWrapper to the value saved in imageHeight.  Now, the fly out .toggleInfo div will always have the same height as its associated image.
  $('.infoWrapper').each(function() {
    imageHeight = $(this).children('img').attr('height') - '3'; // I subtract 3 from this value because I have added a 3px border on the .toggleInfo div I am getting the height for so I have to account for those three pixels that will be added to the height.
    $(this).children('.toggleInfo').height(imageHeight);
  });
  $('#scroller .infoWrapper').css({  // Use css to add a pointer cursor on the .infoWrapper div (this is the div that will be clicked to show the slideout info).  We add this css via javascript because when js is disabled, we don't want there to be a pointer cursor suggesting you could click on this div, when it won't do anything without js enabled.
    'cursor' : 'pointer' 
  });
  $('.toggleInfo').addClass('hidden'); // First, add a class of hidden to all .toggleInfo divs, this will allow to differentiate between the opened div and all the others.
  $('.toggleInfo').animate({ 
    opacity : '0', // Set the initial opacity to zero, this allows us to create the fade in effect when clicked on. 
    width : '0' // Set the initial width to zero, this allows us to create the slide out effect when clicked on.  In our css, we have this div positioned absolutely to the right.  That helps create the effect of the div sliding out to the left when clicked on.
  });
  $('.infoWrapper').click(function() {
    wrapper.unbind('mousemove');
    //the following code check to see if you are at the first or last image and moves the scroller to the top or bottom accordingly to view the entire image on click
    var index = $('.infoWrapper').index(this); //get the position of the div clicked
    if (index == 0) {
      $('.scrollerWrap').scrollTop(0); //if you click the first one, move the div to the top
    }
    if (index == ($('.infoWrapper').size() - 1)) {
      var top = parseInt($('.scrollerWrap').css('height'));
      $('.scrollerWrap').scrollTop(top); //if you click the last one, move the div to the bottom
    }
    $('.toggleInfo').animate({
      opacity : '0',  // The first thing to do is go through and hide all .toggleInfo divs with opacity 0 and width 0.  This is the first step in ensuring that all other .toggleInfo divs will be hidden except for the one we clicked on.
      width : '0'
    });
    if($(this).children('.toggleInfo').hasClass('hidden')) {  // Next, check to see if the .toggleInfo div we are clicking on has a class of hidden.  If it does, this tells us that it isn't shown obviously, so we want to show it.  The following code is how we go about showing this specific div.
      $(this).children('.toggleInfo').animate({
        opacity : '1', // Give it an opacity of 1 (this fades in from our initial setting of 0).
        width : '260px' // Also, give it a width of 260px (this slides out from the right from our initial width of 0)  Note that this div must have an absolute postion of right: 0 (or soemthing) in order to create the effect of sliding out to the left. 
      });
      $('#scroller').animate({
        width : '429px'  // Also, give the container div, #scroller a wider width to accomodate for the wider .toggleInfo div.  If we didn't make this container div any wider, the part of the .toggleInfo div that is wider than its container will just get cut off.
      });      
      // The following helps manage only having one div open at a time.  This may seem unnecessary, but this process is very important in ensuring that each div has the appropriate class name so that we can target it appropriately.
      // We initially reset all .toggleInfo div classes to 'hidden'.  This corresponds to initially setting all .toggleInfo divs to zero opacity and width 0.  We are basically hiding everything, and then going through and altering the just the div we clicked on.  This way, only the div we click on will ever be displayed.  You can never have two .toggleInfo divs displayed.
      $('.toggleInfo').removeClass('visible'); // Check to see if any div has a class of visible (this means it's open) and remove that class.
      $('.toggleInfo').addClass('hidden'); // Give all .toggleInfo divs a class of 'hidden'.  So now, all .toggleInfo divs hav a class of hidden (so none are showing).  We essentially just reset everything to hidden and can now target and alter the exact div we clicked on.
      $(this).children('.toggleInfo').removeClass('hidden'); // However, we do want the one we clicked on to be showing, so we remove the class of hidden ONLY from the one we actually clicked on (this) that initally had a class of 'hidden'.
      $(this).children('.toggleInfo').addClass('visible'); // Then, add a class of visible, telling us that it is open and visible
    } else { // However, the following code runs if the div we clicked on has a class of visible.  This means that we clicked on an image to open its info, then clicked that same image again.  In this case, we want to hide all .toggleInfo divs, including this one.
      makeScrollable("div.scrollerWrap", "div.imageStrip", true);
      if($(this).children('.toggleInfo').hasClass('visible')) {
        $('.toggleInfo').animate({
          opacity : '0', // First, go through and hide all .toggleInfo divs by resetting the opacity to 0 and width to 0.  Even though we are targeting all .toggleInfo divs, we are really only affecting the one that is open because it will be the only div with a class of visible.
          width : '0'
        });
        $('#scroller').animate({  // So now, all .toggleInfo divs are hidden.  We want to reset the width of the container div, #scroller, so that it doesn't overlap the rest of the content on the page when no .toggleInfo divs are open.
          width : '158px'
        });
        // Finally, in order to be able to reshow this .toggleInfo div if we clicked on it again, we need to remove the class of visible and add a class of hidden since only divs with a class of hidden can be shown.
        $(this).children('.toggleInfo').removeClass('visible');
        $(this).children('.toggleInfo').addClass('hidden');
      }
    }
  });
}
//********************************schedule/roster tab switcher*********************************//
function sportTabSwitch() {
  if ($('ul.tabs').length != 1) return false;
  $('div.tabWrap').each(function (i) {
    $(this).hide();
  });
  $('ul.tabs li a').each(function (i) {
    $(this).attr('id','callTab' + i);
  });
  if ($('body.athletics').length > 0) {
    $('ul.tabs').addClass('selected0');
    $('div.tabWrap:eq(0)').show();
  } else {
    $('div.tabWrap:eq(4)').show();
  }
	$('ul.tabs li a').click(function(){
    if ($('body.athletics').length > 0) {
      $(this).parent().parent().removeClass('selected0');
      $(this).parent().parent().removeClass('selected1');
      $(this).parent().parent().parent().children().children('div').each(function (i) {
        $(this).hide();
      });
    } else {
      $(this).parent().parent().children('li').children('a').each(function (i) {
        $(this).removeClass('selected');
      });  
      $(this).parent().parent().parent().children('div.tabWrap').each(function (i) {
        $(this).hide();
      });
      $(this).addClass('selected');    
    }
    var position = $(this).attr('id').substr(7,2) - 0;
    $(this).parent().parent().addClass('selected'+position+'');
	  $('div.tabWrap:eq('+position+')').show();
	  return false;
	});
}
//*****Mask function from http://digitalbush.com/projects/masked-input-plugin**************************************************//
function mask() {
  if ($('#formValidate').length < 1) return false;
  $('.zip').mask('99999');
  $('.phone').mask('(999) 999-9999');
  $('.date').mask('99/99/9999');
  $('.ssn').mask('999-99-9999');
  $('.year').mask('9999');
}
//*****jQuery form validation from http://bassistance.de/jquery-plugins/jquery-plugin-validation/**************************************************//
function validate() {
  if ($('#formValidate').length < 1) return false;
  $('#formValidate').validate({
    highlight: function(element, errorClass) {//add the error class to the label and element
		  if ($(element).is(':radio')) {
		    $(element).parent().prev().addClass(errorClass);
		  } else {
        $(element).addClass(errorClass);
        $(element.form).find("label[for=" + element.id + "]").addClass(errorClass);
      }
    },
    unhighlight: function(element, errorClass) {//remove error class from label and element once valid
		  if ($(element).is(':radio')) {
		    $(element).parent().prev().removeClass(errorClass);
		    $(element).parent().prev().addClass('valid');
		  } else {
        $(element).removeClass(errorClass);
        $(element.form).find("label[for=" + element.id + "]").removeClass(errorClass);
      }
    },
    success: function(label) {//add the green box and checkmark for valid fields
		  if (label.prev().is(':checkbox')) {
        label.next().addClass("valid");
        label.addClass("valid").text("✓");
      } else {
        label.prev().addClass("valid");
        label.addClass("valid").text("✓");
      }
    },
    onfocusout: false,
    onkeyup: false,
    onclick: false,
    //do not use the title attribute as the error message
    ignoreTitle: true,
    //make the error text wrapped in a span
    errorElement: 'span',
    //javascript instead of class specified rules
    rules: {
      'rdoLiveWith[]': 'required'
    },
    //messages other than the default 'X'
    messages: {
		  'rdoLiveWith[]': '<br />X Please select one of the options below<br />'
		},
    // the errorPlacement has to take the h2 of radio buttons into account
		errorPlacement: function(error, element) {
		  if ( element.is(':radio') )
		    error.appendTo( element.parent().prev() );
		  else
				error.insertAfter(element);
		}
  });
}
//*****jQuery clear value from july 21st 2009 comment on http://www.joesak.com/2008/11/19/a-jquery-function-to-auto-fill-input-fields-and-clear-them-on-click*****//
function clearDefaultValue() {
  if ($('input').length < 1) return false;
  $(':input').focus(function() {
    if($(this).val() == $(this).attr('title')) {
      $(this).val('');
    }
  }).blur(function() {
    if($(this).val() == '') {
      $(this).val($(this).attr('title'));
    }
  });
  $('#btnNext').click(function() {
	  $(':input').each(function (i) {
      if($(this).val() == $(this).attr('title')) {
        $(this).val('');
      }
    });
  });
}
function populateDefaultValues(){
  $(':input').each(function(){
    if($(this).val() == ''){
      $(this).val($(this).attr('title'));      
    }
  });
}
//*****misc form functions*****//
function formStuff() {
  if ($('#formValidate').length < 1) return false;
  function cloneTableRow() {
    $('.addALine').click(function() {
      //the row to clone
      var $row = $(this).closest('tr').prev();
      //the cloned row
      var $clonedRow = $row.clone();
      //the amount of rows to append to end of the id and name
      var index = $(this).closest('tr').siblings().length + 1;
      $clonedRow.find('*').andSelf().filter('[id]').each( function(){
        id = this.id.slice(0,this.id.length - 1);
        this.id = id + index;
      });
      $clonedRow.find('*').andSelf().filter('[name]').each( function(){
        name = this.name.slice(0,this.name.length - 1);
        this.name = name + index;
      });
      $clonedRow.find('*').andSelf().filter('[value]').each( function(){
        this.value = '';
      });
      $clonedRow.find('span').remove();
      $clonedRow.find('input').removeAttr('class');
      $clonedRow.find('input').removeAttr('checked');
      $clonedRow.find('select').removeAttr('class');
      $clonedRow.insertAfter($row);
      $clonedRow.find('*').andSelf().filter('input').eq(0).focus();
      return false;
    });
  }
  cloneTableRow();
}
//*****misc verify functions*****//
function verify() {
  $('.formVerify li:odd').addClass('odd');
  $('.formVerify li:even').addClass('even');
}
//*****Load all functions**************************************************//
$(document).ready(function(){
  replaceAlign();
  replaceTarget();
  strictNewWindow();
  initializeFlash();
  clearDefaultValue();
  toggleImageStripInfo();
  sportTabSwitch();
  mask();
  validate();
  clearDefaultValue();
  populateDefaultValues();
  formStuff();
  verify();
});