﻿/*@cc_on
( function() {
	var html = document.getElementsByTagName( 'HTML' )[0];
	html.className += ' msie';
} )();
@*/

(function($) {
	$.extend( $.ajaxSettings, { traditional: true } );
	if( !''.trim ) String.prototype.trim = function() { return this.replace( /(^\s+|\s+$)/g, '' ); };
	$.create =
		function( tagName, doc ) {
			doc = doc || document;
			if( doc.createElementNS ) return $( doc.createElementNS( 'http://www.w3.org/1999/xhtml', tagName ) );
			else return $( doc.createElement( tagName ) );
		};

	window.Current = {
		BasePath: '/calculators/products',
		Website: {
			ID: 'US',
			DisplayName: 'US and Canada',
			Language: 'en',
			SearchWatermark: 'Enter Keywords',
			DateFormat: 'MM/DD/YYYY',
			TimeFormat: '12'
		}
	};

	$.datepicker.setDefaults( $.extend( {}, $.datepicker.regional[ Current.Website.Language ] || {}, {
		navigationAsDateFormat: true,
		showOn: 'both',
		buttonImage: '/calculators/products/images/calendar-icon.gif',
		buttonImageOnly: true,
		dateFormat: $.datepicker.W3C,
		changeMonth: true,
		changeYear: true
	} ) );

	$.fn.simulateClick = function() {
		return this.each( function() {
			var $this = $(this);
		
			if( $this.is( 'a[href]' ) ) {
				$.create('form')
				.attr( {
					target: $this.attr( 'target' ),
					method: 'GET',
					action: $this.attr( 'href' )
				} )
				.hide()
				.appendTo( 'body' )
				.submit()
				.remove();
			}
		} );
	};
	
	$.fn.jeCarousel = function( options ) {
		
		options = $.extend( {
			delay: 12000,
			slideTime: 1000,
			resumeAfterClick: false,
			clickToStart: false,
			enableHover: false
		}, options );

		return this.each( function() {
			var $this = $(this);

			var $carousel =
				$.create( 'div' )
				.addClass( 'jecarousel' )
				.css( {
					position: 'relative',
					overflow: 'hidden'
				} );

			var $frames =
				$this
				.children( 'li' );

			var totalWidth = 0;
			$frames.each( function() {
				var $li = $(this).css( { position: 'absolute', left: totalWidth + 'px' } );
				totalWidth += $li.outerWidth();
			} );
			var avgWidth = totalWidth / $frames.length;

			$carousel =
				$this
				.wrapAll(
					$carousel
					.width( avgWidth )
					.height( $this.height() )
				)
				.parent();
			
			$this
			.css( { position: 'absolute', left: 0 } )
			.width( totalWidth );

			$frames
			.addClass( 'jecarousel-slide' )
			.each( function( index, e ) {
				$(e).addClass( 'jecarousel-slide-' + ( index + 1 ) )
				.data( 'slideIndex', index );
			} );

			var $buttons =
				$.create( 'ul' )
				.addClass( 'jecarousel-buttons' );

			var interval;

			var delay = options.delay;

			var nextFrame = function () {
				var $currentButton = $buttons.children( 'li.selected' );
				var $nextButton;
				if( $currentButton.is( ':last-child' ) )
					$nextButton = $buttons.children( 'li ').first();
				else
					$nextButton = $currentButton.next( 'li' );

				$nextButton.triggerHandler( 'select' );
			};

			var timeout;
			if( $frames.length > 1 ) {
				for( var i = 0; i < $frames.length; i++ ) {

					var li =
						$.create( 'li' )
						.addClass( 'jecarousel-button jecarousel-button-' + ( i + 1 ) )
						.append( $.create( 'span' ).text( i + 1 ) )
						.data( 'frame', $frames.eq( i ) )
						.data( 'buttonIndex', i )
						.bind( 'select', function() {
							var $t = $(this);

							if( $t.hasClass( 'selected' ) )
								return;

							$t.data( 'transitioning', true ).data( 'frame' );
							$buttons.children( 'li.selected' ).data( 'frame' );

							if( $buttons.data( 'transitioning' ) ) {
								clearTimeout( timeout );
								timeout = setTimeout( function() {
									$t.triggerHandler( 'select' );
								}, 10 );
								return;
							}
							$buttons.data( 'transitioning', true );

							$buttons.children( 'li' ).removeClass( 'selected' );
							$t.addClass( 'selected' );
							$this.animate( { left: ( -avgWidth * $t.data( 'buttonIndex' ) ) + 'px' }, options.slideTime, function() {
								$buttons.data( 'transitioning', false );
							} );
						} )
						.css( {
							cursor: 'pointer'
						} )
						.click( function( e ) {
							e.stopImmediatePropagation();
							clearInterval( interval );
							$(this).triggerHandler( 'select' );
							if( options.resumeAfterClick ) interval = setInterval( nextFrame, delay );
						} );

					if( options.enableHover ) {
						li.mouseover( function () {
							clearInterval( interval );
							$(this).triggerHandler( 'select' );
						} )
						.mouseout( function () {
							clearInterval( interval );
							interval = setInterval( nextFrame, delay );
						} );
					}

					$buttons.append( li );
				}

				$buttons.children( 'li' ).first().addClass( 'selected' );

				$carousel.after( $buttons );

				if( !options.clickToStart ) {
					clearInterval( interval );
					interval = setInterval( nextFrame, delay );
				}
			}
		} );
	};

	$.fn.jeSlideshow = function( options ) {

		options = $.extend( {
			delay: 12000,
			fadeTime: 1000,
			resumeAfterClick: false,
			clickToStart: false,
			enableHover: false
		}, options );

		return this.each( function() {
			var $this = $(this);

			var $slideshow = $this.addClass( 'jeslideshow' );
			var $frames =
				$slideshow
				.children( 'li' )
				.addClass( 'jeslideshow-slide' )
				.each( function( index, e ) {
					$(e).addClass( 'jeslideshow-slide-' + ( index + 1 ) )
					.data( 'slideIndex', index );
				} );

			var $buttons =
				$.create( 'ul' )
				.addClass( 'jeslideshow-buttons' );

			var interval;

			var delay = options.delay;
			var fadeTime = options.fadeTime;

			var nextFrame = function () {
				var $currentButton = $buttons.children( 'li.selected' );
				var $nextButton;
				if( $currentButton.is( ':last-child' ) )
					$nextButton = $buttons.children( 'li ').first();
				else
					$nextButton = $currentButton.next( 'li' );

				$nextButton.triggerHandler( 'select' );
			};

			var timeout;
			if( $frames.length > 1 ) {
				for( var i = 0; i < $frames.length; i++ ) {

					var li =
						$.create( 'li' )
						.addClass( 'jeslideshow-button jeslideshow-button-' + ( i + 1 ) )
						.append( $.create( 'span' ).text( i + 1 ) )
						.data( 'frame', $frames.eq( i ) )
						.data( 'buttonIndex', i )
						.bind( 'select', function () {
							var $t = $(this);

							if( $t.hasClass( 'selected' ) )
								return;

							var $thisFrame = $t.data( 'transitioning', true ).data( 'frame' );
							var $selectedFrame = $buttons.children( 'li.selected' ).data( 'frame' );

							if( $buttons.data( 'transitioning' ) ) {
								clearTimeout( timeout );
								timeout = setTimeout( function() {
									$t.triggerHandler( 'select' );
								}, 10 );
								return;
							}
							$buttons.data( 'transitioning', true );

							$buttons.children( 'li' ).removeClass( 'selected' );
							$t.addClass( 'selected' );
							$selectedFrame.css( { display: 'block', 'z-index': 3 } );
							$thisFrame.css( { display: 'block', 'z-index': 2 } );

							$selectedFrame.fadeOut( fadeTime, function() {
								$thisFrame.css( { 'z-index': 3 } );
								$buttons.data( 'transitioning', false );
							} );
						} )
						.css( {
							cursor: 'pointer'
						} )
						.click( function( e ) {
							e.stopImmediatePropagation();
							clearInterval( interval );
							$(this).triggerHandler( 'select' );
							if( options.resumeAfterClick ) interval = setInterval( nextFrame, delay );
						} );
					if( options.enableHover ) {
						li.mouseover( function () {
							clearInterval( interval );
							$(this).triggerHandler( 'select' );
						} )
						.mouseout( function () {
							clearInterval( interval );
							interval = setInterval( nextFrame, delay );
						} );
					}

					$buttons.append( li );
				}

				$frames.css( { 'z-index': 2 } ).slice( 1 ).hide();
				$buttons.children( 'li' ).first().addClass( 'selected' );

				$slideshow.after($buttons);

				if( !options.clickToStart ) {
					clearInterval( interval );
					interval = setInterval( nextFrame, delay );
				}
			}
		} );
	};
	$.fn.popupWindow = function( instanceSettings ) {
		return this.each( function() {
			$(this).click( function() {
				$.fn.popupWindow.defaultSettings = {
					centerBrowser: false, // center window over browser window? Overrides top and left
					centerScreen: false, // center window over entire screen? Overrides top and left
					height: 500, // sets the height in pixels of the window.
					left: 0, // left position when the window appears.
					location: false, // determines whether the address bar is displayed
					menubar: false, // determines whether the menu bar is displayed
					resizable: false, // whether the window can be resized Can also be overloaded using resizable.
					scrollbars: false, // determines whether scrollbars appear on the window
					status: false, // whether a status line appears at the bottom of the window
					width: 500, // sets the width in pixels of the window
					windowName: null, // name of window set from the name attribute of the element that invokes the click
					windowUrl: null, // url used for the popup
					top: 0, // top position when the window appears
					toolbar: false // determines whether a toolbar (includes the forward and back buttons) is displayed
				};

				var settings = $.extend( {}, $.fn.popupWindow.defaultSettings, instanceSettings || {} );

				var windowFeatures =		
					'height=' + settings.height +
					',width=' + settings.width +
					',toolbar=' + ( settings.toolbar ? 1 : 0 ) +
					',scrollbars=' + ( settings.scrollbars ? 1 : 0 ) +
					',status=' + ( settings.status ? 1 : 0 ) +
					',resizable=' + ( settings.resizable ? 1 : 0 ) +
					',location=' + ( settings.location ? 1 : 0 ) +
					',menuBar=' + ( settings.menubar ? 1 : 0 );

				settings.windowName = settings.windowName || this.name;
				settings.windowUrl = settings.windowUrl || this.href;
				var centeredX, centeredY, w;

				if( settings.centerBrowser ) {
					if ($.browser.msie) {//hacked together for IE browsers
						centeredY = (window.screenTop - 120) + ((((document.documentElement.clientHeight + 120) / 2) - (settings.height / 2)));
						centeredX = window.screenLeft + ((((document.body.offsetWidth + 20) / 2) - (settings.width / 2)));
					} else {
						centeredY = window.screenY + (((window.outerHeight / 2) - (settings.height / 2)));
						centeredX = window.screenX + (((window.outerWidth / 2) - (settings.width / 2)));
					}
					w = window.open(settings.windowUrl, settings.windowName, windowFeatures + ',left=' + centeredX + ',top=' + centeredY );
				} else if (settings.centerScreen) {
					centeredY = (screen.height - settings.height) / 2;
					centeredX = (screen.width - settings.width) / 2;
					w = window.open( settings.windowUrl, settings.windowName, windowFeatures + ',left=' + centeredX + ',top=' + centeredY );
				} else {
					w = window.open( settings.windowUrl, settings.windowName, windowFeatures + ',left=' + settings.left + ',top=' + settings.top );
				}
				try {
					if( w ) w.focus();
				} catch( ex ) {}
				return false;
			} );
		} );
	};
	
} )( jQuery );

$(function() {
	window.$window = $( window );
	window.$body = $( 'body' );
	window.$form = $( '#aspnetForm' );
	var pageRequestManager = Sys.WebForms.PageRequestManager.getInstance();

	$window
	.bind( 'style', function() {
		$( 'body *' ).removeClass( 'first-child last-child' );
		$( 'tr, td' ).removeClass( 'odd even' );
		$( 'input' ).removeClass( 'button checkbox radio submit file text reset' );

		$( 'body :first-child' ).addClass( 'first-child' );
		$( 'body :last-child' ).addClass( 'last-child' );

		$( 'tr:nth-child(odd), li:nth-child(odd)' ).addClass( 'odd' );
		$( 'tr:nth-child(even), li:nth-child(even)' ).addClass( 'even' );

		$( 'input:button' ).addClass( 'button' );
		$( 'input:checkbox' ).addClass( 'checkbox' );
		$( 'input:radio' ).addClass( 'radio' );
		$( 'input:submit' ).addClass( 'submit' );
		$( 'input:file' ).addClass( 'file' );
		$( 'input:text' ).addClass( 'text' );
		$( 'input:reset' ).addClass( 'reset' );

		$( 'table' ).attr( { cellSpacing: 0, cellPadding: 0 } );

		$( '#navigation-primary > li, #related-sites, input:submit' )
		.each( function() {
			var t = $(this);
			var e = t.data( 'events' );
			if( e && e.hover ) return;
			t.hover(
				function() { t.addClass( 'hover' ); },
				function() { t.removeClass( 'hover' ); }
			);
		} );
	} );

	//fix navigation floating behind certain controls
	$( '#navigation-primary' )
	.hover(
		function() {
			if( $.browser.msie && parseFloat( $.browser.version ) <= 6 ) $( '#site-wrapper select,#site-wrapper iframe' ).css( { visibility: 'hidden' } );
		},
		function() {
			if( $.browser.msie && parseFloat( $.browser.version ) <= 6 ) $( '#site-wrapper select,#site-wrapper iframe' ).css( { visibility: 'visible' } );
		}
	);

	pageRequestManager.add_pageLoaded( function() {
		$window.triggerHandler( 'style' );
	} );

	$( '#site-search input:text' ).data( 'Watermark', Current.Website.SearchWatermark );
	$( ':text' )
	.filter( function() { return $(this).data( 'Watermark' ); } )
	.bind( 'WatermarkShow', function() { var $t = $(this); if( $t.val() === '' ) $t.val( $t.data( 'Watermark' ) ); })
	.bind( 'WatermarkHide', function() { var $t = $(this); if( $t.val() === $t.data( 'Watermark' ) ) $t.val( '' ); })
	.blur( function() { $(this).triggerHandler( 'WatermarkShow' ); } )
	.focus( function() { $(this).triggerHandler( 'WatermarkHide' ); } )
	.blur();

	$( 'form' )
	.submit( function() { $( ':text', this ).triggerHandler( 'WatermarkHide' ); } );

	window.closeLightbox = function() {
		var lightbox = $( '#lightbox' );
		
		var flash_id = lightbox.find( 'object' ).attr( 'id' );
		if( flash_id ) swfobject.removeSWF( flash_id );

		lightbox
		.fadeOut( 'slow' )
		.children( '#lightbox-inner' )
		.children()
		.detach();

		$.bbq.removeState( 'show' );
	};
	
	window.openLightbox = function( child ) {
		var $child = $( child );

		var lightbox = $( '#lightbox' );

		if( lightbox.length <= 0 ) {
			lightbox =
				$.create( 'div' )
				.attr( 'id', 'lightbox' )
				.click( function( e ) {
					e.stopImmediatePropagation();
					closeLightbox();
				} )
				.hide();
		}

		var flash_id = lightbox.find( 'object' ).attr( 'id' );
		if( flash_id ) swfobject.removeSWF( flash_id );

		lightbox
		.fadeOut( 'slow' )
		.children( '#lightbox-inner' )
		.children()
		.detach();

		lightbox
		.append(
			$.create( 'div' )
			.attr( 'id', 'lightbox-inner' )
			.append(
				$child
				.click( function( e ) {
					e.stopImmediatePropagation();
				} )
			)
		)
		.prependTo( 'body' );

		lightbox
		.fadeTo( 0, 1 )
		.children( '#lightbox-inner' )
		.css( 'margin-top', Math.floor( ( $( window ).height() - $child.show().height() ) * .5 ) + 'px' );

		lightbox
		.fadeIn( 'slow' );

		var swf = $child.data( 'swf' );
		if( swf ) {
			var oid = 'flash-' + swf.id + '-object';
			$child.append(
				$.create( 'div' )
				.attr( { id: oid } )
				.css( { width: swf.width + 'px', height: swf.height + 'px' } )
			);

			swfobject.embedSWF( swf.swf, oid, swf.width, swf.height, '10.0.0', '', swf.flashvars, { wmode: 'transparent', allowScriptAccess: 'always' }, {} );
		}
	};

	window.setLightboxFlashTrigger = function( swf, key ) {
		var e = $( document.getElementById( swf.id ) );
		if( !e.length ) {
			var id = 'flash-' + swf.id;
				
			e =
				$.create( 'div' )
				.attr( { id: id } )
				.css( { width: swf.width + 'px', height: swf.height + 'px', margin: '0 auto' } )
				.hide()
				.appendTo( $body );

			e.data( 'swf', swf );

			$window.bind( 'hashchange', ( function( swf, e, key ) { return function() {
				var show = key ? $.bbq.getState( key ) : $.param.fragment();
				if( show === swf.id ) {
					window.openLightbox( e );
				} else {
					if( e.closest( '#lightbox-inner' ).length ) {
						var lightbox = $( '#lightbox' );

						var flash_id = lightbox.find( 'object' ).attr( 'id' );
						if( flash_id ) swfobject.removeSWF( flash_id );

						lightbox
						.fadeOut( 'slow' )
						.children( '#lightbox-inner' )
						.children()
						.detach();
					}
				}
			}; }( swf, e, key ) ) );

			//e.detach().show();
		}
	};
	
	$window
	.resize( function() { 
		var lbi = $( '#lightbox-inner' );
		lbi.css( 'margin-top', Math.floor( ( $window.height() - lbi.height() ) * .5 ) + 'px' );
	} );

	var riseDuration = 500;
	var riseLow = 301;
	var riseHighOffset = 200;

	$( '.rise-panels > li' )
	.hover(
		function() {
			var $t = $(this);

			var riseMargin = $t.data( 'margin-left' );
			var riseHigh = $t.parent().height() - ( riseHighOffset + $t.height() );

			$t
			.stop( false )
			.animate( { top: riseHigh + 'px' }, riseDuration, 'easeOutBack', function() {
				if( !isNaN( riseMargin ) ) {
					$t.css( { marginLeft: ( riseMargin + 1 ) + 'px' } );
					$t.css( { marginLeft: riseMargin + 'px' } );
				}
			} );
		},
		function() {
			var $t = $(this);

			var riseMargin = $t.data( 'margin-left' );

			$t
			.stop( false )
			.animate( { top: riseLow + 'px' }, riseDuration, 'easeInOutCubic', function() {
				if( !isNaN( riseMargin ) ) {
					$t.css( { 'margin-left': ( riseMargin + 1 ) + 'px' } );
					$t.css( { 'margin-left': riseMargin + 'px' } );
				}
			} );
		}
	)
	.each( function() {
		var $t = $(this);
		$t.data( 'margin-left', parseFloat( /^(-?\d+)/.exec( $t.css( 'margin-left' ) )[ 1 ] ) );
		$t.css( { top: riseLow + 'px' } );
	} );
	
	$( 'body#site-home' ).each( function() {
		$( '.jeslideshow' ).jeSlideshow();
		$( '.jecarousel' ).jeCarousel();
		$( '#panels > li:has( a.more[ href ] )' )
		.css( { cursor: 'pointer' } )
		.click( function( e ) {
			e.preventDefault();
			$( 'a.more[ href ]', this ).simulateClick();
		} );
	} );

	$( 'body.nspired-learning-interior' ).each( function() {
		var contactTi = $( '#contact-ti' );
		var contactTiPanel = contactTi.children( 'div' ).fadeTo( 0, 0 );
		contactTi.find( '> p > a' ).toggle(
			function( e ) {
				e.preventDefault();
				contactTiPanel.fadeTo( 'slow', 1 );
			},
			function( e ) {
				e.preventDefault();
				contactTiPanel.fadeTo( 'slow', 0 );
			}
		);
	} );
	
	$( 'body#nspire-family-home' ).each( function() {
		$( '.rise-panels:eq(0)' ).append(
			$.create( 'li' )
			.attr( { id: 'flash-placeholder-li' } )
			.append(
				$.create( 'div' )
				.attr( { id: 'flash-placeholder-object' } )
			)
		);
		if( $( '#flash-placeholder-object' ).length > 0 ) swfobject.embedSWF( 'http://education.ti.com/flash/products/nspire/US-home.swf', 'flash-placeholder-object', '960', '330', '10.0.0', '', { country: 'US' }, { wmode: 'transparent', allowScriptAccess: 'always' }, { country: 'US' } );
	} );

	$( 'body.product-family-interior' ).each( function() {
		$( '#hero-copy-student' ).live( 'mouseover', function() { $( '.section-wrapper' ).removeClass( 'teacher' ).addClass( 'student' ); } );
		$( '#hero-copy-teacher' ).live( 'mouseover', function() { $( '.section-wrapper' ).removeClass( 'student' ).addClass( 'teacher' ); } );

		var fn_enlarge =
			function() {
				$( 'a.enlarge:not( ~ img.popup-enlarged )' )
				.each( function() {
					var $t = $(this);

					var popup =
						$.create( 'div' )
						.addClass( 'popup-enlarged' )
						.hide()
						.mouseout( function() {
							$(this).fadeOut( 'slow' );
						} )
						.append(
							$.create( 'img' )
							.attr( { src: $t.attr( 'href' ), alt: '' } )
						)
						.insertAfter( $t );

					$t
					.click( function( e ) {
						e.preventDefault();

						popup.show();
					} );
				} );
			};
		$( 'li:has(>.popup-enlarged)' )
		.live( 'mouseleave', function() { $( this ).children( '.popup-enlarged' ).fadeOut( 'slow' ); } );
		fn_enlarge();

		var allSlides = [ { name: 'cx-handhelds' }, { name: 'software' }, { name: 'navigator' }, { name: 'data-collection' } ];
		var offset = 0, i = 0;
		$.each( allSlides, function() {
			if( $.browser.msie ) {
				var version = parseFloat( $.browser.version );
				if( version >= 7 && version < 8 ) return;
			}
			return; // temporarily disabled

			var currentSlide = this;
			var onload = function() {
				var currentSlide, i;
				for( i = 0; i < allSlides.length; i++ ) {
					currentSlide = allSlides[ i ];
					if( !currentSlide.div || !currentSlide.div.length ) return;
				}

				var $navLIs = $();
				var sortedSlides = [];
				for( i = 0; i < allSlides.length; i++ ) {
					sortedSlides[ i ] = allSlides[ ( i + offset ) % allSlides.length ];
					currentSlide = sortedSlides[ i ];
					currentSlide.index = i;
					$navLIs = $navLIs.add( currentSlide.navLI );
				}
				allSlides = sortedSlides;
				allSlides[ 0 ].div.addClass( 'selected' );
				$window.triggerHandler( 'style' );

				fn_enlarge();

				var delay = 8000, fadeTime = 1000, timeout;
				for( i = 0; i < allSlides.length; i++ ) {
					currentSlide = allSlides[ i ];
					currentSlide.bringToFront = ( function( i, currentSlide ) { return function( advance ) {
						if( allSlides.transitioning ) return;
						allSlides.transitioning = true;
						if( timeout ) clearTimeout( timeout );
						timeout = null;

						var nextSlide = allSlides[ ( i + 1 ) % allSlides.length ];
						if( !currentSlide.navLI.hasClass( 'selected' ) ) {
							var previousSlide = $navLIs.filter( '.selected' ).data( 'slide' );
							currentSlide.navLI.addClass( 'selected' ).removeClass( 'deselected' );
							if( previousSlide && previousSlide.href != currentSlide.href ) {
								previousSlide.navLI.addClass( 'deselected' ).removeClass( 'selected' );

								currentSlide.div.stop( true ).fadeIn( fadeTime, function() {
									previousSlide.div.css( { opacity: 0 } );
									currentSlide.div.css( { opacity: 1 } );
								} );
								previousSlide.div.stop( true ).fadeOut( fadeTime );
							}
						}

						if( advance ) timeout = setTimeout( function() { nextSlide.bringToFront(); }, delay );
						allSlides.transitioning = false;
					}; } )( i, currentSlide );
				}  

				allSlides[ 0 ].bringToFront( false );

				allSlides.loaded = true;
			};

			var fn = ( function( currentSlide ) { return function( data ) {
				currentSlide.div = $( 'div.section-content', data ).appendTo( 'div.section-wrapper' ).hide();
				if( currentSlide.div.length ) onload(); 
			}; } )( currentSlide );

			currentSlide.navLI =
				$( 'li#nspire-nav-' + currentSlide.name )
				.data( 'slide', currentSlide );

			var a =
				currentSlide.navLI
				.children( 'a' )
				.click( function( e ) {
					if( !allSlides.loaded ) return;
					e.preventDefault();
					$(this).data( 'slide' ).bringToFront( false );
				} )
				.data( 'slide', currentSlide );

			currentSlide.href = a.attr( 'href' );
			currentSlide.div = $( document.getElementById( 'section-content-' + currentSlide.name ) );
			if( currentSlide.div.length ) {
				offset = i;
				onload();
			} else $.get( currentSlide.href, fn );
			i++;
		} );
	} );

	$( 'body.product-navigator' ).each( function() {
		$( '.jecarousel' ).jeCarousel();
		$( '.jeslideshow' ).jeSlideshow();
	} );

	$( 'body#product-navigator-home' ).each( function() {
		window.setLightboxFlashTrigger( { id: 'video', width: 900, height: 530, swf: 'http://education.ti.com/flash/products/nspire/US-navigator-feature.swf', flashvars: { country: 'US' } } );
		$window.triggerHandler( 'hashchange' );
	} );

	$( 'body#nspired-school-home' ).each( function() {
		swfobject.embedSWF( 'http://education.ti.com/flash/products/US/school/home.swf', 'flash-placeholder-object', '960', '396', '10.0.0', '', { LoadXML: 'http://education.ti.com/flash/products/US/school/VirtualSchoolHouse.xml' }, { wmode: 'transparent', allowScriptAccess: 'always' }, { LoadXML: 'http://education.ti.com/flash/products/US/school/VirtualSchoolHouse.xml' } );
	} );

	$( 'body#nspired-school-about' ).each( function() {
		$( '#slideshow' ).jeSlideshow();
	} );

	$( 'body#nspired-school-story' ).each( function() {
		$( 'blockquote.left, blockquote.right' )
		.wrapInner( $.create( 'div' ).addClass( 'middle' ) )
		.prepend( $.create( 'div' ).addClass( 'top' ) )
		.append( $.create( 'div' ).addClass( 'bottom' ) );

		$( 'span.condensed' ).each( function() {
			var $span = $(this).hide();
			$.create( 'a' )
			.attr( { href: '#' } )
			.addClass( 'expand-collapse'  )
			.text( '\u2026[+]' )
			.click( function( e ) {
				e.preventDefault();
				var $t = $(this);
				if( $t.text() === '\u2026[+]' ) {
					$span.show();
					$t.text( '[-]' );
				} else {
					$span.hide();
					$t.text( '\u2026[+]' );
				}
			} )
			.insertAfter( $span );
		} );

		$( '#photo-gallery' ).each( function() {
			var photo_gallery = $(this);
			var h2 = photo_gallery.children( 'h2' );
			var ul = photo_gallery.children( 'ul' );
			var lis = ul.children( 'li' );

			var content_div =
				$.create( 'div' )
				.attr( { id: 'photo-gallery-content' } )
				.insertAfter( h2 );

			var content_img_wrapper =
				$.create( 'div' )
				.attr( { id: 'photo-gallery-image-wrapper' } )
				.appendTo( content_div );

			var content_img =
				$.create( 'img' )
				.attr( { id: 'photo-gallery-image', alt: '' } )
				.appendTo( content_img_wrapper );

			var content_info =
				$.create( 'div' )
				.attr( { id: 'photo-gallery-information' } )
				.appendTo( content_div );

			$.create( 'br' ).attr( { clear: 'all' } ).appendTo( content_div );

			var content_prev =
				$.create( 'a' )
				.html( '&nbsp;' )
				.attr( { href: '#', id: 'photo-gallery-previous' } )
				.addClass( 'gallery-left off' )
				.click( function( e ) {
					e.preventDefault();
					var index = lis.index( ul.children( 'li.selected' ) ) || 0;
					if( index > 0 ) lis.eq( index - 1 ).triggerHandler( 'select' );
				} )
				.appendTo( content_div );

			var content_next =
				$.create( 'a' )
				.html( '&nbsp;' )
				.attr( { href: '#', id: 'photo-gallery-next' } )
				.addClass( 'gallery-right off' )
				.click( function( e ) {
					e.preventDefault();
					var index = lis.index( ul.children( 'li.selected' ) ) || 0;
					lis.eq( index + 1 ).triggerHandler( 'select' );
				} )
				.appendTo( content_div );

			$.create( 'br' ).attr( { clear: 'all' } ).appendTo( content_div );

			var scroll_wrapper =
				$.create( 'div' )
				.attr( { id: 'photo-gallery-scroll' } )
				.append( ul )
				.appendTo( photo_gallery );

			var scroll_left =
				$.create( 'a' )
				.html( '&nbsp;' )
				.attr( { href: '#', id: 'photo-gallery-left' } )
				.addClass( 'gallery-left off' )
				.click( function( e ) {
					e.preventDefault();
					var index = lis.index( ul.children( 'li.selected' ) ) || 0;
					if( index > 0 ) lis.eq( index - 1 ).triggerHandler( 'select' );
				} )
				.insertBefore( scroll_wrapper );

			var scroll_right =
				$.create( 'a' )
				.html( '&nbsp;' )
				.attr( { href: '#', id: 'photo-gallery-right' } )
				.addClass( 'gallery-right off' )
				.click( function( e ) {
					e.preventDefault();
					var index = lis.index( ul.children( 'li.selected' ) ) || 0;
					lis.eq( index + 1 ).triggerHandler( 'select' );
				} )
				.insertAfter( scroll_wrapper );

			var li_margin = 42;
			var li_total_width = 0;
			lis
			.each( function() {
				var li = $(this);
				var content =
					$.create( 'div' )
					.append(
						li.children( 'h4, div.location, div.date, div.description' )
						.detach()
					);

				li.data( 'content', content );

				li.bind( 'select', function() {
					$.bbq.pushState( { i: lis.index( this ) + 1 } );
				} );

				li.children( 'a' )
				.click( function( e ) {
					e.preventDefault();
					li.triggerHandler( 'select' );
				} );

				li_total_width += ( li.outerWidth() + li_margin );
			} );
			ul.width( li_total_width );

			photo_gallery =
				photo_gallery
				.detach()
				.show()
				.dialog( {
					autoOpen: false,
					width: '634px',
					resizable: false,
					modal: true,
					open: function() {
						if( isNaN( parseInt( $.bbq.getState( 'i' ), 10 ) ) ) lis.eq( 0 ).triggerHandler( 'select' );
					},
					close: function () {
						$.bbq.removeState( 'photo-gallery', 'i' );
					}
				} );

			$window
			.bind( 'hashchange', function() {
				var i = parseInt( $.bbq.getState( 'i' ), 10 );
				if( typeof $.bbq.getState( 'photo-gallery' ) !== 'undefined' ) {
					if( !photo_gallery.dialog( 'isOpen' ) ) photo_gallery.dialog( 'open' );
					
					if( !isNaN( i ) ) {
						var li = lis.eq( i - 1 );
						if( li.length === 1 ) {
							if( i > 1 ) {
								content_prev.removeClass( 'off' ).addClass( 'on' );
								scroll_left.removeClass( 'off' ).addClass( 'on' );
							} else {
								content_prev.removeClass( 'on' ).addClass( 'off' );
								scroll_left.removeClass( 'on' ).addClass( 'off' );
							}
							if( i < lis.length ) {
								content_next.removeClass( 'off' ).addClass( 'on' );
								scroll_right.removeClass( 'off' ).addClass( 'on' );
							} else {
								content_next.removeClass( 'on' ).addClass( 'off' );
								scroll_right.removeClass( 'on' ).addClass( 'off' );
							}

							lis.removeClass( 'selected' );
							content_info.children( 'div' ).detach();

							li.addClass( 'selected' );
							content_img.attr( { src: li.children( 'a:has(img)' ).attr( 'href' ) } );
							content_info.append( li.data( 'content' ) );

							scroll_wrapper.stop( true ).scrollTo( li, { axis: 'x', duration: 'slow',  offset: { left: ( scroll_wrapper.innerWidth() - li.outerWidth() ) / -2 } } );
						}
					}
				} else {
					if( photo_gallery.dialog( 'isOpen' ) ) photo_gallery.dialog( 'close' );
				}
			} );
		} );
		$window.trigger( 'hashchange' );
	} );

	$( 'body#nspired-school-classroom-science' ).each( function() {
		swfobject.embedSWF( 'http://education.ti.com/flash/products/US/school/shell.swf', 'flash-placeholder-object', '960', '496', '10.0.0', '', { LoadXML: 'http://education.ti.com/flash/products/US/school/VirtualSchoolHouse.xml', InitialRoom: 0 }, { wmode: 'transparent', allowScriptAccess: 'always' }, { LoadXML: 'http://education.ti.com/flash/products/US/school/VirtualSchoolHouse.xml', InitialRoom: 0 } );
	} );

	$( 'body#nspired-school-classroom-math' ).each( function() {
		swfobject.embedSWF( 'http://education.ti.com/flash/products/US/school/shell.swf', 'flash-placeholder-object', '960', '496', '10.0.0', '', { LoadXML: 'http://education.ti.com/flash/products/US/school/VirtualSchoolHouse.xml', InitialRoom: 4 }, { wmode: 'transparent', allowScriptAccess: 'always' }, { LoadXML: 'http://education.ti.com/flash/products/US/school/VirtualSchoolHouse.xml', InitialRoom: 4 } );
	} );

	$( 'body#nspired-school-classroom-computer-lab' ).each( function() {
		swfobject.embedSWF( 'http://education.ti.com/flash/products/US/school/shell.swf', 'flash-placeholder-object', '960', '496', '10.0.0', '', { LoadXML: 'http://education.ti.com/flash/products/US/school/VirtualSchoolHouse.xml', InitialRoom: 1 }, { wmode: 'transparent', allowScriptAccess: 'always' }, { LoadXML: 'http://education.ti.com/flash/products/US/school/VirtualSchoolHouse.xml', InitialRoom: 1 } );
	} );

	$( 'body#nspired-school-classroom-tech-coordinator' ).each( function() {
		swfobject.embedSWF( 'http://education.ti.com/flash/products/US/school/shell.swf', 'flash-placeholder-object', '960', '496', '10.0.0', '', { LoadXML: 'http://education.ti.com/flash/products/US/school/VirtualSchoolHouse.xml', InitialRoom: 3 }, { wmode: 'transparent', allowScriptAccess: 'always' }, { LoadXML: 'http://education.ti.com/flash/products/US/school/VirtualSchoolHouse.xml', InitialRoom: 3 } );
	} );

	$( 'body#nspired-school-classroom-staff-development' ).each( function() {
		swfobject.embedSWF( 'http://education.ti.com/flash/products/US/school/shell.swf', 'flash-placeholder-object', '960', '496', '10.0.0', '', { LoadXML: 'http://education.ti.com/flash/products/US/school/VirtualSchoolHouse.xml', InitialRoom: 2 }, { wmode: 'transparent', allowScriptAccess: 'always' }, { LoadXML: 'http://education.ti.com/flash/products/US/school/VirtualSchoolHouse.xml', InitialRoom: 2 } );
	} );
	
	$( 'body.nspired-school-classroom' ).each( function() {
		var virtualSchool_swf = $( '#flash-placeholder-object' ).get( 0 );
		var virtualSchool_importClassroom = function( classroom_id, serialized_data ) {
			if( !virtualSchool_swf ) return;
			else return virtualSchool_swf.importClassroom( classroom_id, serialized_data );
		};

		var virtualSchool_exportClassroom = function() {
			if( !virtualSchool_swf ) return { classroom_id: null, serialized_data: null };
			else return virtualSchool_swf.exportClassroom();
		};

		window.virtualSchool_ready = function() {
			virtualSchool_swf = $( '#flash-placeholder-object' ).get( 0 );
		};

		window.virtualSchool_change = function() {
			var data = virtualSchool_exportClassroom();
		};

		window.virtualSchool_command = function( command, args ) {
			var data = virtualSchool_exportClassroom();
		};

		window.setLightboxFlashTrigger( { id: 'video-navigator', width: 900, height: 530, swf: 'http://education.ti.com/flash/products/nspire/US-navigator-feature.swf', flashvars: { country: 'US'} }, 'show' );
		window.setLightboxFlashTrigger( { id: 'video-docking-station', width: 900, height: 530, swf: 'http://education.ti.com/flash/products/nspire/US-cx-data-coll-feature.swf', flashvars: { country: 'US'} }, 'show' );
		window.setLightboxFlashTrigger( { id: 'video-data-collection', width: 900, height: 530, swf: 'http://education.ti.com/flash/products/nspire/US-cx-data-coll-feature.swf', flashvars: { country: 'US'} }, 'show' );
		window.setLightboxFlashTrigger( { id: 'video-nspire-cx', width: 900, height: 530, swf: 'http://education.ti.com/flash/products/nspire/US-cx-handheld-feature.swf', flashvars: { country: 'US' } }, 'show' );
		window.setLightboxFlashTrigger( { id: 'video-software', width: 900, height: 530, swf: 'http://education.ti.com/flash/products/nspire/US-software-feature.swf', flashvars: { country: 'US' } }, 'show' );
		window.setLightboxFlashTrigger( { id: '360-nspire', width: 640, height: 480, swf: 'http://education.ti.com/flash/nspire360.swf', flashvars: { country: 'US' } }, 'show' );
		window.setLightboxFlashTrigger( { id: '360-nspire-cas', width: 640, height: 480, swf: 'http://education.ti.com/flash/nspire360.swf', flashvars: { country: 'US', calculator: 'cas' } }, 'show' );
		window.setLightboxFlashTrigger( { id: '360-nspire-cx', width: 640, height: 480, swf: 'http://education.ti.com/flash/products/nspire/nspirecx360.swf', flashvars: { country: 'US' } }, 'show' );
		window.setLightboxFlashTrigger( { id: '360-nspire-cx-cas', width: 640, height: 480, swf: 'http://education.ti.com/flash/products/nspire/nspirecx360.swf', flashvars: { country: 'US', calculator: 'cas' } }, 'show' );
		
		window.showvideonavigator = function() { $.bbq.pushState( { show: 'video-navigator' } ); };
		window.showvideodockingstation = function() { $.bbq.pushState( { show: 'video-docking-station' } ); };
		window.showvideodatacollection = function() { $.bbq.pushState( { show: 'video-data-collection' } ); };
		window.showvideonspirecx = function() { $.bbq.pushState( { show: 'video-nspire-cx' } ); };
		window.showvideosoftware = function() { $.bbq.pushState( { show: 'video-software' } ); };
		window.show360nspire = function() { $.bbq.pushState( { show: '360-nspire' } ); };
		window.show360nspirecas = function() { $.bbq.pushState( { show: '360-nspire-cas' } ); };
		window.show360nspirecx = function() { $.bbq.pushState( { show: '360-nspire-cx' } ); };
		window.show360nspirecxcas = function() { $.bbq.pushState( { show: '360-nspire-cx-cas' } ); };

		$window.trigger( 'hashchange' );
	} );

	$( 'body.product-showcase' ).each( function() {
		$( '.jeslideshow' ).jeSlideshow();
	} );

	$( 'body.product-science' ).each( function() {
		$( '.jeslideshow' ).jeSlideshow();
		window.setLightboxFlashTrigger( { id: 'data-collection', width: 900, height: 530, swf: 'http://education.ti.com/flash/products/nspire/US-cx-data-coll-feature.swf', flashvars: { country: 'US'} }, 'video' );
		$window.triggerHandler( 'hashchange' );
	} );

	$( 'body#os-update-page' ).each( function() {
		$( '.slideshow ul.slideshow-tabs > li' )
		.each( function( index, e ) {
			$(e)
			.addClass( 'slideshow-tab slideshow-tab-' + index )
			.data('slideshow-tab-index', index)
			.click( function () {
				$( '.slideshow li.jeslideshow-button-' + ( index + 2 ) )
				.triggerHandler( 'select');
			} );
		} );
		$( '.slideshow ul.slides' ).jeSlideshow( { delay: 8000 } );
		$( '.slideshow ul.jeslideshow-buttons > li' )
		.bind( 'select', function() {
			var $this = $(this); 
			$( '.slideshow ul.slideshow-tabs > li' )
			.removeClass( 'selected' )
			.each( function( index, e ) {
				if( $this.data( 'frame' ).data( 'slideIndex' ) == ( index + 1 ) ) {
					$(e).addClass( 'selected' );
					return false;
				}
			} );
		} );

		//fly-out for os-update
		if($('#update-path').length){
			$('#update-path').css( {
				"position" : "absolute",
				"z-index" : "1000",
				"top" : "322px",
				"right" : "20px"
			}).mouseleave(function(){
				$.bbq.pushState('#update-path-close');
			});
		   
			$window
				.bind( 'hashchange', function() {
					if( typeof $.bbq.getState( 'update-path-open' ) !== 'undefined' ) {
						$('#update-path').show();
					}
					else{
						$('#update-path').hide();
					}
				});

			$window.trigger( 'hashchange' );
		}

	} );

	$( '.expand-list li' ).click( function() {
		$( '.expand-list li' ).removeClass( 'selected' );
		$(this).addClass( 'selected' );
	} );

	/* document-player code */
	$( '.launch-button' )
	.popupWindow( {
		centerBrowser: true,
		width: 640,
		height: 480,
		resizable: true,
		windowName: 'docPlayer'
	} );

	$( 'ul.site-categories > li > ul > li > a' )
	.each( function( index, e ) {
		var $e = $( e );
		var country = $e.attr( 'rel' );
		if( $.cookie( 'selected_country' ) === country && $.deparam.querystring().force !== '1' ) {
			location.replace( $e.attr( 'href' ) );
			return;
		}

		$e
		.data( 'href', $e.attr( 'href' ) )
		.data( 'country', country )
		.click( function( e ) {
			var $t = $(this);
			e.preventDefault();
			if( $( '#chk-enable-cookie' ).attr( 'checked' ) ) {
				$.cookie( 'selected_country', $t.data( 'country' ), { domain: '.ti.com', path: '/' } );
			}
			location.replace( $t.attr( 'href' ) );
		} );
	} );

	$( '.no-multiplebgs body#product-loan-form-enter-code' ).each( function() {
		$( 'fieldset' ).wrapInner(
			$.create( 'div' ).addClass( 'wrapper-center' ).append(
				$.create( 'div' ).addClass( 'wrapper-left' ).append(
					$.create( 'div' ).addClass( 'wrapper-right' )
				)
			)
		);
	} );

	$( 'body.product-loan-form' ).each( function() {
		var getValidationRange = function( e ) {
			if( e instanceof jQuery ) e = e.get( 0 );
			else if( e instanceof String || typeof e == 'string' ) e = document.getElementById( e );
			var retval = { min: null, max: null };

			if( !e ) return retval;

			$.each( ( e.className || '' ).split( ' ' ), function() {
				var min = /^range-min-(\d+)$/;
				var max = /^range-max-(\d+)$/;
				if( min.test( this ) ) retval.min = parseInt( min.exec( this )[ 1 ], 10 );
				if( max.test( this ) ) retval.max = parseInt( max.exec( this )[ 1 ], 10 );
			} );

			return retval;
		};

		var minDaysStart = getValidationRange( 'validator-range-contact-date-start' ).min;
		var defaultDaysStart = 28;
		var maxDaysStart = getValidationRange( 'validator-range-contact-date-start' ).max;
		var minDaysEnd = getValidationRange( 'validator-range-contact-date-end' ).min;
		var maxDaysEnd = getValidationRange( 'validator-range-contact-date-end' ).max;

		$( 'input.date' ).each( function() {
			var $t = $(this);
			$t.attr( { readonly: 'readonly' } );
			$t.wrap( $.create( 'div' ).addClass( 'date-wrapper' ) );
			$t.datepicker();
		} );

		var $or = $( 'span.or' ).detach().eq( 0 );

		var $dateStart = $( 'input.date[name="contact-date-start"]' );
		var $dateEnd = $( 'input.date[name="contact-date-end"]' );
		var d = new Date();
		d.setDate( d.getDate() + minDaysStart );
		$dateStart.datepicker( 'option', { minDate: $.datepicker.formatDate( $.datepicker.W3C, d ) } );

		d.setDate( d.getDate() + ( defaultDaysStart - minDaysStart ) );
		$dateStart.datepicker( 'setDate', $.datepicker.formatDate( $.datepicker.W3C, d ) );

		d.setDate( d.getDate() + minDaysEnd );
		$dateEnd.datepicker( 'option', { minDate: $.datepicker.formatDate( $.datepicker.W3C, d ) } );

		d.setDate( d.getDate() + ( maxDaysEnd - minDaysEnd ) );
		$dateEnd.datepicker( 'option', { maxDate: $.datepicker.formatDate( $.datepicker.W3C, d ) } );
		$dateEnd.datepicker( 'setDate', d );

		d = new Date();
		d.setDate( d.getDate() + maxDaysStart );
		$dateStart.datepicker( 'option', { maxDate: $.datepicker.formatDate( $.datepicker.W3C, d ) } );

		$dateStart.change( function() {
			var d = $dateStart.datepicker( 'getDate' );

			d.setDate( d.getDate() + 1 );
			$dateEnd.datepicker( 'option', { minDate: $.datepicker.formatDate( $.datepicker.W3C, d ) } );

			d.setDate( d.getDate() + ( maxDaysEnd - minDaysEnd ) );
			$dateEnd.datepicker( 'option', { maxDate: $.datepicker.formatDate( $.datepicker.W3C, d ) } );
		} );
	
		var $fieldsetTabs = $( '#fieldset-tabs' );
		var $fieldsetNspire = $( '#fieldset-nspire' );
		var $fieldsetNspireLegend = $fieldsetNspire.children( 'legend' );
		var $fieldsetNspireLegendText = $fieldsetNspireLegend.text();
		var $fieldsetNspireLegendRadio = $fieldsetNspireLegend.find( 'input:radio' );

		var $fieldsetGraphing = $( '#fieldset-graphing' );
		var $fieldsetGraphingLegend = $fieldsetGraphing.children( 'legend' );
		var $fieldsetGraphingLegendText = $fieldsetGraphingLegend.text();
		var $fieldsetGraphingLegendRadio = $fieldsetGraphingLegend.find( 'input:radio' );

		var $fieldsetProbes = $( '#fieldset-probes' );
		var $fieldsetProbesLegend = $fieldsetProbes.children( 'legend' );
		var $fieldsetProbesContent = $fieldsetProbes.children( '.fieldset-content' );
		$fieldsetProbesContent.children( ':nth-child(odd)' ).addClass( 'odd' );
		$fieldsetProbesContent.children( ':nth-child(even)' ).addClass( 'even' );

		var $handheldSectorCXCAS = $( '#handheld-cx-cas' );
		var $handheldSectorCXCASRadio = $handheldSectorCXCAS.find( 'input:radio' );
		var $handheldSectorCX = $( '#handheld-cx' );
		var $handheldSectorCXRadio = $handheldSectorCX.find( 'input:radio' );
		var $handheldWrapper = $.create( 'div' ).attr( { id: 'handheld-cx-wrapper' } ).insertBefore( $handheldSectorCXCAS );
		$handheldSectorCXCAS.appendTo( $handheldWrapper );
		$.create( 'div' ).attr( { id: 'handheld-cx-divider' } ).appendTo( $handheldWrapper );
		$handheldSectorCX.appendTo( $handheldWrapper );

		var updateSelectedHandheld = function() {
			$fieldsetNspire.removeClass( 'selected-cx selected-cx-cas selected-none' );
			if( $handheldSectorCXCASRadio.is( ':checked' ) ) $fieldsetNspire.addClass( 'selected-cx-cas' );
			if( $handheldSectorCXRadio.is( ':checked' ) ) $fieldsetNspire.addClass( 'selected-cx' );
			if( !$handheldSectorCXCASRadio.is( ':checked' ) && !$handheldSectorCXRadio.is( ':checked' ) ) $fieldsetNspire.addClass( 'selected-none' );
		};

		$handheldSectorCXCASRadio.click( updateSelectedHandheld );
		$handheldSectorCXRadio.click( updateSelectedHandheld );
		updateSelectedHandheld();

		$form.addClass( 'selected-nspire' );

		$fieldsetNspireLegend.wrapInner( $.create( 'span' ) );
		$fieldsetGraphingLegend.wrapInner( $.create( 'span' ) );

		$or.clone().prependTo( $fieldsetGraphingLegend );

		$.create( 'a' )
		.addClass( 'switch-tab' )
		.text( $fieldsetNspireLegendText )
		.attr( { href: '#' } )
		.click( function( e ) {
			e.preventDefault();
			$form.removeClass( 'selected-graphing' ).addClass( 'selected-nspire' );
			$fieldsetGraphingLegendRadio.removeAttr( 'checked' );
			$fieldsetNspireLegendRadio.attr( { checked: 'checked' } );
		} )
		.prependTo( $fieldsetGraphingLegend );

		$or.clone().appendTo( $fieldsetNspireLegend );

		$.create( 'a' )
		.addClass( 'switch-tab' )
		.text( $fieldsetGraphingLegendText )
		.attr( { href: '#' } )
		.click( function( e ) {
			e.preventDefault();
			$form.removeClass( 'selected-nspire' ).addClass( 'selected-graphing' );
			$fieldsetNspireLegendRadio.removeAttr( 'checked' );
			$fieldsetGraphingLegendRadio.attr( { checked: 'checked' } );
		} )
		.appendTo( $fieldsetNspireLegend );

		$.create( 'a' )
		.text( '+' )
		.attr( { href: '#' } )
		.click( function( e ) {
			var $t = $(this);
			e.stopImmediatePropagation();
			e.preventDefault();
			if( $t.text() === '+' ) {
				$fieldsetProbesContent.slideDown( 'slow' );
				$t.text( '\u2013' );
			} else {
				$fieldsetProbesContent.slideUp( 'slow' );
				$t.text( '+' );
			}
		} )
		.prependTo( $fieldsetProbesLegend );
		$fieldsetProbesLegend.click( function( e ) {
			e.stopImmediatePropagation();
			e.preventDefault();
			$(this).children( 'a' ).click();
		} );

		$fieldsetProbesContent.slideUp( 0 );

		$( 'label > .validator[id^="validator-required"]' ).each( function() {
			var $t = $(this);
			$t.bind( 'validate', function() {
				var $ctl = $t.siblings( 'input,textarea,select' );
				if( !$ctl.val() && ( !$ctl.attr( 'checked' ) != 'checked' ) ) {
					$form.data( 'validation', $.merge( $form.data( 'validation' ), [ $t.text() ] ) );
				}
			} );
		} );

		$( 'label > .validator[class*="range-"]' ).each( function() {
			var $t = $(this);
			$t.bind( 'validate', function() {
				var $ctl = $t.siblings( 'input,textarea,select' );
				if( $ctl.length === 0 ) return;
				var v = parseInt( $ctl.val(), 10 );
				if( isNaN( v ) || !isFinite( v ) ) {
					$form.data( 'validation', $.merge( $form.data( 'validation' ), [ $t.text() ] ) );
					return;
				}
				var range = getValidationRange( this );
				if( ( range.min !== null && v < range.min ) || ( range.max !== null && v > range.max ) ) {
					$form.data( 'validation', $.merge( $form.data( 'validation' ), [ $t.text() ] ) );
					return;
				}
			} );
		} );

		$( '.validator#validator-format-contact-email' ).each( function() {
			var $t = $(this);
			$t.bind( 'validate', function() {
				var $ctl = $t.siblings( 'input' );
				var v = $ctl.val();
				if( v && !/^[^@]+@[^.@]+\.[^@]+[^.@]$/i.test( v ) ) {
					$form.data( 'validation', $.merge( $form.data( 'validation' ), [ $t.text() ] ) );
				}
			} );
		} );

		$( '.validator#validator-nspire-required-model' ).each( function() {
			var $t = $(this);
			$t.bind( 'validate', function() {
				if( !$fieldsetNspireLegendRadio.is( ':checked' ) ) return;
				if( !$handheldSectorCXCASRadio.is( ':checked' ) && !$handheldSectorCXRadio.is( ':checked' ) ) {
					$form.data( 'validation', $.merge( $form.data( 'validation' ), [ $t.text() ] ) );
				}
			} );
		} );

		$( '.validator#validator-nspire-required-kit' ).each( function() {
			var $t = $(this);
			$t.bind( 'validate', function() {
				if( !$fieldsetNspireLegendRadio.is( ':checked' ) ) return;
				if(
				( $handheldSectorCXCASRadio.is( ':checked' ) && ( $( 'input[name="cx-cas-kit"]:checked' ).length == 0 ) )
			||  ( $handheldSectorCXRadio.is( ':checked' ) && ( $( 'input[name="cx-kit"]:checked' ).length == 0 ) )
			) {
					$form.data( 'validation', $.merge( $form.data( 'validation' ), [ $t.text() ] ) );
				}
			} );
		} );

		$( '.validator#validator-nspire-range-kit' ).each( function() {
			var $t = $(this);
			$t.bind( 'validate', function() {
				if( !$fieldsetNspireLegendRadio.is( ':checked' ) ) return;
				var range = getValidationRange( this );
				var sum = 0;
				if( $handheldSectorCXCASRadio.is( ':checked' ) ) {
					$( 'input[name^="cx-cas:"]' ).each( function() {
						var v = parseInt( $(this).val(), 10 );
						sum += ( isNaN( v ) ) ? 0 : v;
					} );
				}
				if( $handheldSectorCXRadio.is( ':checked' ) ) {
					$( 'input[name^="cx:"]' ).each( function() {
						var v = parseInt( $(this).val(), 10 );
						sum += ( isNaN( v ) ) ? 0 : v;
					} );
				}

				if( ( range.min !== null && sum < range.min ) || ( range.max !== null && sum > range.max ) ) {
					$form.data( 'validation', $.merge( $form.data( 'validation' ), [ $t.text() ] ) );
					return;
				}
			} );			
		} );

		$( '.validator#validator-sum-graphing' ).each( function() {
			var $t = $(this);
			$t.bind( 'validate', function() {
				if( !$fieldsetGraphingLegendRadio.is( ':checked' ) ) return;
				var range = getValidationRange( this );
				var sum = 0;
				$( 'input[name^="graphing:"]' ).each( function() {
					var v = parseInt( $(this).val(), 10 );
					sum += ( isNaN( v ) ) ? 0 : v;
				} );

				if( ( range.min !== null && sum < range.min ) || ( range.max !== null && sum > range.max ) ) {
					$form.data( 'validation', $.merge( $form.data( 'validation' ), [ $t.text() ] ) );
					return;
				}
			} );
		} );

		$( '.validator#validator-probes-range' ).each( function() {
			var $t = $(this);
			$t.bind( 'validate', function() {
				var range = getValidationRange( this );
				var sum = 0;
				$( 'input[name^="probe:"]' ).each( function() {
					var v = parseInt( $(this).val(), 10 );
					sum += ( isNaN( v ) ) ? 0 : v;
				} );

				if( ( range.min !== null && sum < range.min ) || ( range.max !== null && sum > range.max ) ) {
					$form.data( 'validation', $.merge( $form.data( 'validation' ), [ $t.text() ] ) );
					return;
				}
			} );
		} );

		$form.submit( function( e ) {
			$form.data( 'validation', [] );
			$form.find( '.validator' ).each( function() { $(this).triggerHandler( 'validate' ); } );
			var validation = $form.data( 'validation' ).join( '\n' );
			if( validation ) {
				e.preventDefault();
				alert( validation );
			}
		} );
	} );

	//india activities page tabs
	$('body#nspired-learning-activities, body#activities-home, body.has-activities').each( function() {
		var paginationPattern = /^paginate-by-(\d+)$/;
		var pagination = 10;
		var hasPagination = false;

		

		$.each( ( $('#activities-table').attr('class') || '' ).split( ' ' ), function() {
			if( paginationPattern.test( this ) ){
				pagination = parseInt( paginationPattern.exec( this )[ 1 ], 10 );
				hasPagination = true;
			}
		} );

		//if a pagination list doesn't exist but the
		//pm specified a pagination value then lets make one.
		if(!$('#pagination-list')[0] && hasPagination){
			$('#pagination-wrapper').append($('<ul id="pagination-list" />'));
		}
		$('#pagination-list').addClass('bbq').data('pagination', pagination);

	});
	$('.bbq a[href^=#]').live('click', function (e) {
		var state = {},
		// Get the id.
					  id = $(this).closest('.bbq').attr('id'),
		// Get the url from the link's href attribute, stripping any leading #.
					  url = $(this).attr('href').replace(/^#/, '');
		// Set the state!
		if(id != 'pagination-list' && $('#pagination-list')[0] && $('#pagination-list').is(':visible')){
			state['pagination-list']  = "1";
		}
		state[id] = url;
		$.bbq.pushState(state);
		// And finally, prevent the default link click behavior by returning false.
		return false;
	});

	$(window).bind('hashchange', function (e) {
		$('.bbq').each(function () {
			var that = $(this),
						url = $.bbq.getState(that.attr('id')) || '';
			that.data('url', url);

			that.find('.selected').removeClass('selected');
			if (url == '') {
				that.find('li:first-child').addClass('selected');
			}
			else {
				that.find('li a').each(function () {
					if ($(this).attr('href') == '#' + url) {
						$(this).parent().addClass('selected');

						return false;
					}
				});
			}
		});

		//actual logic that hides activities based on filter.
		var grade = $('#grades-list').data('url');
		var subject = $('#subjects-list').data('url');
		var page = 1;
		var pagination;
		var $pl = $('#pagination-list');
		var count;

		$pl.each(function(){
			page = parseInt($pl.data('url'), 10);
			if(!page){
				page = 1;
			}
			pagination = parseInt($pl.data('pagination'), 10);
		});
		
		
		var $trs=$('#activities-table tbody tr:not(.no-activities)');
		$('#activities-table tbody tr').hide();

		if( grade ) {
			$trs = $trs.not($trs.filter(':not(.' + grade +')'));
		}
		if( subject ) {
			$trs = $trs.not($trs.filter(':not(.' + subject +')'));
		}

		if( pagination > 0 ) {
			count = Math.ceil( $trs.length / pagination );

			var shownPages = [];
			var addPage = function( i ) {
				if( $.inArray( i, shownPages ) < 0 ) shownPages.push( i );
			};

			addPage( 1 );
			for( var i = Math.max( 1, page - 2 ); i <= Math.min( page + 2, count ); i++ ) { addPage( i ); }
			addPage( count );

			$pl.empty();
			var prevPage = 0;
			$.each( shownPages, function( dummy, i ) {
				if( i > prevPage + 1 ) {
					$pl.append( $( '<li>&hellip;</li>' ) );
				}
				var li = $('<li><a href="#' + i + '">' + i + '</a></li>');
				if(i == page){
					li.addClass("selected");
				}
				$pl.append(li);
				prevPage = i;
			} );
			if(count <= 1){
				$pl.hide();
				$('#pagination-wrapper').hide();
			}
			else{
				$pl.show();
				$('#pagination-wrapper').show();
			}

			//filter activities by page if need be.
			$trs = $trs.slice((page - 1) * pagination ,  page * pagination);
		}

		//show the activities that are available
		$trs.show();

		//if none of the activities are visible, show a message.
		if(!$('#activities-table tbody tr').is( ':visible' )){
			$('#activities-table tbody tr.no-activities').show();
		}

	});
	$(window).trigger('hashchange');

} );

