﻿(function($) {
	if( !''.trim ) String.prototype.trim = function() { return this.replace( /(^\s+|\s+$)/g, '' ); };

	$.create =
		function( tagName ) {
			if( document.createElementNS ) return $( document.createElementNS( 'http://www.w3.org/1999/xhtml', tagName ) );
			else return $( document.createElement( tagName ) );
		};

	window.Current = {
		BasePath: '/calculators/timathnspired',
		Website: {
			ID: 'US',
			DisplayName: 'US and Canada',
			Language: 'en',
			SearchWatermark: 'Enter Keywords',
			DateFormat: 'MM/DD/YYYY',
			TimeFormat: '12'
		}
	};

	var ajax = function( url, params, callback ) {
		callback = callback ||
			function( data, textStatus, request ) {

			};

		$.ajax( {
			type: 'POST',
			contentType: 'application/json; charset=utf-8',
			url: '/calculators/timathnspired/US' + url,
			data: Sys.Serialization.JavaScriptSerializer.serialize( params ),
			dataType: 'json',
			success: function( data, textStatus, request ) {
				callback( data, textStatus, request );
			},
			error: function( request, textStatus, errorThrown ) {
				Dialog.Notify.Open( { heading: 'Error', text: 'An unexpected system error has occurred while processing your request. Please go back and try again.' } );
			}
		} );
	};

	window.Ajax = {
		Authentication: {
			LogIn: function( username, password, callback ) {
				ajax( '/Ajax/Authentication.asmx/LogIn', { username: username, password: password }, callback );
			}
		},
		Activities: {
			Recommend: function( activityId, callback ) {
				ajax( '/Ajax/Activities.asmx/Recommend', { activityId: activityId }, callback );
			},
			Save: function( activityId, callback ) {
				ajax( '/Ajax/Activities.asmx/Save', { activityId: activityId }, callback );
			},
			Unsave: function( activityId, callback ) {
				ajax( '/Ajax/Activities.asmx/Unsave', { activityId: activityId }, callback );
			},
			GroupList: function( callback ) {
				ajax( '/Ajax/Activities.asmx/GroupList', {}, callback );
			},
			GroupRemove: function( groupId, callback ) {
				ajax( '/Ajax/Activities.asmx/GroupRemove', { groupId: groupId }, callback );
			},
			GroupCreate: function( groupName, activityIds, callback ) {
				ajax( '/Ajax/Activities.asmx/GroupCreate', { groupName: groupName, activityIds: activityIds }, callback );
			},
			AddToGroup: function( groupId, activityIds, callback ) {
				ajax( '/Ajax/Activities.asmx/AddToGroup', { groupId: groupId, activityIds: activityIds }, callback );
			},
			RemoveFromGroup: function( groupId, activityIds, callback ) {
				ajax( '/Ajax/Activities.asmx/RemoveFromGroup', { groupId: groupId, activityIds: activityIds }, callback );
			},
			SubmitTextbook: function( title, publisher, edition, publishDate, comments, callback ) {
				ajax( '/Ajax/Activities.asmx/SubmitTextbook', { title: title, publisher: publisher, edition: edition, publishDate: publishDate, comments: comments }, callback );
			},
			EmailAFriend: function( fromName, fromEmail, toName, toEmail, subject, body, recaptchaChallenge, recaptchaResponse, activityIds, callback ) {
				ajax( '/Ajax/Activities.asmx/EmailAFriend', { fromName: fromName, fromEmail: fromEmail, toName: toName, toEmail: toEmail, subject: subject, body: body, recaptchaChallenge: recaptchaChallenge, recaptchaResponse: recaptchaResponse, activityIds: activityIds }, callback );
			}
		}
	};

	var dlg = function( key, title ) {
		var dlg;
		var defaultWidth = 300;
		return {
			Open: function( params ) {
				if( dlg ) {
					if( dlg.dialog( 'isOpen' ) ) dlg.dialog( 'close' );

					dlg
					.addClass( 'loading' )
					.triggerHandler( 'setParams', [ params || {} ] );
					$window.triggerHandler('style');
					dlg.triggerHandler('style');

					dlg
					.removeClass( 'loading' )
					.dialog( 'option', 'position', 'center' )
					.dialog( 'open' );
				} else {
					dlg =
						$.create( 'div' )
						.dialog( {
							autoOpen: true,
							width: defaultWidth,
							resizable: false,
							closeText: 'Close Window',
							modal: true,
							title: title,
							open: function () {
								if( $.browser.msie && $.browser.version == '6.0' ) $( '#site-wrapper select,#site-wrapper iframe' ).css( { visibility: 'hidden' } );
							},
							close: function () {
								if( $.param.fragment() == key ) $.bbq.removeState();
								if( $.browser.msie && $.browser.version == '6.0' ) $( '#site-wrapper select,#site-wrapper iframe' ).css( { visibility: 'visible' } );
							}
						} )
						.addClass('loading')
						.bind( 'style', function() {
							var result = /^(\d+)px$/.exec( dlg.children( 'div' ).eq( 0 ).css( 'width' ) );
							var w = null;
							if( result ) w = parseInt( result[ 1 ], 10 );
							if( isNaN( w ) ) w = defaultWidth;
							else w += 18;
							if( w < defaultWidth ) w = defaultWidth;
							dlg.dialog( 'option', { width: w } );
						} );

					$window.data( 'dialog-' + key, dlg );

					dlg.load( '/calculators/timathnspired/US/html/' + key + '.html', function() {
						setTimeout( function() {
							dlg
							.triggerHandler( 'setParams', [ params || {} ] );
							$window.triggerHandler('style');
							dlg.triggerHandler('style');

							dlg
							.removeClass( 'loading' )
							.dialog( 'option', 'position', 'center' )
							.triggerHandler( 'dialogopen' );
						}, 0 );
					} );
				}
			},
			Close: function() {
				if( dlg && dlg.dialog( 'isOpen' ) ) dlg.dialog( 'close' );
			},
			IsOpen: function() {
				return ( dlg && dlg.dialog( 'isOpen' ) );
			}
		};
	};

	/*************************
	* Added by Penwoodtech
	**************************/
	var dlgCollection = function( key, title ) {
		var dlg;
		return {
			Open: function( params ) {				
				if( dlg ) {
					if( dlg.dialog( 'isOpen' ) ) dlg.dialog( 'close' );
					dlg.addClass( 'loading' ).triggerHandler( 'setParams', [ params || {} ] );
					$window.triggerHandler( 'style' );
					dlg	
					.dialog( 'option', 'title', title )
					.dialog( 'option', 'dialogClass', 'dlg-add-remove-activity' )
					.dialog( 'option', 'position', params.position )
					.removeClass( 'loading' )					
					.dialog( 'open' );
				} else {	
					dlg =
						$.create( 'div' )
						.dialog( {
							autoOpen: true,
							width: 'auto',
							resizable: false,
							draggable: false,
							closeText: 'Close Window',							
							title: title,
							open: function () {
								if( $.browser.msie && $.browser.version == '6.0' ) $( '#site-wrapper select,#site-wrapper iframe' ).css( { visibility: 'hidden' } );
							},
							close: function () {
								if( $.param.fragment() == key ) $.bbq.removeState();
								if( $.browser.msie && $.browser.version == '6.0' ) $( '#site-wrapper select,#site-wrapper iframe' ).css( { visibility: 'visible' } );
							}
						} )
						.addClass( 'loading' );		
					
					$window.data( 'dialog-' + key, dlg );
					dlg.load( '/calculators/timathnspired/US/html/' + key + '.html', function() {
						setTimeout( function() {
							dlg.triggerHandler( 'setParams', [ params || {} ] );
							$window.triggerHandler( 'style' );
							dlg							
							.dialog( 'option', 'title', title )
							.dialog( 'option', 'dialogClass', 'dlg-add-remove-activity' )
							.dialog( 'option', 'position', params.position )
							.removeClass( 'loading' )
							.triggerHandler( 'dialogopen' );
						}, 0 );						
					} );
				}
			},
			Close: function() {
				if( dlg && dlg.dialog( 'isOpen' ) ) dlg.dialog( 'close' );
			},
			IsOpen: function() {
				return ( dlg && dlg.dialog( 'isOpen' ) );
			}
		};
	};
	
	window.Dialog = {
		LogIn: dlg( 'login', 'Sign In' ),
		SubmitTextbook: dlg( 'submit-textbook', 'Textbook' ),
		ReportIssue: dlg( 'report-issue', 'Report an Issue' ),
		AddToGroup: dlg( 'add-to-group', 'Add to Activity Set' ),
		Notify: dlg( 'notify', 'Notice' ),
		EmailAFriend: dlg( 'email-a-friend', 'Email a friend' ),	
		
		/*************************
		* Added by Penwoodtech
		**************************/
		PreviewVideo: dlg( 'preview-video', 'Preview' ),		
		PreviewImage: dlg( 'preview-image', 'Preview' ),
		Standards: dlg('standards', 'Alignment'),
		AddRemoveActivity: dlgCollection('add-remove-activity', 'My Activities')
		/*************************/
    };

    $.fn.popupWindow = function (instanceSettings) {

        return this.each(function () {

            $(this).click(function () {

                $.fn.popupWindow.defaultSettings = {
                    centerBrowser: 0, // center window over browser window? {1 (YES) or 0 (NO)}. overrides top and left
                    centerScreen: 0, // center window over entire screen? {1 (YES) or 0 (NO)}. overrides top and left
                    height: 500, // sets the height in pixels of the window.
                    left: 0, // left position when the window appears.
                    location: 0, // determines whether the address bar is displayed {1 (YES) or 0 (NO)}.
                    menubar: 0, // determines whether the menu bar is displayed {1 (YES) or 0 (NO)}.
                    resizable: 0, // whether the window can be resized {1 (YES) or 0 (NO)}. Can also be overloaded using resizable.
                    scrollbars: 0, // determines whether scrollbars appear on the window {1 (YES) or 0 (NO)}.
                    status: 0, // whether a status line appears at the bottom of the window {1 (YES) or 0 (NO)}.
                    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: 0 // determines whether a toolbar (includes the forward and back buttons) is displayed {1 (YES) or 0 (NO)}.
                };

                settings = $.extend({}, $.fn.popupWindow.defaultSettings, instanceSettings || {});

                var windowFeatures = 'height=' + settings.height +
								    ',width=' + settings.width +
								    ',toolbar=' + settings.toolbar +
								    ',scrollbars=' + settings.scrollbars +
								    ',status=' + settings.status +
								    ',resizable=' + settings.resizable +
								    ',location=' + settings.location +
								    ',menuBar=' + settings.menubar;

                settings.windowName = this.name || settings.windowName;
                settings.windowURL = this.href || settings.windowURL;
                var centeredY, centeredX;

                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)));
                    }
                    window.open(settings.windowURL, settings.windowName, windowFeatures + ',left=' + centeredX + ',top=' + centeredY).focus();
                } else if (settings.centerScreen) {
                    centeredY = (screen.height - settings.height) / 2;
                    centeredX = (screen.width - settings.width) / 2;
                    window.open(settings.windowURL, settings.windowName, windowFeatures + ',left=' + centeredX + ',top=' + centeredY).focus();
                } else {
                    window.open(settings.windowURL, settings.windowName, windowFeatures + ',left=' + settings.left + ',top=' + settings.top).focus();
                }
                return false;
            });

        });
    };
} )(jQuery);

$(function () {
    window.$window = $(window);
    window.$body = $(document.body);

    var pageRequestManager = Sys.WebForms.PageRequestManager.getInstance();
    var loggedIn = $('body.logged-in').length > 0;

    $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'); }
			);
		});
	});

    $('#navigation-primary')
	.hover(
		function () {
		    if ($.browser.msie && $.browser.version == '6.0') $('#site-wrapper select,#site-wrapper iframe').css({ visibility: 'hidden' });
		},
		function () {
		    if ($.browser.msie && $.browser.version == '6.0') $('#site-wrapper select,#site-wrapper iframe').css({ visibility: 'visible' });
		}
	);

    pageRequestManager.add_pageLoaded(function (sender, e) {
        $window.triggerHandler('style');
    });

    $('#site-search input:text').data('Watermark', Current.Website.SearchWatermark);
    $('.form-line input:text').data('Watermark', 'Enter Keywords');

    $(':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'); });

    if (!loggedIn) {
        var logInOutLink = $('#navigation-account > li:last-child > a:eq(0)');

        var chs = [];
        var hookup =
			function (selector, optional, callback) {
			    var ch;
			    var cb =
					function (user) {
					    $body.removeClass('logged-out').addClass('logged-in');
					    loggedIn = true;
					    logInOutLink.text('Sign Out').attr({ href: 'http://epsstore.ti.com/OA_HTML/TIibeCZzpEntry.jsp\u003fsiteref=http%3a%2f%2feducation%2eti%2ecom%2fcalculators%2ftimathnspired/&target=signout&cid=US&minisite=10023&respid=22372' });

					    $.each(chs, function () { $('a').unbind('click', this); });

					    if (callback) {
					        callback(user);
					    } else {
					        var $t;
					        if (selector instanceof jQuery) $t = selector;
					        else $t = $(selector);

					        var href = $t.attr('href');
					        var target = $t.attr('target');
					        $t.triggerHandler('click');
					        if (href) {
					            if (target) {
					                var w = window.open(href, target);
					                if (!w) location.href = href;
					            } else {
					                if (href != '#') location.href = href;
					            }
					        }
					    }
					};
			    ch =
					function (e) {
					    if (optional && ($.cookie('axdc-guest') == '1')) return;
					    e.preventDefault();
					    e.stopImmediatePropagation();
					    if (selector == 'a[rel~="login-message"]') {
					        selector = $(this);
					        Dialog.LogIn.Open({ message: optional, callback: cb });
					    } else {
					        selector = $(this);
					        Dialog.LogIn.Open({ optional: optional, callback: cb });
					    }
					};
			    chs.push(ch);
			    $(selector).click(ch);
			};

        if ($.cookie('axdc-guest') != '1') hookup('a[rel~="login-optional"]', true);
        hookup('a[rel~="login-mandatory"]', false);
        hookup('a[rel~="login-message"]', true);
        hookup(logInOutLink, false, function () { location.reload(); });
    }

    $('.section-software-search tbody, .section-guidebooks-search tbody, #my-software tbody, #my-guidebooks tbody, #my-activities-landing tbody')
	.bind('collapse', function () {
	    $(this)
		.removeClass('expanded')
		.addClass('collapsed');
	})
	.bind('expand', function () {
	    $(this)
		.removeClass('collapsed')
		.addClass('expanded')
		.closest('table')
		.children('tbody')
		.not(this)
		.each(function () { $(this).triggerHandler('collapse'); });
	});

    $('.search-advanced tbody')
	.each(function (index, e) {
	    if (!($(this).hasClass('collapsed') || $(this).hasClass('expanded'))) {
	        $(this).addClass('expanded');
	    }
	})
	.bind('collapse', function () {
	    $(this)
		.removeClass('expanded')
		.addClass('collapsed');
	})
	.bind('expand', function () {
	    $(this)
		.removeClass('collapsed')
		.addClass('expanded');
	})
	.find('th')
	.click(function () {
	    var tbody = $(this).closest('tbody');

	    if (tbody.hasClass('collapsed')) tbody.triggerHandler('expand');
	    else tbody.triggerHandler('collapse');
	})
	.end()
	.find(':checkbox')
	.each(function (index, e) {
	    $(e)
		.change(function () {
		    var tbody = $(this).closest('tbody');
		    var hdr = tbody.find('th');
		    var cspan = hdr.find('span.count');
		    if (cspan.length == 0) {
		        cspan =
					$.create('span')
					.addClass('count')
					.appendTo(hdr);
		    }

		    var chkcount = tbody.find(':checked').length;
		    if (chkcount == 0) cspan.hide();
		    else cspan.show();
		    cspan.text(chkcount);
		});
	});

    var tbody_heading = $('table tbody th h3 a');

    tbody_heading
	.each(function () {
	    var $t = $(this);
	    $t
		.data('link_name', $t.attr('name'))
		.removeAttr('name');
	});

    $('#personalize-container #activities-right-nav')
	.click(function () {
	    $('#personalize-container.enabled')
		.switchClass('enabled', 'disabled', 500);

	    $('#personalize-container.disabled')
		.switchClass('disabled', 'enabled', 500);
	});

    var eula =
        $('#eula')
		.dialog({
		    autoOpen: false,
		    minHeight: 40,
		    resizable: false,
		    closeText: 'Close Window',
		    width: $('#eula').width(),
		    modal: true,
		    title: 'License',
		    close: function () { $.bbq.removeState('license'); }
		});
    eula.children('h4').remove();
    eula.children('table').each(function (index, e) {
        $(e)
		.removeAttr('width')
		.width((parseInt(eula.css('width')) - 20));
    });
    $window
	.bind('hashchange', function () {
	    var fragment = $.param.fragment();

	    var ac = $.deparam.querystring()['ac'];
	    if (ac && !fragment) fragment = 'view-' + ac;

	    (function () {
	        var selected =
				tbody_heading
				.filter(function () { return $(this).data('link_name') == fragment; });
	        if (selected.length > 0) {
	            selected
				.closest('tbody')
				.triggerHandler('expand');
	        } else {
	            tbody_heading
				.closest('tbody')
				.filter('thead + tbody,:first-child')
				.triggerHandler('expand');
	        }
	    })();

	    if (fragment == 'license') eula.dialog('open');
	    else eula.dialog('close');

	    if (fragment == 'submit-textbook') Dialog.SubmitTextbook.Open();
	    else Dialog.SubmitTextbook.Close();
	})
	.triggerHandler('hashchange');

    (function () {
        var cookieName = 'ax-recommended-US';
        var recommendedIds = ($.cookie(cookieName) || '').split('&');

        /*************************
        * Edited by Penwoodtech
        **************************/
        $('.likes-icon a')
		.click(function (e) {
		    e.preventDefault();
		    var activityId = parseInt($('input[name="activity-id"]').val());
		    var value = activityId + '=1';
		    var icon = $(this);
		    var recommended = false;
		    $.each(recommendedIds, function () {
		        if (this == value) recommended = true;
		    });
		    if (!recommended) {
		        Ajax.Activities.Recommend(activityId, function () {
		            icon.addClass('recommended');
		        });
		        recommendedIds.push(value);
		        $.cookie(cookieName, recommendedIds.join('&'), { path: '/calculators/timathnspired/' });
		    }
		})
		.each(function () {
		    var activityId = parseInt($('input[name="activity-id"]').val());
		    var value = activityId + '=1';
		    var recommended = false;
		    $.each(recommendedIds, function () {
		        if (this == value) recommended = true;
		    });
		    if (recommended) $(this).addClass('recommended');
		});
        /*************************/

        $('.email-icon a')
		.click(function (e) {
		    e.preventDefault();
		    Dialog.EmailAFriend.Open({ activityIds: [parseInt($('input[name="activity-id"]').val())] });
		});

        $('#my-activities-landing tbody tr td.email a')
		.click(function (e) {
		    e.preventDefault();
		    Dialog.EmailAFriend.Open({ activityIds: [parseInt($(this).closest('tr').find('input[name="activity-id"]').val())] });
		});

        /*************************
        * Added by Penwoodtech
        **************************/
        $('.email-a-friend')
		.click(function (e) {
		    e.preventDefault();
		    Dialog.EmailAFriend.Open({ activityIds: null });
		});
        /*************************/

        $('#activity-search-results tbody tr td.recommend a, #my-activities-landing tbody tr td.recommand a')
		.click(function (e) {
		    e.preventDefault();
		    var $td = $(this).closest('td');
		    var $tr = $td.closest('tr');
		    var activityId = parseInt($tr.find('input[name="activity-id"]').val());
		    var value = activityId + '=1';

		    var recommended = false;
		    $.each(recommendedIds, function () {
		        if (this == value) recommended = true;
		    });
		    if (!recommended) {
		        Ajax.Activities.Recommend(activityId, function () {
		            $tr.addClass('recommended');
		            var $span = $td.find('span').eq(0);
		            $span.text(parseInt($span.text()) + 1);
		        });
		        recommendedIds.push(value);
		        $.cookie(cookieName, recommendedIds.join('&'), { path: '/calculators/timathnspired/' });
		    }
		})
		.each(function () {
		    var $tr = $(this).closest('tr');
		    var activityId = parseInt($tr.find('input[name="activity-id"]').val());
		    var value = activityId + '=1';

		    var recommended = false;
		    $.each(recommendedIds, function () {
		        if (this == value) recommended = true;
		    });

		    if (recommended) $tr.addClass('recommended');
		});

        /*************************
        * Edited by Penwoodtech
        **************************/
        $('.collection-icon a#icon').attr('title', 'Save Activity');
        $('.collection-icon a#icon.saved').attr('title', 'Remove Activity');
        var mnCollection = {
            isHide: function () { return $('.collection-icon').find('ul').css('display') == 'none'; },
            show: function () { $('.collection-icon').addClass('collection-icon-selected').find('ul').css('display', 'block'); },
            hide: function () { $('.collection-icon').removeClass('collection-icon-selected').find('ul').css('display', 'none'); }
        };
        $('.collection-icon a#icon').click(function () {
            if (mnCollection.isHide()) { mnCollection.show(); }
            else { mnCollection.hide(); }
        });

        $('.collection-icon .view-collection').attr('href', 'http://education.ti.com/calculators/downloads/US/My/Activities/Default.aspx');
        $('.collection-icon .view-collection').click(function () { mnCollection.hide(); });

        $('.collection-icon .add-remove-collection').text($('.collection-icon a#icon').hasClass('saved') ? 'Remove from My Activities' : 'Add to My Activities');
        $('.collection-icon .add-remove-collection').click(function (e) {
            e.preventDefault();
            mnCollection.hide();
            var link = $('.collection-icon a#icon');
            var activityId = parseInt($('input[name="activity-id"]').val());
            if (link.hasClass('saved')) {
                Ajax.Activities.Unsave(activityId, function () {
                    link.removeClass('saved');
                    link.attr('title', 'Save Activity');
                    $('.collection-icon .add-remove-collection').text('Add to My Activities');
                    Dialog.Notify.Open({ heading: 'Remove Activity', text: 'This activity will be removed from your Saved Activities' });
                });
            } else {
                Ajax.Activities.Save(activityId, function () {
                    link.addClass('saved');
                    link.attr('title', 'Remove Activity');
                    $('.collection-icon .add-remove-collection').text('Remove from My Activities');
                    Dialog.Notify.Open({ heading: 'Save to My Downloads and Activities', text: 'This activity has been saved.' });
                });
            }
        });
        /*
        $( '.collection-icon a' ).attr('title', 'Save Activity');
        $( '.collection-icon a.saved' ).attr('title', 'Remove Activity');
        $( '.collection-icon a' )
        .click( function( e ) {
        e.preventDefault();
        var link = $(this);
        var activityId = parseInt( $( 'input[name="activity-id"]' ).val() );
        if( link.hasClass( 'saved' ) ) {
        Ajax.Activities.Unsave( activityId, function() {
        link.removeClass( 'saved' );
        link.attr('title', 'Save Activity');
        Dialog.Notify.Open( { heading: 'Remove Activity', text: 'This activity will be removed from your Saved Activities' } );
        } );
        } else {
        Ajax.Activities.Save( activityId, function() {
        link.addClass( 'saved' );
        link.attr('title', 'Remove Activity');
        Dialog.Notify.Open( { heading: 'Save to My Downloads and Activities', text: 'This activity has been saved.' } );
        } );
        }
        } );
        */
        /*************************
        * Edited by Penwoodtech
        **************************/
        $('#activity-search-results tbody tr td.save a').attr('title', 'Save Activity');
        $('#activity-search-results tbody tr.saved td.save a').attr('title', 'Remove Activity');

        $('#activity-search-results tbody tr td.save a')
		.click(function (evt) {
		    evt.preventDefault();
		    var $tr = $(this).closest('tr');
		    var activityId = parseInt($tr.find('input[name="activity-id"]').val());
		    var $icon = $(this);
		    var pos = objPosition.findPosRelativeToViewport(this);
		    var param = {
		        position: [pos.x - 155, pos.y],
		        activityId: activityId,
		        collectionUrl: 'http://education.ti.com/calculators/downloads/US/My/Activities/Default.aspx',
		        icon: $icon,
		        tr: $tr
		    };
		    Dialog.AddRemoveActivity.Open(param);
		});

        /*************************
        * Added by Penwoodtech
        **************************/
        var objPosition = {
            findPos: function (obj) {
                var curleft = curtop = 0;
                if (obj.offsetParent) {
                    do {
                        curleft += obj.offsetLeft;
                        curtop += obj.offsetTop;
                    } while (obj = obj.offsetParent);
                }
                return [curleft, curtop];
            },
            getPageScroll: function () {
                var xScroll, yScroll;
                if (self.pageYOffset) {
                    yScroll = self.pageYOffset;
                    xScroll = self.pageXOffset;
                } else if (document.documentElement && document.documentElement.scrollTop) {
                    yScroll = document.documentElement.scrollTop;
                    xScroll = document.documentElement.scrollLeft;
                } else if (document.body) {
                    yScroll = document.body.scrollTop;
                    xScroll = document.body.scrollLeft;
                }
                return [xScroll, yScroll]
            },
            findPosRelativeToViewport: function (obj) {
                var objPos = this.findPos(obj)
                var scroll = this.getPageScroll()
                return { x: (objPos[0] - scroll[0]), y: (objPos[1] - scroll[1]) };
            }
        }
        $('#my-activities-landing tbody tr td.add-to-group a')
		.click(function (e) {
		    e.preventDefault();
		    var $tr = $(this).closest('tr');
		    var activityId = parseInt($tr.find('input[name="activity-id"]').val());

		    Dialog.AddToGroup.Open({ activityIds: [activityId] });
		});

        /*************************
        * Added by Penwoodtech
        **************************/
        $('#activity-search-results tbody tr td div.video a')
		.click(function (e) {
		    if ($(this).hasClass('image')) {
		        Dialog.PreviewImage.Open({ src: $(this).attr('rel'), overview: $(this).attr('lang') });
		    } else {
		        Dialog.PreviewVideo.Open({ src: $(this).attr('rel') });
		    }
		});

        $('a[href^="http://correlation.edgate.com/interface\u003fpubid=ti&token=e00fba6fedfb8a49e13346f7099a23fc&function=viewCorrelations&loid="]').click(function (e) {
            e.preventDefault();
            Dialog.Standards.Open({ textbook: false, activityId: /\d+$/.exec($(this).attr('href')) });
        });
        $('a[href^="http://correlation.edgate.com/interface\u003fpubid=titxt&token=739920aa25ab0959ea31530c33d126a3&function=viewCorrelations&textbook=true&loid="]').click(function (e) {
            e.preventDefault();
            Dialog.Standards.Open({ textbook: true, activityId: /\d+$/.exec($(this).attr('href')) });
        });
        /*************************/

    })();

    (function () {
        var slides = [];
        $('#home-main > li:has(input[name="slideshow"])')
		.removeClass('selected')
		.each(function () {
		    var $li = $(this);
		    var num = parseInt($li.find('input[name="slideshow"]').val());
		    slides.push({
		        li: $li,
		        content: $li.children('.content').eq(0),
		        summary: $li.children('.summary').eq(0),
		        backgrounds: parseInt($li.find('input[name="slideshow"]').val())
		    });
		})
		.eq(0)
		.addClass('selected');
        if (slides.length > 0) {
            var timeout = null;
            var delay = 10000;
            var fadeDuration = 1000;
            var currentSlide = slides[0];

            var stopAnimation = function () {
                if (timeout) clearTimeout(timeout);
                timeout = null;
                $.each(slides, function () { this.content.stop(true, true).css({ 'z-index': 1 }); });
            };

            var showSlide = function (num, bg, showNext) {
                stopAnimation();
                var previousSlide = currentSlide;
                previousSlide.content.closest('ul').removeClass();
                previousSlide.li.removeClass('selected');
                currentSlide = slides[num - 1];
                currentSlide.content.closest('ul').removeClass().addClass('slide-' + bg);
                currentSlide.li.addClass('selected');


                var showNext = function () {
                    if (bg < currentSlide.backgrounds) showSlide(num, bg + 1);
                    else showSlide((num % slides.length) + 1, 1);
                };

                if (previousSlide != currentSlide) {
                    stopAnimation();
                    previousSlide.content.show().css({ 'z-index': 3 });
                    currentSlide.content.show().css({ 'z-index': 2 });
                    previousSlide.content.fadeOut(fadeDuration, function () {
                        if (!timeout && (showNext !== false)) timeout = setTimeout(showNext, delay);
                    });
                } else {
                    if (showNext !== false) timeout = setTimeout(showNext, delay);
                }
            };
            $window
			.bind('hashchange', function () {
			    switch ($.param.fragment()) {
			        case 'Software':
			        default:
			            stopAnimation();
			            timeout = setTimeout(function () { showSlide(1, 1, false); });
			            break;
			        case 'Guidebooks':
			            stopAnimation();
			            timeout = setTimeout(function () { showSlide(2, 1, false); });
			            break;
			        case 'Activities':
			            if ($('body.ax-enabled').length > 0) timeout = setTimeout(function () { showSlide(3, 1, false); });
			            break;
			        case 'My':
			            timeout = setTimeout(function () { showSlide(($('body.ax-enabled').length > 0) ? 4 : 3, 1, false); });
			            break;
			    }
			});

            $.each(slides, function (i) {
                this.summary
				.click(function (e) { e.preventDefault(); setTimeout(function () { showSlide(i + 1, 1); }, 0); })
				.css({ cursor: 'pointer' })
				.find('a')
				.click(function (e) {
				    e.stopPropagation();
				    stopAnimation();
				});

                this.content.find('input,select').click(stopAnimation);
            });
        }
    })();

    /* Penwoodtech */
    $('.section-activities #content table td.type span').each(function (i, e) {
        var typeid = $(e).attr('class');
        switch (typeid) {
            case 'type-4': $(e).attr('title', 'Action Consequence'); break;
            case 'type-5': $(e).attr('title', 'Bell Ringer'); break;
            case 'type-6': $(e).attr('title', 'Create Your Own'); break;
            case 'type-8': $(e).attr('title', 'TI-Nspire Navigator Compatible'); break;
            case 'type-20': $(e).attr('title', 'TI Navigator'); break;
            default: break;
        }
    });
    /*expand list */
    var id = $('.expand-list').first().attr('id');
    $(window).bind('hashchange', function (e) {
        if (e.fragment === "") {
            e.fragment = $('.expand-list > li').first().attr('id');
        }
        else {
            var offset = $('.expand-list').first().offset();

            if (offset) {
                $('html,body').scrollTop(offset.top);
            }
        }
        $('.expand-list > li')
		    .removeClass('selected')
		    .each(function (index, element) {
		        if (e.fragment.indexOf($(element).attr('id')) != -1) {
		            $(element).addClass('selected');


		            return false;
		        }
		    });


    });
    $('.expand-list li > h3')
	    .each(function (index, element) {
	        var li_id = id + '-li-' + index;
	        $(element).parent().attr('id', li_id);
	        $(element).wrap('<a href="#' + li_id + '" />');
	    });
    $(window).trigger('hashchange');

    $('#document-player, .document-player').popupWindow({
        centerBrowser: 1,
        width: 424,
        height: 318,
        resizable: 1
    });
});
