function initDatePickers( elem ) {
	var _fadeSpeed = 250;
	$('.calendar-holder', elem ).each(function(){
		var _calHolder = $(this);
		_calHolder.datepicker({
                        monthNames : [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                                       'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ],
			prevText: '&lt;',
			nextText: '&gt;',
			onChangeMonthYear: function(){
				setTimeout(function(){
					var _title = _calHolder.find('.ui-datepicker-header', elem);
					var _linkNext = _title.find('.ui-datepicker-next', elem);
					_title.append(_linkNext)
				}, 200)
			},
			onSelect:function(){
				setTimeout(function(){
					var _title = _calHolder.find('.ui-datepicker-header', elem);
					var _linkNext = _title.find('.ui-datepicker-next', elem);
					_title.append(_linkNext)
				}, 200)
			}
		});
	});
    $( '.rtg-date_picker input', elem ).datepicker({
			prevText: '&lt;',
			nextText: '&gt;',
			changeYear: true,
			yearRange: '1900:2010'
		});
	
}

function initPublicationType( elem ) {
    var field = $( '#publication_type-field', elem );
    
    if( field.length != 1 )
	return;

    var book = $( '#publication_type-0', elem );
	
    book.click( function () {
	$( '#journal_information-box', elem ).hide();
	$( '#book_information-box', elem).show();
    } );
    
    if( book[0].checked ) {
	book.click();
    }
	
    var journal = $( '#publication_type-1', elem );

    journal.click( function () {
	$( '#book_information-box', elem ).hide();
	$( '#journal_information-box', elem ).show();
    } );

    if( journal[0].checked ) {
	journal.click();
    }

    if( !journal[0].checked && !book[0].checked ) {
	book.click();
    }
    
    return;
} // initPublicationType

function initLoanType( elem ) {
    var field = $( '#loan_type-field', elem );
    
    if( field.length != 1 )
	return;

    var book = $( '#loan_type-0', elem );
	
    book.click( function () {
	$( '#article_information-box', elem ).hide();
	$( '#book_information-box', elem ).show();
    } );
    
    if( book[0].checked ) {
	book.click();
    }
	
    var article = $( '#loan_type-1', elem );

    article.click( function () {
	$( '#book_information-box', elem ).hide();
	$( '#article_information-box', elem ).show();
    } );

    if( article[0].checked ) {
	article.click();
    }

    if( !book[0].checked && !article[0].checked ) {
	book.click();
    }
    
    return;
} // initLoanType

function initSearchBox( elem ) {
   
/* search box handling */
	$('#header input#sq', elem ).focus( function() {
			if ( $(this).val() == '' ) {
				$(this).addClass('blackText');
			}
		}
	);
	$('#header input#sq', elem ).blur( function() {
			if ( $(this).val() == '' ) {
				$(this).removeClass('blackText');
			}
			else {

			}
		}
	);
}

function initDonationForm( elem ) {
    // Check for donation form
    var payType = $( '#so_payment_type_keyword-field', elem );
    if( payType.length != 1 )
	return;

    // Setup pay types
    var ccPayType     = $( '#so_payment_type_keyword-0', elem );
    var pledgePayType = $( '#so_payment_type_keyword-1', elem );
	
    ccPayType.click( function () {
	$( '#bill_to-box', elem).show();
    } );
    if( ccPayType[0].checked ) {
	ccPayType.click();
    }

    pledgePayType.click( function () {
	$( '#bill_to-box', elem).hide();
    } );
    if( pledgePayType[0].checked ) {
	pledgePayType.click();
    }

    // Default to pay in full
    if( !ccPayType[0].checked && !pledgePayType[0].checked ) {
	ccPayType.click();
    }

    // Setup dedicate
    var dedicateFlag = $( '#honor_flag-0', elem );

    var toggleHonoreeInfo = function () {
	if( this.checked )
	    $( '#honoree-set' ).show();
	else
	    $( '#honoree-set' ).hide();
    };
    
    dedicateFlag.click( toggleHonoreeInfo );

    toggleHonoreeInfo.call( dedicateFlag[0] );
    
    return;
} // initDonationForm

function initEventRegistrationForm( elem )
{
    $( '.rtg-commerce', elem ).simpleECommerce({
	onTotalChange : function (total) {
	    if( total > 0 ) {
		$( '#bill_to-box', elem ).show();
	    }
	    else {
		$( '#bill_to-box', elem ).hide();
	    }
	}
    });
    
} // initEventRegistrationForm


// Content swipe animation for landing pages
// TODO move this into a jquery ui widget, or at least a separate js

function initSwipeAnimation( elem ) {

	var is_animating = false;
	var swipe_links = $( '.swipe-link', elem );
	var swipe_links_by_url = {};

	// Build the complete list of links eligible for swipe animation.

	$.each( swipe_links, function() {
	    var uri = new $.uri( $(this).attr('href') );
	    swipe_links_by_url[uri.href] = this;
	});

	// Should we skip the animation altogether?
	//
	//   true  : yes, let the browser follow the link normally
	//   false : yes, and ignore the click altogether
	//   null  : no, proceed with animation

	var skipAnimation = function( uri1, uri2 ) {

	    if (is_animating)
		return false;

	    // Can't animate in violation of same original policy, since ajax is used.

	    if (uri1.origin != uri2.origin)
		return true;

	    // Can only animate between links if both are designated as swipe links.

	    if (!swipe_links_by_url[uri1.href] || !swipe_links_by_url[uri2.href])
		return true;

	    // Don't animate if new link is the same as the current one.

	    if (uri1.href == uri2.href)
		return false;

	    return null;
	};

	// React to fragment-changing history events that should kick off the animation.
	// This code is triggered by:
	//
	//    * clicking on an animatable link
	//    * clicking back button after a swipe animation completes
	//    * clicking forward button after a back button animation completes
	//    * typing an animatable link into the address bar hash directly

	$( window ).bind( 'history historyadd', function( e, url2, url1 ) {

	    url1 = new $.uri( url1 );
	    url2 = new $.uri( url2 );

	    if ( ( rc = skipAnimation( url1, url2 ) ) != null )
		return rc;

	    // Direction of swipe is determined by relative position of links on the page.

	    var link1 = $( swipe_links_by_url[url1.href] );
	    var link2 = $( swipe_links_by_url[url2.href] );
	    var direction = ( link1.offset().left < link2.offset().left ) ? -1 : 1;

	    is_animating = true;

	    runSwipeAnimation( elem, url2.href, {

		direction: direction,

		before: function() {
		    $( '#content', elem ).supersleight({shim: '/images/x.gif'});
		    if ( $( '#content', elem ).hasClass('homepage') ) {
			prepareTransition(elem);
		    }
		},

		after: function() {
		    initContentControls( '.swipe-holder .swipe1', elem );
		    is_animating = false;
		}
	    });
	
	    return false;
	});

	// Check for animatable link. If so, set browser hash to it.
	// Wait for jquery.history.js to notice the address bar change.

	swipe_links.click( function() {

	    var url1 = new $.uri( $.history.getCurrent() );
	    var url2 = new $.uri( $(this).attr('href') );

	    if ( ( rc = skipAnimation( url1, url2 ) ) != null )
		return rc;

	    $.history.add( url2.pathname + url2.search + url2.hash );

	    return false;
	});
}


function runSwipeAnimation( elem, url, options ) {

	var LEFT_TO_RIGHT = 1, RIGHT_TO_LEFT = -1;

	var defaults = {
	    direction: RIGHT_TO_LEFT,
	    before: function() {},
	    after: function() {}
	};

	var opts = $.extend( true, defaults, options );
	
	$.ajax({

	    url: url+'?ajax=1',
	    type: 'get',
	    dataType: 'html',
	    success: function (html, textStatus) {

		opts.before();
    
		var swipe1 = $( '.swipe-holder .swipe1', elem );
		var swipe2 = $( '.swipe-holder .swipe2', elem );

		// Base initial and final animation positions on current content.

		var p = swipe1.position();
		var x = p.left;
		var y = p.top;
		var cx = swipe1.width();
		var cy = swipe1.height();

		// Insert new content from ajax. Position off to the side of the old content.

		swipe2.hide();
		swipe2.html( html );
		swipe2.css({
		    position : 'absolute',
		    top      : y      +'px',
		    left     : (x-opts.direction*cx) +'px',
		    width    : cx     +'px'
		}).show();

		var animateCount = 0;
		var resetAnimation = function() {

		    // Wait for both animations to finish

		    if (++animateCount < 2) return;

		    // Exchange the swipe divs, so they're ready for next time.

		    swipe2.css({position: 'relative', top: '', left: '' }); // Clear css props
		    swipe1.html('');
		    swipe1.css( { width: '0px' } ); // Prevent horizontal scrollbar in safari
		    swipe1.removeClass('swipe1').addClass('swipe2');
		    swipe2.removeClass('swipe2').addClass('swipe1');

		    opts.after();
		};

		// Swipe the old content off.  Swipe the new content in.

		swipe1.animate({ left: (opts.direction*cx)+'px' }, 1000, 'swing', resetAnimation);
		swipe2.animate({ left: '0px' }, 1000, 'swing', resetAnimation);
	    }
	});
}

function initScrollPane( elem ) {
	$('.scroll-pane', elem ).jScrollPane( {showArrows:true, scrollbarOnLeft:true } );
	
	if ( $('#content.research .scroll-pane #r-content').height() < 296 ) {
		$('#content.research .scroll-pane').addClass("small");
	}	
}

function initInternational( elem ) {
    $( '.rtg-intl_address', elem ).rubyInternational();
}

function initContentControls( elem ) {
	$('a.lightbox').lightBox();

	$('body').supersleight({shim: '/images/x.gif'});

	if ( $('#content', elem).hasClass('homepage') ) {

		$('.homepage .swipe-holder', elem).addClass("overflowing");

		$('.promo div.art div a,.promo div.art div img').unbind();

		handleFocus("item-4", elem);


		$("#slot-1-image-content", elem).hover(function(){
				$("#slot-1-image-content div.thumbs", elem).stop().animate({
					right: 218
				}, 500);
			}, function(){
				$("#slot-1-image-content div.thumbs", elem).stop().animate({
					right: 0
				}, 500);
		});

		$("#h-slider", elem).easySlider({
			auto: true,
			speed: 1750,
			pause: 6000,
			controlsShow: false,
			continuous: true 
		});
	}

	/* Library */
	$('.library-holder', elem).supersleight({shim: '/images/x.gif'});
	
	$(".library-holder .images .left", elem).hover(function(){
			$(".library-holder .images .left img.map", elem).stop().animate({
				right: 716
			}, 700 );
		}, function(){
			$(".library-holder .images .left img.map", elem).stop().animate({
				right: 0
			}, 700);
	});
	
	$("#l-slider", elem).easySlider({
		auto: true,
		speed: 1500,
		pause: 5000,
		controlsShow: false,
		continuous: true 
	});
	/* End Library */

    initDatePickers( elem );
    initPublicationType( elem );
    initLoanType( elem );
    initScrollPane( elem );
    initInternational( elem );
    initDonationForm( elem );
    initEventRegistrationForm( elem );

    /* Forms - Add required asterisk via JS, because CSS :after no good */
    $( '.rtg-layout .rtg-widget.required.rtg-cvv2 .rtg-label label', elem).each(function(i,e){
        $(e).after("<span class='info-text' title='The verification code is a 3 or 4 digit code embossed or imprinted on the signature panel on the reverse side of Visa, MasterCard and Discover cards and on the front of American Express cards. This code is used as an extra security measure to ensure that you have access and/or physical possession of the credit card itself.' alt='The verification code is a 3 or 4 digit code embossed or imprinted on the signature panel on the reverse side of Visa, MasterCard and Discover cards and on the front of American Express cards. This code is used as an extra security measure to ensure that you have access and/or physical possession of the credit card itself.'>&nbsp;What's this?</span>");
    });
    $( '.rtg-layout .rtg-widget.required .rtg-label label', elem ).after( '*' );

	/* Gallery subsection */
	/* Note: keep this after the initScrollPane */
	$("#g-scroller-container", elem).hide();

	$('a#sub-top-link', elem).bind("click", function(e){
		$("#g-scroller-container", elem).slideToggle(450);
		return false;
	});

	$("#gallery-sub-scroller", elem).smoothDivScroll(
		{
		 autoScroll: "always",
		 autoScrollDirection: "endlessloop",
		 pauseAutoScroll: "mouseover"
		}
	 );
    
	$('.scroller-info', elem).bind("mouseenter.scrollinfo", function(){
		$('.wysiwyg', this).slideDown(200);
	});

	$('.scroller-info', elem).bind("mouseleave.scrollinfo", function(){
		$('.wysiwyg', this).slideUp(200);
	});

    //** rt#9879
    //** after the scroller image leaves the screen, it's deleted, the new one 
    //** doesn't have the events like mouseenter for scroller info
    $("#scroll-container").mouseenter(function(){
    	$('.scroller-info', elem).unbind("mouseenter.scrollinfo");
    	$('.scroller-info', elem).unbind("mouseleave.scrollinfo");
    	$('.scroller-info', elem).bind("mouseenter.scrollinfo", function(){
	    	$('.wysiwyg', this).slideDown(200);
    	});

	    $('.scroller-info', elem).bind("mouseleave.scrollinfo", function(){
		    $('.wysiwyg', this).slideUp(200);
    	});
        
    });

	/* End Gallery subsection */
}

$(document).ready(function() {

	initContentControls( this );
	initSwipeAnimation( this );
	initSearchBox( this );
	
	$('a.nyroModal, a.linked-asset-type-image', this).nyroModal({
		width: 800,
		height: 600,
		windowResize: false,
		resizable: false,
		autoSizable: false,
		closeButton: '<a href="#" class="nyroModalClose" id="closeBut" title="close">Close</a>'
	});

    /* With flash wmode set to opaque, it looks like we no longer need the code below
       2/25/10 - please remove this code if time has past and no bugs encountered
	$.fn.nyroModal.settings.hideLoading = function(elts, settings, callback) {
		$('#flash-content, .wysiwyg, .standard-image').hide();
		$('#nyroModalFull object').css('visibility', 'visible');
		callback();
	}

	$.fn.nyroModal.settings.endRemove = function() { 
		$('#flash-content, .wysiwyg, .standard-image').show();
	};
     */
     
	  TopUp.addPresets({
	    ".top_up, .linked-asset-type-video, .linked-asset-type-flash": {
	      shaded: 1
	    }

	  });
	  
	  $('.linked-asset-type-video, .linked-asset-type-flash').bind( 'click keypress', function() {
			var assetClasses = $(this).attr('class');
			var assetWidth = assetClasses.match(/linked-asset-width-(\d+)/);
			var assetHeight = assetClasses.match(/linked-asset-height-(\d+)/);

			 TopUp.addPresets({
				".linked-asset-type-video": {
					width: assetWidth[1],
					height: assetHeight[1],
					shaded: 1
				},
				".linked-asset-type-flash": {
					width: assetWidth[1],
					height: assetHeight[1],
					shaded: 1
				}
			});
		});
		$('#address_match_flag-0').click(function () {
            address_matcher(this);
        });
});


function address_matcher(elem){
    if(elem.checked){        
        
        address_matcher_helper('first_name');
        address_matcher_helper('last_name');
        address_matcher_helper('address\\.address_line_1');
        address_matcher_helper('address\\.address_line_2');
        address_matcher_helper('address\\.city');
        address_matcher_helper('address\\.other_state');
        address_matcher_helper('address\\.postal_code');
        
        $( '#guest-info select' ).each( function () {                    // loop through each guest info dropdown
        //console.log( 'Working with : ' + this.name );
	    var name = 'bill_to_' + this.name;                              // figure out name to the bill-to equivalent
	    $( '#bill_to select[name="'+name+'"]' ).val( $( this ).val() ); // set bill-to value equal to guest value
        });

        // Update the visible state
        $( '#bill_to .rtg-intl_address' ).rubyInternational( 'refresh' );

        return;

       
        
    }
}

function address_matcher_helper(field){
    $('#bill_to_'+ field).val($('#'+field).val());
}


