/*----------------------------------------------------

	DO NOT MODIFY!

	We need an object and a function outside the jQuery function wrapper
	so flash can call "execSetVideo()" after the flash video
	carousel loads in the video tab found in "5.12_service_details_tabs_auth_user.shtml and also in other pages".  
	The flashChangeTools object stores the flash object ID to be targeted, the video ID that dictates
	which video to be played and a boolean to determine of flash video carousel
	should load a specific video or load normally in default mode.

	Do a global search for comment below to find out how the flashChangeTools object gets populated
	(note: don't include the quotes in your search).

	"// Function that plays specific video in flash video carousel"

----------------------------------------------------*/

var flashChangeTools = {
	runSetVideo:false,
	storedVideoId:"",
	storedObjectId:""
};

function execSetVideo(){
	if(flashChangeTools.runSetVideo){
		document.getElementById(flashChangeTools.storedObjectId).setVideo(flashChangeTools.storedVideoId);
	}
}

(function($) {
	/* Below line added for :  Tech Implementation for loading spinner while logining in */
	var loadingImageGlobal = $('<span class="loadingImageSpinner">&nbsp;</span>').load();

	// Global functions that need to run on every page to setup various interface elements
	$(function() {
	
		(function() {	
			$().ajaxSuccess(function(evt, request, settings){
				if(settings.dataType == "json" && evt.data){	
				
					//we create our the session object
					var sessionObj = {
					    sessionValidated: evt.data.sessionValidated,
					    sessionErrorMessage: evt.data.sessionErrorMessage,
					    sessionRedirectUrl: evt.data.sessionRedirectUrl
					};
					
					Sprint.fn.validateSession(sessionObj);
				}
			});
			
			// Since not all ajax calls have the error function added to them,
			// this will add it when it is non-existent.
			$().ajaxError(function(event, request, options, error) {
				if (options && options.error === undefined) {
					Sprint.fn.ajaxError(event);
				}
			});
		})();
		
		/* Setup the main navigation
		----------------------------------------------------*/
		(function(){
	
			var subNavTimer;
			
			var globalNav = $("#navGlobal");
			var globalNavItems = globalNav.find("> li");
			
			var currentNavState = globalNav.find('> li.currentNavState');
			var hasCurrentState = currentNavState.length > 0;
			
			globalNavItems.bind("mouseover", function() {
				if (hasCurrentState) {
					globalNav.find('> li.over').each(function() {
						var prev_currentNavItem = $(this);
						var prev_currentSubNav = prev_currentNavItem.find("ul.subNav");

						prev_currentNavItem.removeClass("over");

						prev_currentSubNav.find("li.last").removeClass("lastJS");
						prev_currentSubNav.css({
							left: "",
							width: ""
						});
					});
				}
				
				var currentNavItem = $(this);
				var currentNavItemIndex = globalNavItems.index(currentNavItem);
				var currentSubNav = currentNavItem.find("ul.subNav");
				
				currentNavItem.addClass("over");
				
				//Determine the width of the subnav
				var subNavMaxWidth = 829;
				var subNavWidth = 0;
				
				//Calculate the width of the subNav menu
				currentSubNav.find("li").each(function() {
					subNavWidth += $(this).outerWidth(true);
				});
				
				//Set the width for IE6
				if ($.browser.msie && $.browser.version < 7) {
					currentSubNav.width(subNavWidth);
				}
				
				if (subNavWidth <= subNavMaxWidth) {
					currentSubNav.find("li.last").addClass("lastJS");
				}
				
				//If the subNav width is less than the max, check the positioning of the subNav
				if (currentSubNav.width() < subNavMaxWidth) {

					var previousNavItemsTotalWidth = 0;
					var globalNavItemsTotalWidth = 0;
					
					globalNavItems.each(function() {
						var thisItem = $(this);
						if (globalNavItems.index(thisItem) < globalNavItems.index(currentNavItem)) {
							previousNavItemsTotalWidth += thisItem.outerWidth();
						}
						
						globalNavItemsTotalWidth += thisItem.outerWidth();
					});
					
					var navItemRightEdge = previousNavItemsTotalWidth + currentNavItem.outerWidth();
					var subNavRightEdge = currentSubNav.outerWidth();
					
					var leftOverlap = previousNavItemsTotalWidth;
					var rightOverlap = subNavRightEdge - navItemRightEdge;
					
					//If the right overlap of the sub menu is narrower than the left overlap, and the sub menu's right edge is less than the right edge of the last item in the main navigation... line up the sub menu with the last item of the main nav (right aligned)
					if (rightOverlap < leftOverlap && subNavRightEdge < globalNavItemsTotalWidth) {
					
						currentSubNav.css({left: globalNavItemsTotalWidth - subNavRightEdge});

					}
					
					//Finally, make sure that the left edge of the sub menu is always less than or equal to the left edge of the currently selected main nav item
					if (Math.round(currentSubNav.offset().left) > Math.round(currentNavItem.offset().left)) {
						var currentSubNavLeft = parseInt(currentSubNav.css("left"));
						
						currentSubNav.css({
							left: currentSubNavLeft - (Math.round(currentSubNav.offset().left) - Math.round(currentNavItem.offset().left))
						});
					}

				}

			}).bind("mouseout", function(event) {
				if (!$(this).hasClass('currentNavState')) {
					var currentNavItem = $(this);
					var currentSubNav = currentNavItem.find("ul.subNav");

					currentNavItem.removeClass("over");

					currentSubNav.find("li.last").removeClass("lastJS");
					currentSubNav.css({
						left: "",
						width: ""
					});
					
					if (hasCurrentState) {
						currentNavState.trigger('mouseover');
					}
				}
			});
			
			if (hasCurrentState) {
				currentNavState.trigger('mouseover');
			}
			
			globalNav.find("ul.subNav li").bind("mouseover", function() {
				$(this).addClass("over");
				$(this).siblings().removeClass("over");
				clearTimeout(subNavTimer);
				
			}).bind("mouseout", function() {
				var subNavItem = $(this);
				subNavTimer = setTimeout(function(){
					subNavItem.removeClass("over");
				}, 100);
			});
			
			//Add focus handling to aid in keyboard navigation
			var navTimer;
			
			globalNav.find("li a").bind("focus", function() {
			
				//If it's a sub-menu link, make sure the sub-menu stays open and the main nav item still shows as "over"
				if ($(this).parents(".subNav").length > 0) {
					$(this).parent().trigger("mouseover");
					clearTimeout(navTimer);
				}

				$(this).parent().trigger("mouseover");			
				
			}).bind("blur", function() {
			
				var navItem = $(this);
				//Set a slight delay before firing the mouseout event for this nav item (which will remove the "over" class and cause the sub menu to be hidden again). This delay will be cancelled out if the next item to get focus is still inside the currently visible sub menu.
				navTimer = setTimeout(function() {
					navItem.parent().trigger("mouseout");
				}, 50);
				
			});
			if($('#navConsumerTab').length>0){
				$('<div id="navDivider"></div>').appendTo('body');			
			}
			/* additions for business/consumer tabs */
			if(Sprint.fn.readCookie("SLTID")){
				
				var aud=Sprint.fn.readCookie("segment_user").toString().replace(/\s/g,'').toLowerCase();
				var tab="";
				var content="";
				var taud="";
				switch(aud){
					case 'bp':
					case 'bc': tab="#navConsumerTab"; 
											content='<p>Oops! You are currently logged in as a business customer. To visit the personal area, please logout. If you do not wish to logout, click "Stay here" to remain on the current page.</p>';
											taud="consumer";
											break;
					default: tab="#navBusinessTab";	
							content='<p>Oops! You are currently logged in as a personal customer. To visit the business area, please logout. If you do not wish to logout, click "Stay here" to remain on the current page.</p>';			
							taud="business";
				}
				
				var url=encodeURIComponent($(tab+' a').attr('href'));
				var urlBase="/entrycheck/logout.fcc?TARGET=%2Fmysprint%2FSwitchContext%3FswitchToUser%3Dconsumer%26target%3Dhttp%3A%2F%2Fmysprint.sprint.com%3A8003%2Findex_c.html%26smlogout%3Dtrue"
				
				var urlBase="/entrycheck/logout.fcc?TARGET=";
				var urlExt="/mysprint/SwitchContext?switchToUser="+taud+"&smlogout=true&target="+url;
				
				$(tab+' a').bind('click', function(event){
					if(typeof(TeaLeaf) != "undefined" &&  typeof(TeaLeaf.Client) != "undefined") {
						TeaLeaf.Client.tlAddEvent(event);
					}
					event.preventDefault();
					
					url=Sprint.baseUrls.mysprint+urlBase+encodeURIComponent(urlExt);
					content+='<div class="audienceModalButtons"><ul>';
					content+='<li><a href="'+url+'" class="button1_converted"><span><span><span><span>logout</span></span></span></span></a></li>';
					content+='<li><a href="#" class="button2_converted closeModal"><span><span><span><span>Stay here</span></span></span></span></a></li>';
					content+='</ul></div>';
					var audienceModal = $("#navAudienceModal");
					if(audienceModal.length < 1) {
						var newModal = $('<div class="modal"></div>').appendTo("body").hide();
						audienceModal = $('<div id="navAudienceModal">'+content+'</div>').appendTo(newModal);							
					}
					audienceModal.openModal({
						width:500,
						openCallback: function(){									
							Sprint.modal.elem.sizeModal();
							try {
								Analytics[Analytics.MetricData.appId].screenChangeHelperFunction(((aud == "bc")?"Business":"Consumer")+" Logout Intercept Page");
							} catch(e){};
						}
					});
				
				});
			}
	
		})();
		
		/* Setup mini cart in the nav utility
		----------------------------------------------------*/
		(function() {
			var container = $('#miniCartContainer');
			var button = $('#miniCartButton');
			var popup = $('#miniCartPopup');
			var popupContainer = $('#miniCartPopupContainer');
			
			// fixes popup not animating the first time
			popup.css('display', 'none');
			
			// fix safari position
			if ($.browser.safari) {
				popup.css('left', '-144px');
			}
			
			button.bind("click", function(event) {
				
				// TEALEAF SESSION TRACKING
				if (typeof(TeaLeaf) != "undefined" &&  typeof(TeaLeaf.Client) != "undefined") {
					TeaLeaf.Client.tlAddEvent(event);
				}
				
				window.location = '/global/shop/cart/5.4_shopping_cart.shtml';
				
				// Mini-Cart has been de-scoped
				/*
				var opened = container.hasClass("on");
				
				if (opened) {
					animate();
					return;
				}
				
				$.ajax({
					url: "/global/ajax/5.1_MiniCartPopupBody.php",
					dataType: "html",
					success: function(data) {
						popupContainer.html(data);
						$("#miniCartViewButton").createHighResButtons();
						
						var cartItems = $('#miniCartItems');
						var items = cartItems.find('ul.items');
						
						if (opened == false) {
							container.addClass("on");
							// popup.height(1);
						}
						
						if (cartItems.length > 0) {
							items.find('li:first').addClass('first');
							items.find('li:last').addClass('last');
						} else {
							// disable the view cart button where the cart is empty
							popupContainer.find('#miniCartViewButton').bind('click', function() {
								$(this).blur();
								return false;
							});
						}
						
						function checkHeight()
						{
							var itemsHeight = items.height();
							var containerHeight = $('#miniCartItemsScroller').height();
							
							// loop until layout is finilized and height becomes known
							if (itemsHeight == 0 && containerHeight == 0)
							{
								setTimeout(checkHeight, 100);
								return;
							}
							
							// add scrolling if necessary
							if (itemsHeight > containerHeight) {
								cartItems.wrap('<div class="scroll"></div>');
							}
						};
						
						checkHeight();
						animate();
					}
				});
				
				function animate() {
					popup[opened ? 'slideUp' : 'slideDown']("normal", function() {
						if (opened == true) {
							container.removeClass("on");
						}
					});
				};
				*/
				
				return false;
			})
			.bind("mouseover", function() { button.addClass("hover"); })
			.bind("mouseout", function() { button.removeClass("hover"); })
			;
		})();
		
		/* Setup Chat Offline Tooltip for Global Header
		----------------------------------------------------*/
		(function() {

			// Configure tooltip
			$("#chatOffline").setupComponents();
			$("#chatTooltip").tooltip({belowAnchor: true});
			setTimeout(function() {
					$("#chatOffline").hide();
				}, 1);
			
			// Holiday hours
			$(".chatHolidayHours").hide();
			$("#showChatHolidayHours").live("click", function(event) {
				// TEALEAF SESSION TRACKING
				if (typeof(TeaLeaf) != "undefined" &&  typeof(TeaLeaf.Client) != "undefined") {
					TeaLeaf.Client.tlAddEvent(event);
				}
				event.preventDefault();
				$(".chatHolidayHours").toggle("fast");												  
			});
			
		})();
		
		/* Setup the Search form in the nav
		----------------------------------------------------*/
		(function() {
			
			var searchLabel = $("#frmSearch label");
			var searchField = $("#frmSearch #txtSearch");
			var searchBtnGo = $("#frmSearch"); /* Modified By Breakfix tech team */
			
			searchLabel.hide();
			searchField.val(searchLabel.text());
			/*Below "click" has been modified to "submit" for Breakfix tech team */
			searchBtnGo.bind("submit", function() {
	             var searchFieldValue = searchField.val();
	             var searchfilter="%/\'<>";
	              for (var i = 0; i < searchFieldValue.length; i++) {
	                         if (searchfilter.indexOf(searchFieldValue.charAt(i)) != -1) {
	                                     searchFieldValue = searchFieldValue.replace((searchFieldValue.charAt(i)),"");
	                         }
	              }
	              searchField.val(searchFieldValue); 
            });
	
			//Event handlers
			searchField.bind("focus", function() {
				if ($(this).val() == searchLabel.text()) {
					//Clear the text field
					searchField.val("");
				}
			});
			searchField.bind("blur", function() {
				if ($.trim($(this).val()) == "") {
					searchField.val(searchLabel.text());
				}
			});
			
		})();
		
	
		
		/* Site Map functions and event setup
		----------------------------------------------------*/
		
		(function() {
		
			var siteMapForm = $("#siteMap div.siteMapColSignUp form");
			
			siteMapForm.find('input[type=text]').focus(function(){
				var target = $(this);
				target.attr('value', '');
			});
			
			/*
			siteMapForm.find('input[type=text]').blur(function(){
				var target = $(this);
				var targetLabalText = target.prev('label').text();
				
				if((target.attr('value') == '')){
					target.attr('value', targetLabalText);
				}
			});
			*/
			
			siteMapForm.find('input[type=submit]').unbind('click').bind('click', function(){
				
				var target = $(this);
				
				var	signUpForEmailForm = target.closest('#siteMapEmailSignupForm');
				
				signUpForEmailForm.find("label.error").remove();
				
				var signUpEmailFormFields = {
					emailAddress: {
						name: "signUpEmailAddress",
						type: "emailAddress",
						required: true,
						emptyErrorMessage: Sprint.fn.getContentString("formFieldErrors.emailAddressEmpty"),
						invalidErrorMessage: Sprint.fn.getContentString("formFieldErrors.emailAddressInvalid")
					},
					zipCode: {
						name: "signUpZipCode",
						type: "zipCode",
						required: true,
						emptyErrorMessage: Sprint.fn.getContentString("formFieldErrors.zipCodeEmpty"),
						invalidErrorMessage: Sprint.fn.getContentString("formFieldErrors.zipCodeInvalid")
					}
				};
				
				var validForm = Sprint.fn.validateForm(signUpForEmailForm, signUpEmailFormFields);
			
				if(validForm == true){
				
					signUpForEmailForm.submit();
					
				} else {
				
					signUpForEmailForm.showFormErrors({
                        showInline: true,
                        showSummary: false,
                        errorData: validForm
                    });
                    
                    return false;
					
					/*
					if(validForm.signUpEmailAddress != null){
						if($('#siteMapEmailSignupForm span.'+validForm.signUpEmailAddress.name).length == 0){						
							signUpForEmailForm.find('input[name='+validForm.signUpEmailAddress.name+']').before(
								'\<span class="'+validForm.signUpEmailAddress.name+'"\>! '+validForm.signUpEmailAddress.errorMessage+'\</\span\>'
							);
						}
					} else {
						if(signUpForEmailForm.find('span.signUpEmailAddress').length > 0){						
							signUpForEmailForm.find('span.signUpEmailAddress').remove();
						}
					}
					
					if(validForm.signUpZipCode != null){
						if($('#siteMapEmailSignupForm').find('span.'+validForm.signUpZipCode.name).length == 0){
							signUpForEmailForm.find('input[name='+validForm.signUpZipCode.name+']').before(
								'\<span class="'+validForm.signUpZipCode.name+'"\>! '+validForm.signUpZipCode.errorMessage+'\</\span\>'
							);
						}
					} else {
						if(signUpForEmailForm.find('span.signUpZipCode').length > 0){
							signUpForEmailForm.find('span.signUpZipCode').remove();
						}
					}
					return false;
					*/
				}
				
			});
			
		})();
		
		
		
		/* Convert low-res buttons to high-res buttons
		----------------------------------------------------*/
		$(".sprint input[type='submit'], .sprint input[type='button'], .sprint a.button1, .sprint a.button2, .sprint a.button3, .sprint a.button4, .sprint a.flyout").createHighResButtons();


		/* Setup all default components with default values except for buttons
		----------------------------------------------------*/
		$().setupComponents({
			modals: true,
			buttons: false
		});


		/* Functionality for the global Sign In modal
		----------------------------------------------------*/
		Sprint.openSignInModal = function(queryParam) {
			var modalURL = "/mysprint/shop/includes/login_modal.jsp?selectedFlow=";
			// URL for ZipPTN Login  is different
			if($("#zipViaPTNUrl").length > 0){
				modalURL = $("#zipViaPTNUrl").val();
			}
			if(queryParam != null || queryParam != undefined){
				modalURL += queryParam;
			}
			/* Check if the modal already is there */
            var signInDeepLinkModal = $("#signInDeepLinkModal");
			
			if (signInDeepLinkModal.length < 1) {
				//Because this modal is being loaded via AJAX, it won't exist in the markup already. Create the modal on the fly
				var newModal = $("<div class=\"modal\" id=\"deepLinkSignIn\"></div>").appendTo("div.sprint div.body").hide();
	
				signInDeepLinkModal = $("<div id=\"signInDeepLinkModal\"></div>").appendTo(newModal);
				
			}
			
			signInDeepLinkModal.openModal({
				ajaxContent: true,
				ajaxPath: modalURL,
				
				openCallback: function() {
					Sprint.signInFormProcess(); //This function is defined in later on in this file in the deep linking section. Note: do NOT call Sprint.openSignInModal() before the signInFormProcess function has been defined, or you'll get errors.
					//To enable events to signin box after first time opening.
					if($("#frmInterceptCurrentUser").length > 0) { 
						// Redirect all submit events through our submit button.
						$("#btnLoginSubmitIntercept").unbind("click").bind("click", function(event) {
						
							// TEALEAF SESSION TRACKING
							if (typeof(TeaLeaf) != "undefined" &&  typeof(TeaLeaf.Client) != "undefined") {
								TeaLeaf.Client.tlAddEvent(event);
							}
							event.preventDefault();
							
							$("#frmInterceptCurrentUser").trigger("submit");
						
						});
					
						//$("#frmInterceptCurrentUser").bindLoginActionEvents({parent:$("#frmInterceptCurrentUser").parent(), frmSelector:"#frmInterceptCurrentUser"});
					
						$("#frmInterceptCurrentUser").bind("submit",function(event) {
							event.preventDefault();
							$("#frmInterceptCurrentUser").signinValidationHandler({form:$("#frmInterceptCurrentUser")});
						});
					
						var originalselectionChoiceURL = $("#selectionChoiceURL").val();
						// grab the service URL and append params
						var zipViaPTN = $("#zipViaPTN").val();
						if(zipViaPTN == "zipViaPTN") {
								var zipViaPTNURLDefault = originalselectionChoiceURL.split("selectedFlow=");
								zipViaPTNURLDefault[0] += "selectedFlow="+$("input[name='radInterceptChoice']:checked").val()+zipViaPTNURLDefault[1]+"selectedFlow="+$("input[name='radInterceptChoice']:checked").val();
								$("#selectionChoiceURL").val(zipViaPTNURLDefault[0]);

						}else{
							$("#selectionChoiceURL").val(originalselectionChoiceURL+$("input[name='radInterceptChoice']:checked").val()) ;
						}

		
						$("#frmInterceptCurrentUser").find("input[name='radInterceptChoice']").bind("click", function(event) {
							//event.preventDefault();
							// grab the service URL and append params
							if(zipViaPTN == "zipViaPTN") {
								var zipViaPTNURL = originalselectionChoiceURL.split("selectedFlow=");
								zipViaPTNURL[0] += "selectedFlow="+ $(this).val()+zipViaPTNURL[1]+"selectedFlow="+ $(this).val();
								$("#selectionChoiceURL").val(zipViaPTNURL[0]);
							}else{						
							var selectionChoiceURL = originalselectionChoiceURL;
							selectionChoiceURL += $(this).val();
							$("#selectionChoiceURL").val(selectionChoiceURL);
							}
						});
					}
					
				}
			});
		};

		
		
		/* Adds Print button to container
		----------------------------------------------------*/
		$(".printButtonContainer").show();
		
		

		/* Default Error Messaging Behaviour
		----------------------------------------------------*/
		$("ul.formErrors li a").live("click", function() {
		
			//Find the anchor target that this error links to
			var anchorTarget = $(this).attr("href");
			
			//strip off everything before the "#"
			anchorTarget = anchorTarget.substr(anchorTarget.indexOf("#"));
			
			$(anchorTarget).scrollTo({speed: "slow"});
			
			//Set focus to the field that the label represents and select any text that may be inside
			$("#"+$(anchorTarget).attr("for")).trigger("focus").trigger("select");
			
			return false;
		
		});
		
		
		
		/* Sign-In
		-------------------------------------------------*/
		(function() {
		
			var submitLoginForm = false;
			var frmUserLogin = $("#frmUserLogin");

			frmUserLogin.find("#btnLoginSubmitEmailVerification").unbind("click").bind("click", function(event) {
			
				event.preventDefault();
				var submitButton = $("#btnLoginSubmitEmailVerification").clone(true);
				
				var formPathEmailVerification = frmUserLogin.attr("action");
				
				// Email validation
				var signUpEmailFormFields = {
					emailAddress: {
						name: "txtEmail",
						type: "emailAddress",
						required: true,
						emptyErrorMessage: Sprint.fn.getContentString("formFieldErrors.emailAddressEmpty"),
						invalidErrorMessage: Sprint.fn.getContentString("formFieldErrors.emailAddressInvalid")
					}
				};
				
				var dataToValidate = Sprint.fn.cloneObject(signUpEmailFormFields);
				var validForm = Sprint.fn.validateForm(frmUserLogin, signUpEmailFormFields);
				
				if(validForm == true) { // Email validation passed.
					
					$.ajax({
						data: frmUserLogin.serialize() + "&emailVerification=true",
						type: "POST",
						url: formPathEmailVerification,
						dataType: "json",
						
						success: function(data) {
							if (data.validated) {
								$.get(data.nextPage, function(signin_content) {
								
									var header = $("#navUser").find("#userLogin");
									header.find("#userLoginContent").remove();
									header.append($(signin_content));
									
									header.find(".formErrors").remove();
									header.find(".updateMessage").remove();
									
									// Show success message
									var updateMessage = $("<div class=\"updateMessage\"><img class=\"messageIcon\" src=\"/global/images/icons/ico_advantages_med.gif\" alt=\"Success\" /><div class=\"updateText\">"+data.validationMessage+"</div></div>");
									updateMessage.prependTo(header.find("#frmUserLogin fieldset"));
									
									var submitParent = header.find("div.buttons");
									frmUserLogin.find("#btnLoginSubmitEmailVerification").createHighResButtons();
										
								}); // end get
							} 
							else { // !data.validated
							
								// Remove any current success/error messages
								$("#navUser").find("#userLogin").find(".updateMessage").remove();
								$("#navUser").find("#userLogin").find(".formErrors").remove();
								
								$("#frmUserLogin").showFormErrors({
									errorData: {
										txtEmailDL: {
											name: "txtEmail",
											errorMessage: data.errorMessage
										}
									},
									summaryAnchor: $("#navUser").find("#userLogin").find("#verificationErrors"),
									scrollToSummary: false,
									showInline: false
								});
							}
						},
						error: Sprint.fn.ajaxError
					}); // End ajax
					
				} // validForm == false
				else {
					
					//Remove previous error messages.
					$("#navUser").find("#userLogin").find(".formErrors").remove();
					$("#navUser").find("#userLogin").find(".error").removeClass("error");
					$("#navUser").find("#userLogin").find(".updateMessage").remove();
					
					frmUserLogin.showFormErrors({
                        showInline: false,
                        summaryAnchor: $("#navUser").find("#userLogin").find("#verificationErrors"),
                        showSummary: true,
                        errorData: validForm
                    });
                    return false;
				}
			
			});
		
			function signinValidationHandler(sForm) {
				var fields = {
					txtLoginUsername: {
						name: "USER",
						type: "legacyUsername",
						required: true,
						emptyErrorMessage: Sprint.fn.getContentString("signInOutErrors.usernameEmpty"),
						invalidErrorMessage: Sprint.fn.getContentString("signInOutErrors.usernameInvalid"),
						customValidationRule: function(field) {
							var validUserName = true;
							var fieldValue = field.val();
							var baseRule = /^.{1,33}$/;
							//Test to see if the field value passes the base ruleset OR if it passes the email address test
							return (baseRule.test(fieldValue) || Sprint.formFieldTypes.emailAddress.test(fieldValue));
						}
					},
					txtLoginPassword: {
						name: "PASSWORD",
						type: "password",
						required: true,
						emptyErrorMessage: Sprint.fn.getContentString("signInOutErrors.passwordEmpty"),
						invalidErrorMessage: Sprint.fn.getContentString("signInOutErrors.passwordInvalid"),
						customValidationRule: function(field) {
							var validUserName = true;					
							var fieldValue = field.val();
							var baseRule = /^.{6,33}$/;					
							//Test to see if the field value passes the base ruleset OR if it passes the email address test
							return (baseRule.test(fieldValue));
						}
					}
				};
				
				//var form = $("#frmUserLogin");
				var validation = Sprint.fn.validateForm(sForm, fields);
				
				sForm.find("label.error").remove();
				sForm.find("input.error").removeClass("error");
				$('#signInDeepLinkModal form').wrapInner('<fieldset />');
				/* BEGIN: Tech Implementation for loading spinner while logining in */
				var loadingHt = $('#frmUserLogin > fieldset').height()+'px';
				var loadingMarTop = ($('#frmUserLogin > fieldset').height()/4 - 13)+'px';
				var loadingDiv = '<div id="signInLoadingWindow" style="display:none; height:'+loadingHt+'; text-align:center;"><div style="margin-top:'+loadingMarTop+';" ><p>Please wait while we load all of your account details. This may take a minute for larger accounts.</p></div></div>';
				$('#frmUserLogin').append(loadingDiv);
				$('#frmUserLogin').find("#signInLoadingWindow div").prepend(loadingImageGlobal);
				/* END: Tech Implementation for loading spinner while logining in */

				if (typeof(validation) != "boolean") {
					sForm.showFormErrors({
						errorData: validation,
						showInline: true,
						scrollToSummary: false
					});
					
					return false;
				}
				/* BEGIN: Tech Implementation for loading spinner while logining in */
				if($('#frmUserLogin').length > 0){
					$('#frmUserLogin #signInLoadingWindow').show();
					$('#frmUserLogin > fieldset').hide();
				}
				/* END: Tech Implementation for loading spinner while logining in */
				sForm.unbind("submit").submit();
				return true;
			}
			
			//Intercept Pages, Sign In Handler

			$.fn.signinValidationHandler = function (settings) {
				$.extend(settings);
				signinValidationHandler(settings.form);
			}
			
			/* This function has been modified as per tech instructions to check SMAUTHREASON contact person Narasimha Reddy [nreddy2@sapient.com] */
			$(window).bind("load", function() {
				var browserURL = window.location.href;
				var querystring = Sprint.fn.getQueryString(String(browserURL));
				if (querystring != "") {
					if(browserURL.indexOf('index_c.html') != -1 || browserURL.indexOf('index_b.html') != -1 || browserURL.indexOf('index_p.html') != -1) {
						smAuth = Sprint.fn.getURLParameter(querystring, "SMAUTHREASON");
						if (smAuth == "0") {
							clearTimeout(fredTimeOut);
							$("#frmUserLogin").prepend('<ul class="formErrors"><li><a href="#txtLoginUsername">'+Sprint.fn.getContentString("userLoginDisclosure.errorMsg")+'</a></li></ul>');
							if($('#userLogin').hasClass('disclosureClosed')) {
								$('#signInLink').trigger('click');
							}
						}
					}
				}
			});
			
			frmUserLogin.find("#btnLoginSubmit").unbind("click").bind("click",function() {
				signinValidationHandler(frmUserLogin);
			});
			frmUserLogin.bind("submit",function(event) {
				event.preventDefault();
				frmUserLogin.find("#btnLoginSubmit").trigger("click");
			});
		
			$("#userLoginContent").addRoundedCorners();
				
			var userLogin = $("#userLogin");
			var signInLink = $("#signInLink");
			var signInLinkOriginalWidth = signInLink.width();

			var showImmediately = false;
			signInLink.data("isAnimating", false);

			//Show fred immediately if requested, or for first time visitors on the home page
			if (userLogin.hasClass("startOpen") || $("#sprintHome.firstTimeVisitor").length > 0) {
				showImmediately = true;
			}
			
			var fredTimeOut = setTimeout(function() {
				if($("#userLogin").hasClass("disclosureOpen")) {
					$("#signInLink").trigger("click");
					showImmediately = false;
					clearTimeout(fredTimeOut);
				}	
			}, 1000);
			
			$("#userLogin #txtLoginUsername, #userLogin #txtLoginPassword").bind("focus", function(){
				$("#userLogin #txtLoginUsername, #userLogin #txtLoginPassword").bind("keypress", function(){
					clearTimeout(fredTimeOut);
				});
			});
			
			//Don't auto-hide fred if the login form has errors
			if (userLogin.find(".error, .formErrors").length > 0) {
				clearTimeout(fredTimeOut);
			}
			
			var startClosed = true;
			
			if (showImmediately) {
				startClosed = false;
			}
		
			userLogin.disclosure({
				startClosed:     startClosed,
				titleClickable:  false,
				speed:           "fast",
				openedText:      Sprint.fn.getContentString("userLoginDisclosure.openedText"),
				closedText:      Sprint.fn.getContentString("userLoginDisclosure.closedText"),
				
				openCallback:    function(event) {
					userLogin.addShim(300); //Add an iframe shim (for IE6)
					function removeShim(event) {
						userLogin.removeShim(); //Remove iframe shim (for IE6)
						
						//Once the shim has been removed, get rid of the click function
						userLogin.find(".disclosureToggle").unbind("click", removeShim);
						
						// TECH IMPLEMENTATION
						if (typeof(TeaLeaf) != "undefined" &&  typeof(TeaLeaf.Client) != "undefined") {
							TeaLeaf.Client.tlAddEvent(event);
						}
					}
					
					// Set the focus on the user name field once open.
					userLogin.find("#txtLoginUsername").focus();
					
					userLogin.find(".disclosureToggle").bind("click", removeShim);
					
					sprintHomePageModuleOpen = true; //Disable promo animation on the home page

				},
				
				closeCallback:   function() {
					var navButton = signInLink.parent().parent();
					userLogin.hide();
					navButton.removeClass("expanded");
					
					if(signInLink.data("isAnimating") == false){
						signInLink.data("isAnimating", true);
						signInLink.animate({width: signInLinkOriginalWidth},"normal",function(){
						
							//toggle animation flag
							signInLink.data("isAnimating", false);
						});
					}
					
					sprintHomePageModuleOpen = false; //Re-enable promo animation on the home page
				}
				
			}).hide();
		
			
			signInLink.bind("click", function(event) {
											  						  
				//$(this).parent().width($(this).outerWidth());
				
				//signInLink.stop(true,true);
				
				if(signInLink.data("isAnimating") == false){
					//toggle animation flag
					signInLink.data("isAnimating", true);
					
					if ($(this).is(".disabled")) return false;
					
					var navButton = signInLink.parent().parent();
					
					var animationSpeed = "normal";
					
					if (showImmediately) {
						animationSpeed = 0;
					}
		
					var sWidth = "226px";
	                if (signInLink.hasClass(".signInCookied")) sWidth = signInLink.width();

	                signInLink.animate({width: sWidth}, animationSpeed, function() {
	                    navButton.addClass("expanded");
	                    userLogin.show();
	                    if (!showImmediately) {
	                        userLogin.find(".disclosureToggle").trigger("click");
	                    } else {
	                        // Set the focus on the user name field once open.
	                        userLogin.find("#txtLoginUsername").focus();
	                    }

	                    showImmediately = false; //Reset flag so that it's only shown immediately on page load.
	                    
	                    //toggle animation flag now that animation is complete
	                    signInLink.data("isAnimating",false);
	                });
	                
					// TECH IMPLEMENTATION
					if (typeof(TeaLeaf) != "undefined" &&  typeof(TeaLeaf.Client) != "undefined") {
						TeaLeaf.Client.tlAddEvent(event);
					}
	                
				}
				
				return false;
			});
			
			//Show fred immediately if needed
			if (showImmediately) {
				signInLink.trigger("click");
			}
			
			$("#navUser .cookiedUser a.signInCookied").bind("click", function(event) {
				
				event.preventDefault();
				
				var navButton = $(this).parent().parent();
			
				if (navButton.hasClass("expanded")) {
					navButton.removeClass("expanded");
					userLogin.find(".disclosureToggle").trigger("click");
				}
				else {
					navButton.addClass("expanded");
					userLogin.show();
					userLogin.find(".disclosureToggle").trigger("click");
				}
				
				return false;
				
			});
		
		})();



		/* Signed In User Nav
		-------------------------------------------------*/
		(function() {
		
			var userLoggedIn = $("#userLoggedIn");
			var signOutLink = $("#signOutLink");
			var navUser = $("#navUser");
			var loggedInUserLink = navUser.find("li.loggedInUser a");
		
			$("#userLoggedInContent").addRoundedCorners();
			userLoggedIn.hide();
			
  			
			loggedInUserLink.bind("click", function(event) {
				
				event.preventDefault();
				
				var navButton = loggedInUserLink.parent().parent();
				var hasExpandedClass = navButton.hasClass("expanded");
				
				// expanded class should always be added first and removed last
				if (!hasExpandedClass) {
					navButton.addClass("expanded");
					
					sprintHomePageModuleOpen = true; //Disable promo animation on the home page
				}
				userLoggedIn.slideToggle("fast", function() {
					if (hasExpandedClass) {
						navButton.removeClass("expanded");
						
						sprintHomePageModuleOpen = false; //Re-enable promo animation on the home page
					}
				});
			});
			
			//DE-SCOPING: if the user has items in their cart and they have authenticated, prevent them from clicking any of the links in the tabbed content layers.
			$("#userLoggedInContent.disabled ul li a").unbind("click").bind("click", function(event) {
				event.preventDefault();
			});
			//END DE-SCOPING
			
		
		})();
				
		
		/* Account Flipper - When switch betwen multiple accounts
		----------------------------------------------------------*/
		(function() {
			
			/*var selUserAccount = $("#selUserAccount");
			
			//DE-SCOPING: added stored value vairable
			var originalSelectValue = selUserAccount;
			//END DE-SCOPING

			selUserAccount.bind("change", function(event) {
				
				//DE-SCOPING: if clause added for de-scoping purposes. If this is ever re-scoped, use the else case from this section only.
				if (selUserAccount.hasClass("disabled")) {
					selUserAccount.val(originalSelectValue);
				}
				else {
					selUserAccount.parents("form:first").submit();
				}

			});*/
                         //Merged from 10.4
                        $("#selUserAccount").bind("change", function(event) {			
				var classNameOfOption = $("#selUserAccount").find("option:selected").attr('class');
				if(classNameOfOption == 'hiddenVarUrl'){
					var optionValue = 'url_'+$("#selUserAccount").val();
					$(this).parents("form:first").attr('action', $('#'+optionValue).val());
				}
				$(this).parents("form:first").submit();			 
			});
		
		})();
		
		/* MyTools Tabs in Global Fred
		-----------------------------------------------------------*/
		$(function() {
			
			// Initalize
			var tabLinks = $("#navUser ul.myToolsTabs li a");
			
			
			// Hide content for all tabs except the selected one
			tabLinks.each(function() {
				
				var tabLink = $(this);
								   
				if (!tabLink.parent().hasClass("selected")) {
					$(tabLink.attr("href")).hide();
				}
			});
			
				   
			// Add click event handler to all tabs
			tabLinks.bind("click", function(event) {
				
				event.preventDefault();
				
				var tabLink = $(this);
				var tab = tabLink.parent();
				
				// Don't process a tab that's already selected
				if (tab.hasClass("selected")) {
					return false;	
				}
				
				// Remove selected class from other tabs
				tab.parent().find("li.selected").removeClass("selected");
				
				// Add class to the selected tab
				tab.addClass("selected");
				
				// Hide content for other tabs
				$("#navUser #myTools .myToolsTabContent").hide();
				
				// Show content for selected tab
				$(tabLink.attr("href")).show();
			
			});
		});
		
		/* Open Link in New Window
		-------------------------------------------------------*/
		$.fn.popupWindow = function(instanceSettings){
			
			return this.each(function(){		
			
				$(this).click(function(){
				
					$.fn.popupWindow.defaultSettings = {
						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)}.
					};
							
					var optionsString = "{"+$(this).attr('popup')+"}";
					var optionsObj = eval( "("+ optionsString +")" );

					settings = $.extend({}, $.fn.popupWindow.defaultSettings, optionsObj || 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;
					
					if(settings.centerScreen){
						var centeredY, centeredX;
						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;
				});	
			});	
		};
		
		/* Example usage #1: All links with attribute 'popupLink' will open in new window with default settings */
		$(function() {
			$("a[popup]").popupWindow({});
		});
		
		/* Change Location Modal 
		-------------------------------------------------------*/
		$(function() {
			
			// Display modal dialog
			$("a.showModalChangeLocation").bind("click", function(event) {
				
				event.preventDefault();
				
				var locationModal = $("#changeLocationModal");
				
				locationModal.openModal({
					width:275,
					openCallback: function() {
						// Make sure sIFR is properly applied
						locationModal.setupComponents({buttons:false});
					}
				});
			});
			
			
			// Change location submit handling
			$("#frmChangeLocation").bind("submit", function(event) {
															
				event.preventDefault();
				$("#btnChangeLocation").trigger("click", event);
			
			});
			
			
			$("#btnChangeLocation").unbind("click").bind("click", function(event) {
				event.preventDefault();
				
				// When we change location we need to submit the new location to the store locator
				$("#txtFindStoreAddress").val($("#txtNewLocation").val());
				$("#btnFindStore").trigger("click");
				
				// Once submitted we can close the modal
				$("#changeLocationModal").closeModal();
				
			});
		});


		/* Find a Store Form (in the Contact Us module in the side bar)
		-------------------------------------------------*/
		(function() {
		
			var frmFindStore = $("#frmFindStore");
			
			if (frmFindStore.length > 0) {
			
				var locationDisplay = $("#locationDisplay");
				
				locationDisplay.hide();
				
				locationDisplay.find("ul.storeLocatorLink li a").bind("click", function(event) {
				
					event.preventDefault();
					
					if ($(this).is(".changeLocation")) {
						locationDisplay.hide();
						frmFindStore.parent().show();
						
						frmFindStore.find("#btnFindStore").removeClass("disabled");
						
						frmFindStore.find("#txtFindStoreAddress").focus().select();
					}
					else if ($(this).is(".seeAll")) {
						
						/*
						$("#frmViewAllStores").find("input[name='r']").val(frmFindStore.find("#hidFindStoreRadius").val());
						$("#frmViewAllStores").find("input[name='addr']").val($.trim(frmFindStore.find("#txtFindStoreAddress").val()));						
						
						$("#frmViewAllStores").trigger("submit");						
						*/
					}
				
				});
				
				frmFindStore.bind("submit", function(event) {
				
					event.preventDefault();
					
					frmFindStore.find("#btnFindStore").trigger("click");
				
				});
			
				function findStores(event, supressErrors){
					if(event){	event.preventDefault();	}
					
					if( supressErrors==null ){ supressErrors=false;}
					
					if ($(this).is(".disabled")) {
						return false;
					}
					
					var searchString = $.trim(frmFindStore.find("#txtFindStoreAddress").val());
					
					$(this).addClass("disabled");
				
					
					var errorFunction = Sprint.fn.ajaxError;
					if(supressErrors){
						errorFunction = function(){return true};
					}
					
					//Send an AJAX request to get the store data for the address entered.
					$.ajax({
					
						url: frmFindStore.attr("action"),
						
						data: {
							addr: searchString,
							r: frmFindStore.find("#hidFindStoreRadius").val()
						},
						
						type: "GET",
						
						dataType: "json",
						
						success: function(data) {
						
							//Remove any previous results
							locationDisplay.find(".storeLocation").remove();
							locationDisplay.find(".errorHolder").remove();
						
							if (data.error && data.error[0] && data.error[0].noSearchKeyFound) {
								$('#locationDisplay').hide();
								$('#contactFind').show();
							}
							else if (data.stores) {
								var outputString = "";
							
								//No errors, output the first 2 results
								$.each(data.stores, function(i) {
									if (i >= 2) {
										return;
									}
									
									//Make an Appointment change
									var appointment = "";
									if (data.stores[i] && data.stores[i].appointment && data.stores[i].appointment.length > 0) {
										appointment = "<div><a href=" + data.stores[i].appointment + " target=\"_blank\">Make an Appointment</a></div>";
									}

									outputString = outputString + "<div class=\"storeLocation\"><h5>" + data.stores[i].name + "</h5><div class=\"locationTelephone\"><em><b>" + data.stores[i].phone + "</b></em></div><div class=\"locationAddress01\">" + data.stores[i].address + "</div>" + appointment + "</div>";									
								});
							
								locationDisplay.prepend(outputString);
								frmFindStore.parent().hide();							
								locationDisplay.show();
							}
						},
						error: function() {
							locationDisplay.find(".storeLocation").remove();
							locationDisplay.find(".errorHolder").remove();
							locationDisplay.prepend('<div class="errorHolder"><ul class="formErrors"><li>Please enter valid Street, city, state, and/or ZIP</li></ul></div>');
							frmFindStore.parent().hide();

							locationDisplay.show();
							
							// Omniture tracking the error message when go is clicked
							var omnitureCalls = $('OmnitureCalls');
							if (omnitureCalls.length > 0 && omnitureCalls.val() == "false") {
								Analytics.Support.trackError('user', 'Please enter valid Street, city, state, and/or ZIP');
							}
						}
					});
						
				}//end of findStores
			
				frmFindStore.find("#btnFindStore").unbind("click").bind("click", function(event) {
					var checkNullVal = $.trim(frmFindStore.find("#txtFindStoreAddress").val());
					var omnitureCalls = $('#OmnitureCalls');
					
					if (omnitureCalls.length > 0 && omnitureCalls.val() == "false") {
						Analytics.Support.trackGoStoreSelector();
					}

					if (checkNullVal != "") {
						findStores(event);
					} else {
						event.preventDefault();

						locationDisplay.find(".storeLocation").remove();
						locationDisplay.find(".errorHolder").remove();
						locationDisplay.prepend('<div class="errorHolder"><ul class="formErrors"><li>Oops, you forgot to enter your address</li></ul></div>');
						frmFindStore.parent().hide();
						locationDisplay.show();
						
						// Omniture tracking the error message when go is clicked
						if (typeof(Analytics) !== "undefined") {
							if (omnitureCalls.length > 0 && omnitureCalls.val() == "false") {
								Analytics.Support.trackError('user', 'Oops, you forgot to enter your address');
							}
						}
					}
				});
			
				$(window).load( function(){
					//initialize the store locator, but supress error messages
					findStores(null, true);
				});
			}
			

		
		})();
		
		
		
		/* Form Enter-key support for Internet Explorer (because buttons are hidden, enter doesn't submit the form, this fixes that) */
		if ($.browser.msie) {
			$(document).bind("keydown", function(event) {
				if (event.keyCode == 13) {
				
					if ($(event.target).is("textarea")) return;
					sourceElement = $(event.srcElement);
					parentForm = sourceElement.parents("form");
				
					if (parentForm.length > 0) {
					
						event.preventDefault();
						
						//Submit this item's parent form.
						parentForm.trigger("submit");
					
					}

				}
			});			
		}



		//Setup link handling for any "forgot password" links
		(function() {
		
			var forgotPasswordFields = {
				txtForgotPasswordUsername: {
					name: "txtForgotPasswordUsername",
					type: "legacyUsername",
					required: true,
					emptyErrorMessage: Sprint.fn.getContentString("formFieldErrors.forgotPasswordUsernameEmpty"),
					invalidErrorMessage: Sprint.fn.getContentString("formFieldErrors.usernameInvalid"),
					
					customValidationRule: function(field) {
		
						var validUserName = true;
						
						var fieldValue = field.val();
					
						var baseRule = /^[a-zA-Z0-9\.\-_]{1,33}$/;
						
						//Test to see if the field value passes the base ruleset OR if it passes the email address test
						if (!baseRule.test(fieldValue) && !Sprint.formFieldTypes.emailAddress.test(fieldValue)) {
							validUserName = false;
						}			
						
						return validUserName;
					
					}
				},
				radForgotPasswordDestinationEmail: {
					name: "radForgotPasswordDestinationEmail",
					type: "radioButton",
					required: true,
					emptyErrorMessage: Sprint.fn.getContentString("forgotPasswordErrors.passwordDestinationEmpty")
				},
				radForgotPasswordDestinationEmail: {
					name: "radForgotPasswordDestinationText",
					type: "radioButton",
					required: true,
					emptyErrorMessage: Sprint.fn.getContentString("forgotPasswordErrors.passwordDestinationEmpty")
				},
				txtForgotPasswordAnswer: {
					name: "txtForgotPasswordAnswer",
					type: "securityAnswer",
					required: false,
					invalidErrorMessage: Sprint.fn.getContentString("forgotPasswordErrors.securityAnswerInvalid"),
					customValidationRule: function(field) {
						var fieldValue = field.val();
						var secondaryFieldValue = $("#txtForgotPasswordPin").val();
						
						if (fieldValue != "" && secondaryFieldValue == "") {
							forgotPasswordFields.txtForgotPasswordPin.required = false;
							if(fieldValue.length > 30){
								// can't be greater than 30 characters
								return false;
							} else {
								return Sprint.formFieldTypes.securityAnswer.test(fieldValue);
							}
						} else {
							return true;
						}
					}
				},
				txtForgotPasswordPin: {
					name: "txtForgotPasswordPin",
					type: "PIN",
					required: true,
					emptyErrorMessage: Sprint.fn.getContentString("forgotPasswordErrors.pinAndAnswerEmpty"),
					invalidErrorMessage: Sprint.fn.getContentString("forgotPasswordErrors.pinInvalid")
				},
				txtForgotPasswordCode: {
					name: "txtForgotPasswordCode",
					type: "ESN,MEID,BAN,phoneNumber",
					required: true,
					emptyErrorMessage: Sprint.fn.getContentString("forgotPasswordErrors.passwordCodeEmpty"),
					invalidErrorMessage: Sprint.fn.getContentString("forgotPasswordErrors.passwordCodeInvalid")
				},
				txtForgotPasswordNewPassword: {
					name: "txtForgotPasswordNewPassword",
					type: "password_11_3",
					required: true,
					emptyErrorMessage: Sprint.fn.getContentString("forgotPasswordErrors.newPasswordEmpty"),
					invalidErrorMessage: Sprint.fn.getContentString("forgotPasswordErrors.newPasswordInvalid_11_3")
				},
				txtForgotPasswordConfirmPassword: {
					name: "txtForgotPasswordConfirmPassword",
					type: "match",
					required: true,
					mustMatch: "txtForgotPasswordNewPassword",
					emptyErrorMessage: Sprint.fn.getContentString("forgotPasswordErrors.newPasswordConfirmEmpty"),
					invalidErrorMessage: Sprint.fn.getContentString("forgotPasswordErrors.newPasswordConfirmInvalid")
				},
				txtForgotPasswordEmail: {
					name: "txtForgotPasswordEmail",
					type: "emailAddress",
					required: false,
					invalidErrorMessage: Sprint.fn.getContentString("formFieldErrors.emailAddressInvalid"),
					customValidationRule: function(field) {
						var fieldValue = field.val();
						var secondaryFieldValue = $("#txtForgotPasswordPhone").val();
						
						if (fieldValue != "" && secondaryFieldValue == "") {
							forgotPasswordFields.txtForgotPasswordPhone.required = false;
							return Sprint.formFieldTypes.emailAddress.test(fieldValue);
						} else {
							return true;
						}
					}
				},
				txtForgotPasswordPhone: {
					name: "txtForgotPasswordPhone",
					type: "phoneNumber",
					required: true,
					emptyErrorMessage: Sprint.fn.getContentString("forgotPasswordErrors.phoneNumberAndEmailEmpty"),
					invalidErrorMessage: Sprint.fn.getContentString("formFieldErrors.phoneNumberInvalid")
				},txtBillingZip: {
					name: "txtBillingZip",
					type: "freeZipCode",
					required: true,
					emptyErrorMessage: Sprint.fn.getContentString("formFieldErrors.zipCodeEmpty"),
					invalidErrorMessage: Sprint.fn.getContentString("formFieldErrors.freeZipCodeInvalid")
				},
				txtSSN: {
					name: "txtSSN",
					type: "textArea",
					required: true,
					emptyErrorMessage: Sprint.fn.getContentString("shop.checkout.accountContactInformation.ssnEmpty"),
					invalidErrorMessage: Sprint.fn.getContentString("shop.checkout.accountContactInformation.ssnInvalid")
				},
				txtForgotPasswordPin: {
					name: "txtForgotPasswordPin",
					type: "PIN",
					required: true,
					emptyErrorMessage: Sprint.fn.getContentString("forgotPasswordErrors.pinAndAnswerEmpty"),
					invalidErrorMessage: Sprint.fn.getContentString("forgotPasswordErrors.pinInvalid")
				},
				txtForgotPasswordAnswer: {
					name: "txtForgotPasswordAnswer",
					type: "securityAnswer",
					required: false,
					invalidErrorMessage: Sprint.fn.getContentString("forgotPasswordErrors.securityAnswerInvalid"),
					customValidationRule: function(field) {
						var fieldValue = field.val();
						var secondaryFieldValue = $("#txtForgotPasswordPin").val();
						
						if (fieldValue != "" && secondaryFieldValue == "") {
							forgotPasswordFields.txtForgotPasswordPin.required = false;
							if(fieldValue.length > 30){
								// can't be greater than 30 characters
								return false;
							} else {
								return Sprint.formFieldTypes.securityAnswer.test(fieldValue);
							}
						} else {
							return true;
						}
					}
				},
				txtSecBillingZip: {
					name: "txtSecBillingZip",
					type: "freeZipCode",
					required: true,
					emptyErrorMessage: Sprint.fn.getContentString("formFieldErrors.zipCodeEmpty"),
					invalidErrorMessage: Sprint.fn.getContentString("formFieldErrors.freeZipCodeInvalid")
				},
				txtSecSSN: {
					name: "txtSecSSN",
					type: "textArea",
					required: true,
					emptyErrorMessage: Sprint.fn.getContentString("shop.checkout.accountContactInformation.ssnEmpty"),
					invalidErrorMessage: Sprint.fn.getContentString("shop.checkout.accountContactInformation.ssnInvalid")
				}
				
			};
			var forgotPasswordAccountFields = {
				txtBillingZip: {
					name: "txtBillingZip",
					type: "freeZipCode",
					required: true,
					emptyErrorMessage: Sprint.fn.getContentString("formFieldErrors.zipCodeEmpty"),
					invalidErrorMessage: Sprint.fn.getContentString("formFieldErrors.freeZipCodeInvalid")
				},
				txtSSN: {
					name: "txtSSN",
					type: "textArea",
					required: true,
					emptyErrorMessage: Sprint.fn.getContentString("shop.checkout.accountContactInformation.ssnEmpty"),
					invalidErrorMessage: Sprint.fn.getContentString("shop.checkout.accountContactInformation.ssnInvalid")
				},
				txtForgotPasswordPin: {
					name: "txtForgotPasswordPin",
					type: "PIN",
					required: true,
					emptyErrorMessage: Sprint.fn.getContentString("forgotPasswordErrors.pinAndAnswerEmpty"),
					invalidErrorMessage: Sprint.fn.getContentString("forgotPasswordErrors.pinInvalid")
				}
			};
			var forgotPasswordSecureFields = {
				txtForgotPasswordAnswer: {
					name: "txtForgotPasswordAnswer",
					type: "securityAnswer",
					required: false,
					invalidErrorMessage: Sprint.fn.getContentString("forgotPasswordErrors.securityAnswerInvalid"),
					customValidationRule: function(field) {
						var fieldValue = field.val();
						var secondaryFieldValue = $("#txtForgotPasswordPin").val();
						
						if (fieldValue != "" && secondaryFieldValue == "") {
							forgotPasswordFields.txtForgotPasswordPin.required = false;
							if(fieldValue.length > 30){
								// can't be greater than 30 characters
								return false;
							} else {
								return Sprint.formFieldTypes.securityAnswer.test(fieldValue);
							}
						} else {
							return true;
						}
					}
				},
				txtSecBillingZip: {
					name: "txtSecBillingZip",
					type: "freeZipCode",
					required: true,
					emptyErrorMessage: Sprint.fn.getContentString("formFieldErrors.zipCodeEmpty"),
					invalidErrorMessage: Sprint.fn.getContentString("formFieldErrors.freeZipCodeInvalid")
				},
				txtSecSSN: {
					name: "txtSecSSN",
					type: "textArea",
					required: true,
					emptyErrorMessage: Sprint.fn.getContentString("shop.checkout.accountContactInformation.ssnEmpty"),
					invalidErrorMessage: Sprint.fn.getContentString("shop.checkout.accountContactInformation.ssnInvalid")
				}
			};
			// Bind the cancel button to trigger the click event on the modal chrome close button.
			function bindCancelButton() {
				$("#forgotPasswordModal").find("#btnForgotPasswordCancel").bind("click", function(event) {
					event.preventDefault();
					Sprint.modal.elem.closeModal();
					
					// To determine when 'Done' button was pressed, we check if 'button1_converted'
					// class is present, which distiguishes it from 'Cancel' buttons.
					if ($(this).hasClass('button1_converted')) {
						// do a soft variable get and then redirect if it has value
						var redirectUrl = window['tempPasswordResetUrl'];
						if (redirectUrl != null && redirectUrl != '') {
							window.location.href = redirectUrl;
						}
					}
				});
				
				//If we're on the "Done" page, make sure that closing the modal through the X button or the ESC key triggers the click event on the "Done" button.
				if ($("#btnForgotPasswordCancel.button1_converted").length > 0) {
					//Make sure clicking the X button, or hitting escape triggers the click event on the Done button.
					$("#modalHolder a.closeModal").unbind("click").bind("click", function(e) {
						e.preventDefault();
						$("#btnForgotPasswordCancel").trigger("click");
					});
					$(document).unbind("keydown").bind("keydown", function(e) {
						if (e.keyCode == 27) {
							e.preventDefault();
							$("#btnForgotPasswordCancel").trigger("click");
						}
					});
				}
			}
			//Bind forgotSubmit function for validating the accountpin and security answer only
			function bindForgotSubmitButton(){
				var forgotPasswordModal = $("#forgotPasswordModal");
				var frmForgotPassword   = forgotPasswordModal.find("#frmForgotPassword");
				
				forgotPasswordModal.find("#btnForgotPwdAccountSubmit,#btnForgotPwdSecureSubmit").unbind("click").bind("click", function(event) {
					event.preventDefault();
					var $this = $(this);
					var enableSnare = true;
					// if snare is enabled then fetch snare results
					if (enableSnare) {
					
						//fetch results from the iframe
						var blackBoxValue = Sprint.getBBdata();
					} else {
					
						//create dummy object to bypass snare
						var blackBoxValue = {blackbox:"unavailable"};
					}
										//if($("#txtForgotPasswordAnswer").length >= 1){
						/*if(blackBoxValue.blackbox == 'undefined'){
							$(this).a
						}
						setTimeout(function() {
						}*/
					
					//}
					// Client-side validation
					var validationRules = Sprint.fn.cloneObject(forgotPasswordFields);
					if($this.attr('id') == 'btnForgotPwdAccountSubmit'){
						
						var validForm = Sprint.fn.validateForm(forgotPasswordModal.find("#frmForgotPassword"), forgotPasswordAccountFields);
					} else {
						var validForm = Sprint.fn.validateForm(forgotPasswordModal.find("#frmForgotPassword"), forgotPasswordSecureFields);
					}
				
					if (validForm == true) {
						//ajaxData += "&ioBlackBox="+blackBoxValue.blackbox;
						if($this.attr('id') == 'btnForgotPwdAccountSubmit'){
							var ajaxData = $("div.accountForgotleft input.text").serialize();
						} else {
							var ajaxData = "txtBillingZip="+$("#txtSecBillingZip").val()+"&txtSSN="+$("#txtSecSSN").val()+"&"+$("#txtForgotPasswordAnswer").serialize();
						}
						
						$.ajax({
							data: ajaxData+"&ajax=true&ioBlackBox="+blackBoxValue.blackbox+"&"+$("#hidForgotPasswordState").serialize(),
							url: frmForgotPassword.attr("action"),
							type: "GET",								
							async: false,
							cache: false,
							dataType: "json",
							
							success: function(data) {
								if (data.validated) {
									Sprint.modal.elem.loadModalContent(data.responseUrl, forgotPasswordModal);
									Sprint.modal.elem.sizeModal({width:340});
									bindSubmitButton();
									bindCancelButton();
									bindTabToValidateFields();
									bindEnterToSubmitEvent();
									setFocusToFirstField();
									
									if (data.securityQuestion) {
										forgotPasswordModal.find("span.securityQuestion").text(data.securityQuestion);
									}
									if (data.emailAddress) {
										forgotPasswordModal.find("span.sendToEmail").text(data.emailAddress);
									}
									if (data.phoneNumber) {
										forgotPasswordModal.find("span.sendToPhone").text(data.phoneNumber);
									}

								} else {
									//Remove previous error messages.
									forgotPasswordModal.find(".headerWrapperPrimary").find(".formErrors").remove();
									forgotPasswordModal.find(".error").removeClass("error");
				
									//Form has errors, show messages.
									forgotPasswordModal.find("#frmForgotPassword").showFormErrors({
										errorData: {
											txtValidationCode: {
												name: data.errorField,
												errorMessage: data.errorMessage
											}
										},
										summaryAnchor: forgotPasswordModal.find(".headerWrapperPrimary"),
										showInline: false,
										scrollToSummary: false,
										showErrorLabel: false
									});
								}
							},
														
							error: Sprint.fn.ajaxError	
						});
					} else {
						//Remove previous error messages.
						forgotPasswordModal.find(".headerWrapperPrimary").find(".formErrors").remove();
						forgotPasswordModal.find(".error").removeClass("error");
				
						//Form has errors, show messages.
						forgotPasswordModal.find("#frmForgotPassword").showFormErrors({
							errorData: validForm,
							summaryAnchor: forgotPasswordModal.find(".headerWrapperPrimary"),
							showInline: false,
							scrollToSummary: false,
							showErrorLabel: false
						});
					}
					
					// Reset the validation rules
					forgotPasswordFields = validationRules;
				});
			
			}
			// Bind the submit button to do client-side validation on the form fields, if that passes then
			// call ajax query to get the next page in the flow.
			function bindSubmitButton() {
				var forgotPasswordModal = $("#forgotPasswordModal");
				var frmForgotPassword   = forgotPasswordModal.find("#frmForgotPassword");
				var ajaxData = "ajax=true";
					if($("#snareIframe").length <= 0){
						$("body").append('<iframe id="snareIframe" src="/mysprint/pages/sl/common/snare.jsp" width="0" height="0" scrolling="no" frameborder="no"></iframe>');
					}
					/* Start : Ivoation changes
					---------------------------- */
					
						Sprint.getBBdata = function(){
							
							var bbData = document.getElementById('snareIframe').contentWindow['bb_data'];
							
							if(typeof(bbData) != "undefined" && bbData != false && typeof(bbData) == "object"){
						
							// if snare has completed then submit
								return bbData;
							} else {
								// snare is enabled but bb_data in the iframe is undefined
								return {blackbox:"unavailable"}
							}
						}
					
						
					
					/* End : Ivoation changes
					---------------------------- */
			
				forgotPasswordModal.find("#btnForgotPasswordSubmit").unbind("click").bind("click", function(event) {
					event.preventDefault();

					// Client-side validation
					var validationRules = Sprint.fn.cloneObject(forgotPasswordFields);
					var validForm = Sprint.fn.validateForm(forgotPasswordModal.find("#frmForgotPassword"), forgotPasswordFields);
					if (validForm == true) {
						$.ajax({
							data: ajaxData+"&"+frmForgotPassword.serialize(),
							url: frmForgotPassword.attr("action"),
							type: "GET",								
							async: false,
							cache: false,
							dataType: "json",							
							success: function(data) {
								if (data.validated) {
									
									Sprint.modal.elem.loadModalContent(data.responseUrl, forgotPasswordModal);
									
										
										if(data.isSingleBan){
											Sprint.modal.elem.sizeModal({width:750,forgot:true});
											bindForgotSubmitButton();
											
											if(data.zipSSNValidSection){
											
												if(data.pinValidSection){
													Sprint.modal.elem.sizeModal({width:340});
													var invalidForgotPassPIN =  Sprint.fn.getContentString("formFieldErrors.invalidForgotPassPIN");
													$("div.accountForgotleft, div.accountForgotRight").hide();
													forgotPasswordModal.find("div.headerWrapperPrimary").append('<ul class="formErrors"><li>'+invalidForgotPassPIN+'</li></ul>');
													$(".sprint .frmForgotPwd .headerWrapperPrimary").css('width','340px');
												}
												if(data.secQuesValidSection){
													Sprint.modal.elem.sizeModal({width:340});
													$("div.accountForgotRight").hide();

												}
											}else {
												var invalidZipSSNError = Sprint.fn.getContentString("formFieldErrors.invalidZipSSNError");
												$("div.accountForgotleft, div.accountForgotRight").hide();
												forgotPasswordModal.find("div.headerWrapperPrimary").append('<ul class="formErrors"><li>'+invalidZipSSNError+'</li></ul>');
												Sprint.modal.elem.sizeModal({width:340});
												$(".sprint .frmForgotPwd .headerWrapperPrimary").css('width','340px');
											}
											
										} else {
											bindSubmitButton();
										}
										
										
										bindCancelButton();
										bindTabToValidateFields();
										bindEnterToSubmitEvent();
										setFocusToFirstField();
										if (data.securityQuestion) {
											forgotPasswordModal.find("span.securityQuestion").text(data.securityQuestion);
										}
										if (data.emailAddress) {
											forgotPasswordModal.find("span.sendToEmail").text(data.emailAddress);
										}
										if (data.phoneNumber) {
											forgotPasswordModal.find("span.sendToPhone").text(data.phoneNumber);
										}
									
								} else {
									//Remove previous error messages.
									forgotPasswordModal.find(".headerWrapperPrimary").find(".formErrors").remove();
									forgotPasswordModal.find(".error").removeClass("error");
				
									//Form has errors, show messages.
									forgotPasswordModal.find("#frmForgotPassword").showFormErrors({
										errorData: {
											txtValidationCode: {
												name: data.errorField,
												errorMessage: data.errorMessage
											}
										},
										summaryAnchor: forgotPasswordModal.find(".headerWrapperPrimary"),
										showInline: false,
										scrollToSummary: false
									});
								}
							},
														
							error: Sprint.fn.ajaxError	
						});
					} else {
						//Remove previous error messages.
						forgotPasswordModal.find(".headerWrapperPrimary").find(".formErrors").remove();
						forgotPasswordModal.find(".error").removeClass("error");
				
						//Form has errors, show messages.
						forgotPasswordModal.find("#frmForgotPassword").showFormErrors({
							errorData: validForm,
							summaryAnchor: forgotPasswordModal.find(".headerWrapperPrimary"),
							showInline: false,
							scrollToSummary: false
						});
					}
					
					// Reset the validation rules
					forgotPasswordFields = validationRules;
				});
			}
			
			//Make sure that the form submit goes through the submit button click event
			function bindEnterToSubmitEvent() {
				$("#frmForgotPassword").bind("submit", function(event) {
					event.preventDefault();
					$("#forgotPasswordModal").find("#btnForgotPasswordSubmit").trigger("click");
				});
			}
			
			// Validates form data when user TABs out of a text field 
			function bindTabToValidateFields() {
				
				var forgotPasswordModal = $("#forgotPasswordModal");
				var frmForgotPassword = forgotPasswordModal.find("#frmForgotPassword");
				
				// Bind the keyDown event to all text input fields in the forgot password form
				frmForgotPassword.find("input.text").unbind("keydown").bind("keydown", function(event) {
					
					// Make sure the user pressed the TAB key
					if (event.keyCode == 9) {
						
						// Remove any previous error messages.
						forgotPasswordModal.find(".headerWrapperPrimary").find(".formErrors").remove();
						frmForgotPassword.find("input.error").removeClass("error");
						
						// Client-side validation of the specific field
						var validForm = Sprint.fn.validateForm(frmForgotPassword, {field: forgotPasswordFields[$(this).attr("name")]});

						// Check if form has errors and if so, show error messages.
						if (validForm != true) {
							//Don't show any errors on tab out if we're on the PIN/Security Answer screen as this is a "one or the other" scenario.
							if (!validForm.txtForgotPasswordPin) {
								frmForgotPassword.showFormErrors({
									errorData: validForm,
									summaryAnchor: forgotPasswordModal.find(".headerWrapperPrimary"),
									showInline: false,
									scrollToSummary: false
								});
							}
						}
					}
				});
			}
			
			// Bind the forgot username link to an event that will load content into the modal.
			function bindForgotUsernameLink() {
				$("#forgotPasswordModal").find("a.forgotUsername").unbind("click").bind("click", function(event) {
					event.preventDefault();
					// OMNITURE ANALYTICS CODE
					if (typeof(Analytics) !== "undefined" && typeof(Analytics.eComATG) != "undefined"  && typeof(Analytics.eComATG.screenChangeHelperFunction) != "undefined") {
						Analytics.eComATG.screenChangeHelperFunction("Forgot Username");
					}
					Sprint.modal.elem.loadModalContent("/mysprint/pages/sl/forgotpassword/modals/forgot_username.jsp", $("#forgotPasswordModal"));
					bindCancelButton();
					bindSubmitButton();
					bindTabToValidateFields();
					bindEnterToSubmitEvent();
					setFocusToFirstField();
				});
			}
			
			// Set the focus on the first input field, not the first item which would be the close button.
			function setFocusToFirstField() {
				Sprint.modal.elem.focusFirstElement({
					focusableElements: "input[type!='hidden'], submit, button",
					containFocus: false
				});
			}
			
			// Bind the forgot password link to open the modal and display the contents.
			$("a.forgotPassword").die("click").live("click", function(event) {
				// TEALEAF SESSION TRACKING
				if (typeof(TeaLeaf) != "undefined" &&  typeof(TeaLeaf.Client) != "undefined") {
					TeaLeaf.Client.tlAddEvent(event);
				}
				
				event.preventDefault();
				// OMNITURE ANALYTICS CODE
				if (typeof(Analytics) !== "undefined" && typeof(Analytics.eComATG) != "undefined"  && typeof(Analytics.eComATG.screenChangeHelperFunction) != "undefined") {
					Analytics.eComATG.screenChangeHelperFunction("Forgot Password");
				}
				var modalExists = $("#deepLinkSignIn").length > 0;
				if (Sprint.modal.elem && Sprint.modal.elem.length > 0) {
					$("a.closeModal").trigger("click");
				}
				
				var forgotPasswordModal = $("#forgotPasswordModal");
				
				if (forgotPasswordModal.length < 1) {
					var newModal = $("<div class=\"modal\"></div>");
					forgotPasswordModal = $("<div id=\"forgotPasswordModal\"></div>");
					forgotPasswordModal.appendTo(newModal);
					newModal.appendTo("div.sprint div.body").hide();
				}
				
				// Open the modal from the initial forgot password state
				forgotPasswordModal.openModal({
					ajaxContent: true,
					ajaxPath: "/mysprint/pages/sl/forgotpassword/modals/forgot_password.jsp",
					
					openCallback: function() {
						bindCancelButton();
						bindSubmitButton();
						bindTabToValidateFields();
						bindEnterToSubmitEvent();
						bindForgotUsernameLink();
						setFocusToFirstField();
						if (modalExists) {
							bindDeepLinkEvent();
						}
					}
				});
			});
			
			// Bind the forgot username link to open the modal and display the contents.
			$("div.forgot > a.forgotUsername").die("click").live("click", function(event) {
				// TEALEAF SESSION TRACKING
				if (typeof(TeaLeaf) != "undefined" &&  typeof(TeaLeaf.Client) != "undefined") {
					TeaLeaf.Client.tlAddEvent(event);
				}
				event.preventDefault();
				// OMNITURE ANALYTICS CODE
				if (typeof(Analytics) !== "undefined" && typeof(Analytics.eComATG) != "undefined"  && typeof(Analytics.eComATG.screenChangeHelperFunction) != "undefined") {
					Analytics.eComATG.screenChangeHelperFunction("Forgot Username");
				}
				var modalExists = $("#deepLinkSignIn").length > 0;
				if (Sprint.modal.elem && Sprint.modal.elem.length > 0) {
					$("a.closeModal").trigger("click");
				}
				
				var forgotPasswordModal = $("#forgotPasswordModal");
				
				if (forgotPasswordModal.length < 1) {
					var newModal = $("<div class=\"modal\"></div>");
					forgotPasswordModal = $("<div id=\"forgotPasswordModal\"></div>");
					forgotPasswordModal.appendTo(newModal);
					newModal.appendTo("div.sprint div.body").hide();
				}
				
				// Open the modal from the initial forgot password state
				forgotPasswordModal.openModal({
					ajaxContent: true,
					ajaxPath: "/mysprint/pages/sl/forgotpassword/modals/forgot_username.jsp",
					
					openCallback: function() {
						bindCancelButton();
						bindSubmitButton();
						bindTabToValidateFields();
						bindEnterToSubmitEvent();
						setFocusToFirstField();
						if (modalExists) {
							bindDeepLinkEvent();
						}
					}
				});
			});
			
			/*
				This is the quick fix to solve the cross-domain ajax issue.  When user clicks on forgot password or
				forgot username on the static homepage, ajax call can't be made because it will be a cross-domain call.
				So the quick solution was to redirect to the jsp page with url parameter lForgotPassword or lForgotUsername
				and if either of those exist, the respect modal is triggered.
			*/
			var pageURL = Sprint.fn.getQueryString(window.location.href);
			var launchForgotPassword = Sprint.fn.getURLParameter(pageURL, "lForgotPassword");
			if (launchForgotPassword && launchForgotPassword != undefined)
				$("a.forgotPassword").trigger("click");
				
			var launchForgotUsername = Sprint.fn.getURLParameter(pageURL, "lForgotUsername");
			if (launchForgotUsername && launchForgotUsername != undefined)
				$("div.forgot > a.forgotUsername").trigger("click");
			
			// If the user got to this modal from the deep link signin modal, then closing
			// this modal should re-open the signin modal.
			function bindDeepLinkEvent() {
				$("#modalHolder a.closeModal").unbind("click").bind("click", function(event) {
					event.preventDefault();
					Sprint.modal.elem.closeModal();
					deepLinkSignInModal();
				});
			}
			
			// Check for the reset temporary password link, if it exists then do a trigger
			// on the event, which causes the modal to show.
			$("a.resetTemporaryPassword").unbind("click").bind("click", function(event) {
				event.preventDefault();
				
				var resetPasswordModal = $("#forgotPasswordModal");
				
				if (resetPasswordModal.length < 1) {
					var newModal = $("<div class=\"modal\"></div>");
					resetPasswordModal = $("<div id=\"forgotPasswordModal\"></div>");
					resetPasswordModal.appendTo(newModal);
					newModal.appendTo("div.sprint div.body").hide();
				}
				
				// Open the modal from the initial forgot password state
				resetPasswordModal.openModal({
					ajaxContent: true,
					ajaxPath: "/mysprint/pages/sl/forgotpassword/modals/change_password.jsp",
					
					openCallback: function() {
						resetPasswordModal.find("#btnResetPasswordSubmit").unbind("click").bind("click", function(event) {
							event.preventDefault();
							
							// Client-side validation
							var validationRules = Sprint.fn.cloneObject(forgotPasswordFields);
							var frmResetPassword = resetPasswordModal.find("#frmResetPassword");
							var validForm = Sprint.fn.validateForm(frmResetPassword, forgotPasswordFields);
							if (validForm == true) {
								$.ajax({
									data: "ajax=true&" + frmResetPassword.serialize(),
									url: frmResetPassword.attr("action"),
									type: "GET",								
									async: false,
									dataType: "json",
									
									success: function(data) {
										if (data.validated) {
											Sprint.modal.elem.loadModalContent(data.responseUrl, resetPasswordModal);
											
											// After the modal is loaded, pressing Done, Enter or closing the modal shouldn't
											// do anything but close it.
											resetPasswordModal.find("#btnResetTemporaryPassDone").live("click", function(event) {
												event.preventDefault();
												Sprint.modal.elem.closeModal();

												//If a redirect url has been set, redirect...
												var redirectUrl = window['tempPasswordResetUrl'];
												if (redirectUrl != null && redirectUrl != '') {
													window.location.href = redirectUrl;
												}
											});
											
											//Make sure clicking the X button, or hitting escape triggers the click event on the Done button.
											$("#modalHolder a.closeModal").unbind("click").bind("click", function(e) {
												e.preventDefault();
												$("#btnResetTemporaryPassDone").trigger("click");
											});
											$(document).unbind("keydown").bind("keydown", function(e) {
												if (e.keyCode == 27) {
													e.preventDefault();
													$("#btnResetTemporaryPassDone").trigger("click");
												}
											});
										}
										else {
											//Remove previous error messages.
											resetPasswordModal.find(".headerWrapperPrimary").find(".formErrors").remove();
											resetPasswordModal.find(".error").removeClass("error");
									
											//Form has errors, show messages.
											frmResetPassword.showFormErrors({
												errorData: {
													txtForgotPasswordNewPassword: {
															name: "txtForgotPasswordNewPassword",
															errorMessage: data.errorMessage
													}
												},
												summaryAnchor: resetPasswordModal.find(".headerWrapperPrimary"),
												showInline: false,
												scrollToSummary: false
											});
										}
									},
									
									error: Sprint.fn.ajaxError
								});
							}
							else {
								//Remove previous error messages.
								resetPasswordModal.find(".headerWrapperPrimary").find(".formErrors").remove();
								resetPasswordModal.find(".error").removeClass("error");
						
								//Form has errors, show messages.
								frmResetPassword.showFormErrors({
									errorData: validForm,
									summaryAnchor: resetPasswordModal.find(".headerWrapperPrimary"),
									showInline: false,
									scrollToSummary: false
								});
							}
						});
						
						// Bind the enter key to the submit button
						$("#frmResetPassword").bind("submit", function(event) {
							event.preventDefault();
							$("#forgotPasswordModal").find("#btnResetPasswordSubmit").trigger("click");
						});
						
						// Closing the modal should redirect them to logout
						$("#modalHolder a.closeModal").unbind("click").bind("click", function() {
							var frmResetPass = resetPasswordModal.find("#frmResetPassword");
							frmResetPass.attr("action", "/entrycheck/logout.fcc");
							frmResetPass.append("<input type=\"hidden\" name=\"TARGET\" value=\"/mysprint/pages/sl/global/index.jsp?smlogout=true\" />")
							frmResetPass.unbind("submit").submit();
						});
						
						// Clicking cancel should redirect them to logout
						resetPasswordModal.find("#btnResetPasswordCancel").unbind("click").bind("click", function(event) {
							event.preventDefault();
							$("#modalHolder a.closeModal").trigger("click");
						});
						
						// Pressing escape key should redirect them to logout
						$(document).unbind("keydown").bind("keydown", function(event) {
							if (event.keyCode == 27) {
								event.preventDefault();
								$("#modalHolder a.closeModal").trigger("click");
							}
						});
					}
				});
			}).click();
		
			/* Deep link landing page sign in 
			Note: this is different from the regular sign in function because the form IDs have to be different in order for 
			the 2 sign in forms to be present on the page.  All form IDs on this form have "DL" appended to it. eg: #frmUserLoginDL
			instead of #frmUserLogin.
			--------------------------------------------------*/
		
			function signInFormProcess() {

				var submitLoginForm = false;
				var frmUserLogin = $("#frmUserLoginDL");
				
				// This handles the email verification scenario for deep linking signin for both the modal and the landing page.
				frmUserLogin.find("#btnLoginSubmitEmailVerificationDL").unbind("click").bind("click", function(event) { 
					
					event.preventDefault();
					var submitButton = $("#btnLoginSubmitEmailVerificationDL").clone(true);
					
					var formPathEmailVerification = frmUserLogin.attr("action");
					
				// Email validation
				var signUpEmailFormFields = {
					emailAddress: {
						name: "txtEmailDL",
						type: "emailAddress",
						required: true,
						emptyErrorMessage: Sprint.fn.getContentString("formFieldErrors.emailAddressEmpty"),
						invalidErrorMessage: Sprint.fn.getContentString("formFieldErrors.emailAddressInvalid")
					}
				};
				var dataToValidate = Sprint.fn.cloneObject(signUpEmailFormFields);
				var validForm = Sprint.fn.validateForm(frmUserLogin, signUpEmailFormFields);
				
				if(validForm == true){ // Email validation passed.
					
					$.ajax({
						data: frmUserLogin.serialize() + "&emailVerification=true",
						type: "POST",
						url: formPathEmailVerification,
						dataType: "json",
						
						success: function(data) {
							if (data.validated) {
								if ($("#deepLinkTriggerSignIn").length > 0) { // The sign in process is happening through the modal.
									
									$.get("/global/common/modals/deeplink_signin.php?ajax=true", function(signin_content) {
										$("#signInDeepLinkModal").empty().append($(signin_content));
										
										
										var header = $("#deepLinkSignIn").find(".headerWrapperPrimary");
										
										// Remove any current success/error messages
										header.find(".updateMessage").remove();
										
										// Show success message
										var updateMessage = $("<div class=\"updateMessage\"><img class=\"messageIcon\" src=\"/global/images/icons/ico_confirmation_med.gif\" alt=\"Success\" /><div class=\"updateText\">"+data.validationMessage+"</div></div>");
										updateMessage.appendTo(header);
										
										// Append the submit button
										var submitParent = $("#signInDeepLinkModal").find("div.buttons");
										submitParent.empty().append(submitButton);
										
									}); // end get
								} 
								else { // The sign in process is happening through the landing page
								
									$.get("/global/_includes/deeplink_landing_signinEmailVerConfirmation.html", function(signin_content) {
									
										$("#deepLinkSignIn").empty().append($(signin_content));
										
										var header = $("#deepLinkSignIn").find("#userLoginDL");
										
										// Remove any current success/error messages
										header.find(".updateMessage").remove();
										
										// Show success message
										var updateMessage = $("<div class=\"updateMessage\"><img class=\"messageIcon\" src=\"/global/images/icons/ico_confirmation_med.gif\" alt=\"Success\" /><div class=\"updateText\">"+data.validationMessage+"</div></div>");
										updateMessage.prependTo(header);
										
										var submitParent = $("#deepLinkSignIn").find("div.buttons");
										
										var newSubmitButton = $("<input type=\"submit\" class=\"button1\" id=\"btnLoginSubmitEmailVerificationDL\" value=\"Sign In\" />");
										submitParent.empty().append(newSubmitButton);
										newSubmitButton.createHighResButtons();
										
										
									}); // end get								
								}
							} 
							else { // Error
							
								if ($("#deepLinkTriggerSignIn").length > 0) { // The sign in process is happening through the modal
								
									$("#deepLinkSignIn").find(".headerWrapperPrimary").find(".updateMessage").remove();
									$("#deepLinkSignIn").find(".headerWrapperPrimary").find(".formErrors").remove();
								
									$("#frmUserLoginDL").showFormErrors({
										errorData: {
											txtEmailDL: {
												name: "txtEmailDL",
												errorMessage: data.errorMessage
											}
										},
										summaryAnchor: $("#deepLinkSignIn").find(".headerWrapperPrimary"),
										scrollToSummary: false,
										showInline: false
									});
								} 
								else { // The sign in process is happening through the landing page
									
									// Remove any current success/error messages
									$("#deepLinkSignIn").find("#userLoginDL").find(".updateMessage").remove();
									$("#deepLinkSignIn").find("#userLoginDL").find(".formErrors").remove();
									
									$("#frmUserLoginDL").showFormErrors({
										errorData: {
											txtEmailDL: {
												name: "txtEmailDL",
												errorMessage: data.errorMessage
											}
										},
										summaryAnchor: $("#deepLinkSignIn").find("#userLoginDL").find("#verificationErrors"),
										scrollToSummary: false,
										showInline: false
									});
								}
							}
						}
					}); // end ajax
					
					}
					else {
						
						if ($("#deepLinkTriggerSignIn").length > 0) { // The sign in process is happening through the modal
						
							$("#deepLinkSignIn").find(".headerWrapperPrimary").find(".updateMessage").remove();
							$("#deepLinkSignIn").find(".headerWrapperPrimary").find(".formErrors").remove();
							$("#deepLinkSignIn").find(".headerWrapperPrimary").find(".error").removeClass("error");
							
							frmUserLogin.showFormErrors({
		                        showInline: false,
		                        summaryAnchor: $("#deepLinkSignIn").find(".headerWrapperPrimary"),
		                        showSummary: true,
		                        errorData: validForm
		                    });
		                    return false;
							
		                } else {
		                
							//Remove previous error messages.
							$("#deepLinkSignIn").find("#userLoginDL").find(".formErrors").remove();
							$("#deepLinkSignIn").find("#userLoginDL").find(".error").removeClass("error");
							$("#deepLinkSignIn").find("#userLoginDL").find(".updateMessage").remove();
							
							frmUserLogin.showFormErrors({
		                        showInline: false,
		                        summaryAnchor: $("#deepLinkSignIn").find("#userLoginDL").find("#verificationErrors"),
		                        showSummary: true,
		                        errorData: validForm
		                    });
		                    return false;		                	
		                }
					} // end email validation
					
				}); // end frmUserLogin.find("#btnLoginSubmitEmailVerificationDL")...
				
				frmUserLogin.find("#btnLoginSubmitDL").unbind("click").bind("click", function(event) {
					event.preventDefault();
					$('#signInDeepLinkModal form').wrapInner('<fieldset />');
					/* BEGIN: Tech Implementation for loading spinner while logining in */
					var loadingHt = $('#frmUserLoginDL > fieldset').height()+'px';
					var loadingMarTop = ($('#frmUserLoginDL > fieldset').height()/4 - 13)+'px';
					var loadingDiv = '<div id="signInLoadingWindow" style="display:none; float:left; height:'+loadingHt+'; text-align:center;"><div style="margin-top:'+loadingMarTop+';"><p>Please wait while we load all of your account details. This may take a minute for larger accounts.</p></div></div>';
					$('#signInLoadingWindow').remove();
					$('#frmUserLoginDL').append(loadingDiv);
					$('#frmUserLoginDL').find('#signInLoadingWindow div').prepend(loadingImageGlobal);
					/* END: Tech Implementation for loading spinner while logining in */
					
					var fields = {
						txtLoginUsername: {
							name: "USER",
							type: "legacyUsername",
							required: true,
							emptyErrorMessage: Sprint.fn.getContentString("signInOutErrors.usernameEmpty"),
							invalidErrorMessage: Sprint.fn.getContentString("signInOutErrors.usernameInvalid"),
							customValidationRule: function(field) {
								var validUserName = true;					
								var fieldValue = field.val();				
								var baseRule = /^.{1,33}$/;					
								//Test to see if the field value passes the base ruleset OR if it passes the email address test
								return (baseRule.test(fieldValue) || Sprint.formFieldTypes.emailAddress.test(fieldValue));
							}
						},
						txtLoginPassword: {
							name: "PASSWORD",
							type: "password",
							required: true,
							emptyErrorMessage: Sprint.fn.getContentString("signInOutErrors.passwordEmpty"),
							invalidErrorMessage: Sprint.fn.getContentString("signInOutErrors.passwordInvalid"),
							customValidationRule: function(field) {
								var validUserName = true;					
								var fieldValue = field.val();				
								var baseRule = /^.{6,33}$/;					
								//Test to see if the field value passes the base ruleset OR if it passes the email address test
								return (baseRule.test(fieldValue));
							}
						}
					};

					var validation = Sprint.fn.validateForm(frmUserLogin, fields);
					
					frmUserLogin.find("label.error").remove();
					frmUserLogin.find("input.error").removeClass("error");

					if (typeof(validation) != "boolean") {
						frmUserLogin.showFormErrors({
							errorData: validation,
							showInline: true,
							scrollToSummary: false
						});

						return false;
					}
					/* BEGIN: Tech Implementation for loading spinner while logining in */
					if($('#frmUserLoginDL').length > 0){
						$('#frmUserLoginDL #signInLoadingWindow').show();
						$('#frmUserLoginDL > fieldset').hide();
					}
					/* END: Tech Implementation for loading spinner while logining in */

					frmUserLogin.submit();
					return true;

				});
				
			} // end signInFormProcess
			
			//Attach this function to the Sprint namespace for re-use later (specifically in the Sprint.openSignInModal function defined above)
			Sprint.signInFormProcess = signInFormProcess;
		
			function deepLinkSignInModal() {
				
				//Check to see if the page has a 'launchSignInModal' variable set to true, if so, launch the sign in modal immediately - do this section first before checking for any deep link version
				var pageURL = Sprint.fn.getQueryString(window.location.href);
				var launchSignInModal = Sprint.fn.getURLParameter(pageURL, "launchSignInModal");
				var queryParam = Sprint.fn.getURLParameter(pageURL, "selectedFlow");	
				if (launchSignInModal == "true") {
					Sprint.openSignInModal(queryParam);
					return; //Don't run the rest of this function...
				}

				if ($("#deepLinkTriggerSignIn").length > 0) { // The sign in process is happening through the modal
	
		            var signInDeepLinkModal = $("#signInDeepLinkModal");
					
					if (signInDeepLinkModal.length < 1) {
						//Because this modal is being loaded via AJAX, it won't exist in the markup already. Create the modal on the fly
						var newModal = $("<div class=\"modal\"></div>").appendTo("div.sprint div.body").hide();
			
						signInDeepLinkModal = $("<div id=\"signInDeepLinkModal\"></div>").appendTo(newModal);
						
					}
					
					signInDeepLinkModal.openModal({
						ajaxContent: true,
						ajaxPath: $("#deepLink_signInDLModal").attr("href"),
						
						openCallback: function() {
							
							signInFormProcess();
						}
					});
				} else { // The sign in is happening through the landing page
					signInFormProcess();
				}
			}
			
			deepLinkSignInModal();
			
			/* END - Deep link landing page sign in 
			--------------------------------------------------*/
		
		})();
		
		// Forgot username/password scenario from external domain
		(function() {
			
			var forgotPasswordFields = {
				txtForgotPasswordUsername: {
					name: "txtForgotPasswordUsername",
					type: "legacyUsername",
					required: true,
					emptyErrorMessage: Sprint.fn.getContentString("formFieldErrors.forgotPasswordUsernameEmpty"),
					invalidErrorMessage: Sprint.fn.getContentString("formFieldErrors.usernameInvalid"),
					
					customValidationRule: function(field) {
		
						var validUserName = true;
						
						var fieldValue = field.val();
					
						var baseRule = /^[a-zA-Z0-9\.\-_]{1,33}$/;
						
						//Test to see if the field value passes the base ruleset OR if it passes the email address test
						if (!baseRule.test(fieldValue) && !Sprint.formFieldTypes.emailAddress.test(fieldValue)) {
							validUserName = false;
						}			
						
						return validUserName;
					
					}
				},
				radForgotPasswordDestinationEmail: {
					name: "radForgotPasswordDestinationEmail",
					type: "radioButton",
					required: true,
					emptyErrorMessage: Sprint.fn.getContentString("forgotPasswordErrors.passwordDestinationEmpty")
				},
				radForgotPasswordDestinationEmail: {
					name: "radForgotPasswordDestinationText",
					type: "radioButton",
					required: true,
					emptyErrorMessage: Sprint.fn.getContentString("forgotPasswordErrors.passwordDestinationEmpty")
				},
				txtForgotPasswordCode: {
					name: "txtForgotPasswordCode",
					type: "ESN,MEID,BAN,phoneNumber",
					required: true,
					emptyErrorMessage: Sprint.fn.getContentString("forgotPasswordErrors.passwordCodeEmpty"),
					invalidErrorMessage: Sprint.fn.getContentString("forgotPasswordErrors.passwordCodeInvalid")
				},
				txtForgotPasswordNewPassword: {
					name: "txtForgotPasswordNewPassword",
					type: "password_11_3",
					required: true,
					emptyErrorMessage: Sprint.fn.getContentString("forgotPasswordErrors.newPasswordEmpty"),
					invalidErrorMessage: Sprint.fn.getContentString("forgotPasswordErrors.newPasswordInvalid_11_3")
				},
				txtForgotPasswordConfirmPassword: {
					name: "txtForgotPasswordConfirmPassword",
					type: "match",
					required: true,
					mustMatch: "txtForgotPasswordNewPassword",
					emptyErrorMessage: Sprint.fn.getContentString("forgotPasswordErrors.newPasswordConfirmEmpty"),
					invalidErrorMessage: Sprint.fn.getContentString("forgotPasswordErrors.newPasswordConfirmInvalid")
				},
				txtForgotPasswordEmail: {
					name: "txtForgotPasswordEmail",
					type: "emailAddress",
					required: false,
					invalidErrorMessage: Sprint.fn.getContentString("formFieldErrors.emailAddressInvalid"),
					customValidationRule: function(field) {
						var fieldValue = field.val();
						var secondaryFieldValue = $("#txtForgotPasswordPhone").val();
						
						if (fieldValue != "" && secondaryFieldValue == "") {
							forgotPasswordFields.txtForgotPasswordPhone.required = false;
							return Sprint.formFieldTypes.emailAddress.test(fieldValue);
						} else {
							return true;
						}
					}
				},
				txtForgotPasswordPhone: {
					name: "txtForgotPasswordPhone",
					type: "phoneNumber",
					required: true,
					emptyErrorMessage: Sprint.fn.getContentString("forgotPasswordErrors.phoneNumberAndEmailEmpty"),
					invalidErrorMessage: Sprint.fn.getContentString("formFieldErrors.phoneNumberInvalid")
				}
			};
			var forgotPasswordAccountFields = {
				txtBillingZip: {
					name: "txtBillingZip",
					type: "freeZipCodeInvalid",
					required: true,
					emptyErrorMessage: Sprint.fn.getContentString("formFieldErrors.zipCodeEmpty"),
					invalidErrorMessage: Sprint.fn.getContentString("formFieldErrors.freeZipCodeInvalid")
				},
				txtSSN: {
					name: "txtSSN",
					type: "textArea",
					required: true,
					emptyErrorMessage: Sprint.fn.getContentString("shop.checkout.accountContactInformation.ssnEmpty"),
					invalidErrorMessage: Sprint.fn.getContentString("shop.checkout.accountContactInformation.ssnInvalid")
				},
				txtForgotPasswordPin: {
					name: "txtForgotPasswordPin",
					type: "PIN",
					required: true,
					emptyErrorMessage: Sprint.fn.getContentString("forgotPasswordErrors.pinAndAnswerEmpty"),
					invalidErrorMessage: Sprint.fn.getContentString("forgotPasswordErrors.pinInvalid")
				}
			};
			var forgotPasswordSecureFields = {
				txtForgotPasswordAnswer: {
					name: "txtForgotPasswordAnswer",
					type: "securityAnswer",
					required: false,
					invalidErrorMessage: Sprint.fn.getContentString("forgotPasswordErrors.securityAnswerInvalid"),
					customValidationRule: function(field) {
						var fieldValue = field.val();
						var secondaryFieldValue = $("#txtForgotPasswordPin").val();
						
						if (fieldValue != "" && secondaryFieldValue == "") {
							//forgotPasswordFields.txtForgotPasswordPin.required = false;
							if(fieldValue.length > 30){
								// can't be greater than 30 characters
								return false;
							} else {
								return Sprint.formFieldTypes.securityAnswer.test(fieldValue);
							}
						} else {
							return true;
						}
					}
				},
				txtSecBillingZip: {
					name: "txtSecBillingZip",
					type: "zipCode",
					required: true,
					emptyErrorMessage: Sprint.fn.getContentString("formFieldErrors.zipCodeEmpty"),
					invalidErrorMessage: Sprint.fn.getContentString("formFieldErrors.zipCodeInvalid")
				},
				txtSecSSN: {
					name: "txtSecSSN",
					type: "textArea",
					required: true,
					emptyErrorMessage: Sprint.fn.getContentString("shop.checkout.accountContactInformation.ssnEmpty"),
					invalidErrorMessage: Sprint.fn.getContentString("shop.checkout.accountContactInformation.ssnInvalid")
				}
			};
			
			bindExternalForgotUserPassSubmitButton();
			bindExternalForgotUserPassCancelButton();
			bindExternalForgotUserPassEnterToSubmitEvent();
			
			function bindExternalForgotUserPassEnterToSubmitEvent() {
				$("#externalForgotUsernamePassword").find("#frmForgotPassword").unbind("submit").bind("submit", function(event) {
					event.preventDefault();
					$("#btnForgotPasswordSubmit").trigger("click");
				});
			}
			
			function bindExternalForgotUserPassCancelButton() {
				$("#externalForgotUsernamePassword").find("#btnForgotPasswordCancel").unbind("click").bind("click", function(event) {
					event.preventDefault();
					window.location = document.referrer;
				});
			}
			function bindExternalForgotSubmitButton(){
				var externalPage      = $("#externalForgotUsernamePassword");
				var frmForgotPassword = externalPage.find("#frmForgotPassword");
				var ajaxData = "ajax=true";
				var enableSnare = true;
					// if snare is enabled then fetch snare results
					if (enableSnare) {
					
						//fetch results from the iframe
						var blackBoxValue = Sprint.getBBdata();
					} else {
					
						//create dummy object to bypass snare
						var blackBoxValue = {blackbox:"undefined"};
					}
										//if($("#txtForgotPasswordAnswer").length >= 1){
						/*if(blackBoxValue.blackbox == 'undefined'){
							$(this).a
						}
						setTimeout(function() {
						}*/
					ajaxData += "&ioBlackBox="+blackBoxValue.blackbox;
					//}
			
				externalPage.find("#btnForgotPwdAccountSubmit,#btnForgotPwdSecureSubmit").unbind("click").bind("click", function(event) {
					event.preventDefault();
					var $this = $(this);
 					// Client-side validation
					var validationRules = Sprint.fn.cloneObject(forgotPasswordFields);
					if($this.attr('id') == 'btnForgotPwdAccountSubmit'){
						var validForm = Sprint.fn.validateForm(frmForgotPassword, forgotPasswordAccountFields);
					} else {
						var validForm = Sprint.fn.validateForm(frmForgotPassword, forgotPasswordSecureFields);
					}
					if (validForm == true) {
						if($this.attr('id') == 'btnForgotPwdAccountSubmit'){
							ajaxData += "&"+$("div.accountForgotleft input.text").serialize();
						} else {
							ajaxData += "&txtBillingZip="+$("#txtSecBillingZip").val()+"&txtSSN="+$("#txtSecSSN").val()+"&"+$("#txtForgotPasswordAnswer").serialize();
						}
						ajaxData += "&"+$("#hidForgotPasswordState").serialize();
						$.ajax({
							data: ajaxData,
							url: frmForgotPassword.attr("action"),
							type: "GET",								
							async: false,
							dataType: "json",
							
							success: function(data) {
								if (data.validated) {
									//Remove previous error messages.
									externalPage.find(".headerWrapperPrimary").find(".formErrors").remove();
									externalPage.find(".error").removeClass("error");
									
									$.get(data.responseUrl, function(content) {
										externalPage.find("div.containerThreeColumn").empty().append($(content)).find("div.headerWrapperPrimary").remove();
										if (data.emailAddress) {
											externalPage.find("span.sendToEmail").text(data.emailAddress);
										}
										if (data.securityQuestion) {
											externalPage.find("span.securityQuestion").text(data.securityQuestion);
										}
										if (data.emailAddress) {
											externalPage.find("span.sendToEmail").text(data.emailAddress);
										}
										if (data.phoneNumber) {
											externalPage.find("span.sendToPhone").text(data.phoneNumber);
										}
										
										$(".sprint input[type='submit'], .sprint input[type='button'], .sprint a.button1, .sprint a.button2").createHighResButtons();

										bindExternalForgotUserPassSubmitButton();
										bindExternalForgotUserPassCancelButton();
										bindExternalForgotUserPassEnterToSubmitEvent();
									});
								} else {
									//Remove previous error messages.
									externalPage.find(".headerWrapperPrimary").find(".formErrors").remove();
									externalPage.find(".error").removeClass("error");
				
									//Form has errors, show messages.
									externalPage.find("#frmForgotPassword").showFormErrors({
										errorData: {
											txtValidationCode: {
												name: data.errorField,
												errorMessage: data.errorMessage
											}
										},
										summaryAnchor: externalPage.find(".headerWrapperPrimary"),
										showInline: false,
										scrollToSummary: false
									});
								}
							},
														
							error: Sprint.fn.ajaxError	
						});
					} else {
						//Remove previous error messages.
						externalPage.find(".headerWrapperPrimary").find(".formErrors").remove();
						externalPage.find(".error").removeClass("error");
				
						//Form has errors, show messages.
						externalPage.find("#frmForgotPassword").showFormErrors({
							errorData: validForm,
							summaryAnchor: externalPage.find(".headerWrapperPrimary"),
							showInline: false,
							scrollToSummary: false
						});
					}
					
					// Reset the validation rules
					forgotPasswordFields = validationRules;
				});
			}
			function bindExternalForgotUserPassSubmitButton() {
				var externalPage      = $("#externalForgotUsernamePassword");
				var frmForgotPassword = externalPage.find("#frmForgotPassword");
					/* Start : Ivoation changes
					---------------------------- */
					if(externalPage.length > 0){
						Sprint.getBBdata = function(){
							if($("#snareIframe").length <= 0){
								$("body").append('<iframe id="snareIframe" src="/mysprint/pages/sl/common/snare.jsp" width="0" height="0" scrolling="no" frameborder="no"></iframe>');
							}
							var bbData = document.getElementById('snareIframe').contentWindow['bb_data'];
							
							if(typeof(bbData) != "undefined"){
								// if snare has completed then submit
								return bbData;
							} else {
								// snare is enabled but bb_data in the iframe is undefined
								return {blackbox:"undefined"}
							}
						}
					
						var enableSnare = true;
						// if snare is enabled then fetch snare results
						if (enableSnare) {
							//fetch results from the iframe
							var blackBoxValue = Sprint.getBBdata();
						} else {
							//create dummy object to bypass snare
							var blackBoxValue = {blackbox:"undefined"};
						}
					}
					/* End : Ivoation changes
					---------------------------- */				
				externalPage.find("#btnForgotPasswordSubmit").unbind("click").bind("click", function(event) {
					event.preventDefault();
					
					// Client-side validation
					var validationRules = Sprint.fn.cloneObject(forgotPasswordFields);
					var validForm = Sprint.fn.validateForm(frmForgotPassword, forgotPasswordFields);
					if (validForm == true) {
						$.ajax({
							data: "ajax=true&" + frmForgotPassword.serialize(),
							url: frmForgotPassword.attr("action"),
							type: "GET",								
							async: false,
							dataType: "json",
							
							success: function(data) {
								if (data.validated) {
									//Remove previous error messages.
									externalPage.find(".headerWrapperPrimary").find(".formErrors").remove();
									externalPage.find(".error").removeClass("error");
									
									$.get(data.responseUrl, function(content) {
										
											externalPage.find("div.containerThreeColumn").empty().append($(content)).find("div.headerWrapperPrimary").remove();
											if (data.emailAddress) {
												externalPage.find("span.sendToEmail").text(data.emailAddress);
											}
											if (data.securityQuestion) {
												externalPage.find("span.securityQuestion").text(data.securityQuestion);
											}
											if (data.emailAddress) {
												externalPage.find("span.sendToEmail").text(data.emailAddress);
											}
											if (data.phoneNumber) {
												externalPage.find("span.sendToPhone").text(data.phoneNumber);
											}
											
											$(".sprint input[type='submit'], .sprint input[type='button'], .sprint a.button1, .sprint a.button2").createHighResButtons();
											
											
											if(data.isSingleBan){
					
												bindExternalForgotSubmitButton();
												if(data.zipSSNValidSection){
													if(data.secQuesValidSection){
												
														$("div.accountForgotRight").hide();

													}
													if(data.pinValidSection){
														
														var invalidForgotPassPIN =  Sprint.fn.getContentString("formFieldErrors.invalidForgotPassPIN");
														$("div.accountForgotleft, div.accountForgotRight").hide();
														externalPage.find("div.headerWrapperPrimary").append('<ul class="formErrors"><li>'+invalidForgotPassPIN+'</li></ul>');
														//$(".sprint .frmForgotPwd .headerWrapperPrimary").css('width','340px');
													}
												} else {
													var invalidZipSSNError = Sprint.fn.getContentString("formFieldErrors.invalidZipSSNError");
													$("div.accountForgotleft, div.accountForgotRight").hide();
													externalPage.find("div.headerWrapperPrimary").append('<ul class="formErrors"><li>'+invalidZipSSNError+'</li></ul>');
											
												}
											} else {
												bindExternalForgotUserPassSubmitButton();
											}
											
											bindExternalForgotUserPassCancelButton();
											bindExternalForgotUserPassEnterToSubmitEvent();
										
									});
								} else {
									//Remove previous error messages.
									externalPage.find(".headerWrapperPrimary").find(".formErrors").remove();
									externalPage.find(".error").removeClass("error");
				
									//Form has errors, show messages.
									externalPage.find("#frmForgotPassword").showFormErrors({
										errorData: {
											txtValidationCode: {
												name: data.errorField,
												errorMessage: data.errorMessage
											}
										},
										summaryAnchor: externalPage.find(".headerWrapperPrimary"),
										showInline: false,
										scrollToSummary: false
									});
								}
							},
														
							error: Sprint.fn.ajaxError	
						});
					} else {
						//Remove previous error messages.
						externalPage.find(".headerWrapperPrimary").find(".formErrors").remove();
						externalPage.find(".error").removeClass("error");
				
						//Form has errors, show messages.
						externalPage.find("#frmForgotPassword").showFormErrors({
							errorData: validForm,
							summaryAnchor: externalPage.find(".headerWrapperPrimary"),
							showInline: false,
							scrollToSummary: false
						});
					}
					
					// Reset the validation rules
					forgotPasswordFields = validationRules;
				});
			}

		})();
		
		/* Deep Linking Trigger Functionality
		---------------------------------------- */
          (function() {

	           var deepLinkTrigger = $("#deepLinkTrigger");
	          
	           if (deepLinkTrigger.length > 0) {

                    //Check for specific cases
                    if ($("#deepLink_addPhoneModal").length > 0) {
                   
                         $(window).bind("load", function() {
                              $("#deepLink_addPhoneModal").trigger("click");
                         });
     
                    }
                    else if ($("#deepLink_swapPlanModal").length > 0) {
                   
	                     $(window).bind("load", function() {
	                          $("#deepLink_swapPlanModal").trigger("click");
                         });
                    
                    }
                    else if ($("#deepLink_loyaltyOffersModal").length > 0) {
                   
	                     $(window).bind("load", function() {
	                          $("#deepLink_loyaltyOffersModal").trigger("click");
                         });
                    
                    }
	           }
          })();
		
		// Email verification scenario from external domain
		(function() {
			var externalPage = $("#externalEmailVerification");
			var frmEmailVerf = externalPage.find("#frmEmailVerification");
								
			externalPage.find("#btnLoginSubmitDL").unbind("click").bind("click", function(event) {
				event.preventDefault();
				
				// Email validation
				var signUpEmailFormFields = {
					emailAddress: {
						name: "txtEmailDL",
						type: "emailAddress",
						required: true,
						emptyErrorMessage: Sprint.fn.getContentString("formFieldErrors.emailAddressEmpty"),
						invalidErrorMessage: Sprint.fn.getContentString("formFieldErrors.emailAddressInvalid")
					}
				};
				var dataToValidate = Sprint.fn.cloneObject(signUpEmailFormFields);
				var validForm = Sprint.fn.validateForm(frmEmailVerf, signUpEmailFormFields);
				
				if(validForm == true){
				
					$.ajax({
						data: "ajax=true&" + frmEmailVerf.serialize()+ "&emailVerification=true",
						url: frmEmailVerf.attr("action"),
						type: "GET",								
						async: false,
						dataType: "json",
						
						success: function(data) {
							if (data.validated) {
								
								//Remove previous error messages.
								externalPage.find(".headerWrapperPrimary").find(".formErrors").remove();
								externalPage.find(".error").removeClass("error");
								externalPage.find(".headerWrapperPrimary").find(".updateMessage").remove();
							
								var updateMessage = $("<div class=\"updateMessage\"><img class=\"messageIcon\" src=\"/global/images/icons/ico_confirmation_med.gif\" alt=\"Success\" /><div class=\"updateText\">" + data.validationMessage + "</div></div>");
								updateMessage.appendTo(externalPage.find(".headerWrapperPrimary"));
								setTimeout(function() {
									// Secure DeepLinking Pages
									if (data.nextPage) {
										window.location = data.nextPage;
									}
									else {
										window.location = "/mysprint/pages/sl/global/index.jsp?smlogout=true"
									}
								}, 2000);
							}
							else {
								//Remove previous error messages.
								externalPage.find(".headerWrapperPrimary").find(".formErrors").remove();
								externalPage.find(".error").removeClass("error");
								externalPage.find(".headerWrapperPrimary").find(".updateMessage").remove();
						
								//Form has errors, show messages.
								frmEmailVerf.showFormErrors({
									errorData: {
												txtEmailDL: {
													name: "txtEmailDL",
													errorMessage: data.errorMessage
												}
											},
									summaryAnchor: externalPage.find(".headerWrapperPrimary"),
									showInline: false,
									scrollToSummary: false
								});
							}
						},
						error: Sprint.fn.ajaxError
					}); // end ajax
				 }
				 else {
				 
					//Remove previous error messages.
					externalPage.find(".headerWrapperPrimary").find(".formErrors").remove();
					externalPage.find(".error").removeClass("error");
					externalPage.find(".headerWrapperPrimary").find(".updateMessage").remove();
					
					frmEmailVerf.showFormErrors({
                        showInline: false,
                        summaryAnchor: externalPage.find(".headerWrapperPrimary"),
                        showSummary: true,
                        errorData: validForm
                    });
                    return false;
                 }
                 // End email validation
			});
			
		})();

		//2.1x - Add a Phone Modal
		(function() {
		
			var targetLink; //Variable that will store the path to the addPhoneModal content
		
			function setupAddPhoneModal() {
				
				var addPhoneModal = $("#addPhoneModal");
				
				addPhoneModal.find(".ellipsis").ellipsis();
				
				//Convert phone lists into carousels
				addPhoneModal.find(".phonesOnPlan").carousel({
					visibleItems: 3,
					scroll: 3
				});
				
				//Setup the currentPlans scrolling layer (if there are more than 2 plans)
				var currentPlans = addPhoneModal.find("div.currentPlans");
						
				//Store the current scrollbar width
				var currentScrollbarWidth = Sprint.fn.getScrollbarWidth();
				
				currentPlans.each(function() {
				
					var currentPlanLayer = $(this);
				
					if (currentPlanLayer.find(".moduleDefault").length > 2) {
						//make sure the heights of each plan are equal
						currentPlanLayer.find(".moduleDefault").equalizeHeights();
						
						//Set the height of the current plans layer to fit 2 plans in view at once						
						var currentPlansHeight = currentPlanLayer.find(".moduleDefault").outerHeight() * 2;
						
						//Add the bottom margin to the height to make sure that everything fits.
						currentPlansHeight = currentPlansHeight + (currentPlanLayer.find(".moduleDefault:first").outerHeight(true) - currentPlanLayer.find(".moduleDefault:first").outerHeight());
	
						//Add the current scrollbar width to the current plans layer
						var currentPlansWidth = currentPlanLayer.width()+currentScrollbarWidth;
						
						currentPlanLayer.height(currentPlansHeight).width(currentPlansWidth).css({
							overflow: "auto",
							position: "absolute"
						});
						
						//Set the currentPlansWrapper div to the same height as the currentPlans div (to clear the absolute positioning)
						currentPlanLayer.parent().height(currentPlansHeight);
					}						

				});
				
				function showAccount(selectedAccount) {
					//Hide all accounts
					addPhoneModal.find("div.accountDetails").hide();
					
					//Show the selected account
					addPhoneModal.find("#details_"+selectedAccount).show();
				}

				//Account change drop-down
				addPhoneModal.find("#selChangeAccountModal").bind("change", function() {
				
					var selectedAccount = $(this).val();
					
					showAccount(selectedAccount);
				
				});
				
				//Do the initial check to show the selected account
				showAccount(addPhoneModal.find("#selChangeAccountModal").val());
				
				// Scroll to the selected device section, if it is in a closed
				// disclosure, then open it then scroll to it.
				$("#addPhoneModal h4 a.sectionAnchor").unbind("click").live("click", function(event) {
					event.preventDefault();
					
					$("a.closeModal").trigger("click");
					
					//Find the anchor target that this links to
					var anchorTarget = $($(this).attr("href"));
					
					if (anchorTarget.is(".disclosureClosed")) {
						anchorTarget.find(".disclosureToggle").trigger("click");
					}
					
					anchorTarget.scrollTo({speed: "slow"});
				});
				// Added to change the Add Another Phone Modal to fit VD
				if(addPhoneModal.find('.accountDetails h2 span').text('OR')) {
					addPhoneModal.find('.accountDetails h2').css({'text-align':'center','border':'none'});
					addPhoneModal.find('.accountDetails > form').wrap('<div class="moduleDefault" />');
				}
			}
		
			/* Change Plan Modal */
			Sprint.changePlanModal = function(targetLink) {
				var swapPlanModal = $("#swapPlanModal");
				
				if (swapPlanModal.length < 1) {
					// Because this modal is being loaded via AJAX, it won't exist in the markup already.
					// Create the modal on the fly
					var newModal = $("<div class=\"modal\"></div>").appendTo("div.sprint div.body").hide();
					swapPlanModal = $("<div id=\"swapPlanModal\"></div>").appendTo(newModal);
				}
				
				swapPlanModal.openModal({
					ajaxContent: true,
					ajaxPath: targetLink,		
					openCallback: function(){
						// Set up vertical scrolling
						var curPlans = $("#swapPlanModal .phonePlanHolder .moduleDefault:visible");
						var planHolder = $("#swapPlanModal .phonePlanHolder");
						var currentScrollbarWidth = Sprint.fn.getScrollbarWidth();
						
						if (curPlans.length > 2) {
							// Issues with IE - Prabir
							// Get the combined height of the first two modules
							var height = $(curPlans.get(0)).outerHeight() + $(curPlans.get(1)).outerHeight();
							height += parseInt($(curPlans.get(0)).css("margin-bottom"))*2;
							
							planHolder.height(height).width(CHANGE_PLAN_MODAL_WIDTH).css({
								"overflow-y": "auto"
							});
						} else {
							planHolder.width(CHANGE_PLAN_MODAL_WIDTH-currentScrollbarWidth).css({
								overflow: "hidden",
								height: "auto"
							});
						}
						
						// Bind the radio buttons
						$("#swapPlanModal input[name='radChangePlan']").unbind("click").bind("click", function(event) {
							$("#swapPlanModal #btnChangePlan").removeClass("disabled");
						});
					},
					width: CHANGE_PLAN_MODAL_WIDTH
				});
			}
		
			var CHANGE_PLAN_MODAL_WIDTH = 700;
			
			// Bind the swap plan modal to the swap plan link
			$("a.changePlanModalTrigger").bind("click", function() {
				targetLink = $(this).attr("href");
				Sprint.changePlanModal(targetLink);
				return false;
			});
			
			
			/* Manage Add-ons Modal */
			var MANAGE_ADDONS_MODAL_WIDTH = 700;
			
			// Bind the manage addons modal to the manage addons link
			$("a.manageAddonsModalTrigger").bind("click", function() {
				targetLink = $(this).attr("href");
				var manageAddonsModal = $("#manageAddonsModal");
				
				if (manageAddonsModal.length < 1) {
					// Because this modal is being loaded via AJAX, it won't exist in the markup already.
					// Create the modal on the fly
					var newModal = $("<div class=\"modal\"></div>").appendTo("div.sprint div.body").hide();
					manageAddonsModal = $("<div id=\"manageAddonsModal\"></div>").appendTo(newModal);
				}
				
				manageAddonsModal.openModal({
					ajaxContent: true,
					ajaxPath: targetLink,		
					openCallback: function() {
						// Set up vertical scrolling
						var curPlans = $("#manageAddonsModal .phonePlanHolder .moduleDefault:visible");
						var planHolder = $("#manageAddonsModal .phonePlanHolder");
						var currentScrollbarWidth = Sprint.fn.getScrollbarWidth();
						
						if (curPlans.length > 2) {
							// Get the combined height of the first two modules
							var height = $(curPlans.get(0)).outerHeight() + $(curPlans.get(1)).outerHeight();
							height += parseInt($(curPlans.get(0)).css("margin-bottom"))*2;
							
							planHolder.height(height).width(CHANGE_PLAN_MODAL_WIDTH).css({
								"overflow-y": "auto"
							});
						} else {
							planHolder.width(CHANGE_PLAN_MODAL_WIDTH-currentScrollbarWidth).css({
								overflow: "hidden",
								height: "auto"
							});
						}
						if (manageAddonsModal.find("#serviceSelectionSaved").length > 0) {
							manageAddonsModal.find("#btnDoneSaveChanges").bind("click", function(event) {
								event.preventDefault();
								$("a.closeModal").trigger("click");
							});
							
							manageAddonsModal.find("#btnPickAnotherPhone").bind("click", function(event) {
								event.preventDefault();
								// Load the add phones modal, then call setup.
								Sprint.modal.elem.loadModalContent("/global/shop/modals/swapPlanModal.php", swapPlanModal);
								setupManageAddonsModal();
							});
						}
						else {
							setupManageAddonsModal();
						}
					},
					width: MANAGE_ADDONS_MODAL_WIDTH
				});
				
				return false;
			});
			
			// Setup the clickable devices for the manage addons modal.
			function setupManageAddonsModal() {
				// hide all update messages by default
				$("#manageAddonsModal .updateMessage").hide();
				
				if ($("#manageAddonsModal .modulePlain").hasClass("contextModal")) {
					manageAddonsSetUpScrolling();
				}
				else {	
					// Set up hovers (for ie6)
					$("#manageAddonsModal ul.accountPhoneSelector li").hover(
						function() { $(this).addClass("hover");	},
						function() { $(this).removeClass("hover"); }
					);
					
					// Now when one of the li's is clicked, make it selected and add it to the form 
					$("#manageAddonsModal ul.accountPhoneSelector li").bind("click", function(event) {
						var self = $(this);
						var module = $(this).closest(".moduleDefault");
						var updateMessage = module.find(".updateMessage");
						
						// If selection in the group is disabled via special 
						// `disableSelection` class, then show update message
						// within this group and don't toggle existing selection.
						if (self.hasClass("disableSelection")) {
							updateMessage.show();
							// copy person's name and phone number into the message
							updateMessage.find(".phoneNumber").text(self.find(".phoneNumber").text());
							updateMessage.find(".personName").text(self.find(".personName").text());
							makeLiUnselected("#manageAddonsModal ul.accountPhoneSelector");
							$("#manageAddonsModal ul.accountPhoneSelector li").removeClass("active");
							$(this).addClass("active");
							$("#btnManageAddonsSubmit").addClass("disabled");
						} else {
							updateMessage.hide();
							if ($(this).hasClass("active")){
								makeLiUnselected(this);
							} else {
								if ($(this).closest(".modulePlain").hasClass("selectOneItemOnly")) {
									makeLiUnselected("#manageAddonsModal ul.accountPhoneSelector li");
								}
								makeLiSelected(this);
							}
						}
					});
					
					// Enable the button if needed
					if ($("#manageAddonsModal ul.accountPhoneSelector li.active").length > 0) {
						$("#manageAddonsModal #btnManageAddonsSubmit").removeClass("disabled");
					}
				}
			}
			
			// Sets up vertical scrolling on the manage addons modal
			function manageAddonsSetUpScrolling() {
				var curPlans = $("#manageAddonsModal .phonePlanHolder .moduleDefault:visible");
				var planHolder = $("#manageAddonsModal .phonePlanHolder");

				//Reset the height each time so that if the height is less than 400, we don't show a bunch of white space...
				planHolder.height("");

				if (planHolder.outerHeight() > 400) {
					planHolder.height(400).width(MANAGE_ADDONS_MODAL_WIDTH).css({
						"overflow-y": "auto"
					});
					
					if ($.browser.msie && $.browser.version == 8) {
						curPlans.each(function() {
							$(this).css({
								"clear": "both"
							});
						});
					}
				}
			}
			
			// Changes li to a selected style and adds the li info to the form
			function makeLiSelected(liElement) {
				var liEl = $(liElement);
				
				// Only do stuff if it's not already selected
				if (!liEl.hasClass("active")) {
					liEl.addClass("active");
					liEl.append("<div class=\"currentAccountPhone\">" +
											"<img src=\"/global/images/icons/ico_confirmation_sml.gif\" alt=\"currently selected\" />" +
											"<br/>Selected</div>");
					
					$("#selectedPhoneId").val(liEl.find(".phoneID").html());
					$("#selectedPlanSkuId").val(liEl.find(".planSkuID").html());
					/* Tech Implementation Plan display field for MAA flow */
					$("#selectedPlanNumber").val(liEl.find(".planDisplayNumber").html());
					$("#selectedPlanProductId").val(liEl.find(".planProductID").html());
					$("#selectedSubscriberId").val(liEl.find(".subscriberID").html());
					
					// Enable the button
					$("#manageAddonsModal #btnManageAddonsSubmit").removeClass("disabled");
				}
			}
			
			// Changes li to an unselected style and removes the li info from the form
			function makeLiUnselected(liElement) {
				$(liElement).each(function() {
					var liEl = $(this);
					
					liEl.find(".currentAccountPhone").remove();
					liEl.removeClass("active");
				
					$("#selectedPhoneId").val("");
					$("#selectedPlanSkuId").val("");
					/* Tech Implementation Plan display field for MAA flow */
					$("#selectedPlanNumber").val("");
					$("#selectedPlanProductId").val("");
					$("#selectedSubscriberId").val("");
				});
				
				// Disable the button
				$("#manageAddonsModal #btnManageAddonsSubmit").addClass("disabled");
			}
		
		})();
		
		
		/* Login Modal (currently used in 5.1 Services Landing)
		-----------------------------------------------------------------------------*/
		(function() {
			function bindLoginActionEvents(parent, frmSelector) {
		 
				var validation;
				var signInFields = {
					txtUsername: {
						name: 'USER',
						type: 'username',
						required: true,
						emptyErrorMessage: Sprint.fn.getContentString("formFieldErrors.usernameEmpty"),
						invalidErrorMessage: Sprint.fn.getContentString("formFieldErrors.usernameInvalid")
					},
					txtPassword: {
						name: 'PASSWORD',
						type: 'password',
						required: true,
						emptyErrorMessage: Sprint.fn.getContentString("formFieldErrors.passwordEmpty"),
						invalidErrorMessage: Sprint.fn.getContentString("formFieldErrors.passwordInvalid")
					}
				};

				// Sign In selection
				var frmSignIn = $(frmSelector);
				frmSignIn.bind('submit', function(event) {
					event.preventDefault();

					parent.find('ul.formErrors').remove();
					parent.find('input.error').removeClass('error');
					
					validation = Sprint.fn.validateForm(frmSignIn, signInFields);
					if (validation == true) {
						
					
						$.ajax({
							url: frmSignIn.attr('action'),
							data: 'action=signin&' + frmSignIn.serialize(),
							async: false,
							dataType: 'json',
							success: function(data) {
								if (data.validated) {
									window.location = data.redirectUrl || data.nextPage;
								}
								else {
									frmSignIn.find('input.error').removeClass('error');
									frmSignIn.find('label.error').remove();
									frmSignIn.showFormErrors({
										showInline: false,
										summaryAnchor: frmSignIn.parent().find(".headerWrapperPrimary"),
										scrollToSummary: false,
										errorData: data.errorData
									});
								}
							},
							error: Sprint.fn.ajaxError
						});
					}
					else {
						frmSignIn.find('input.error').removeClass('error');
						frmSignIn.find('label.error').remove();
						frmSignIn.showFormErrors({
							showInline: false,
							summaryAnchor: frmSignIn.parent().find(".headerWrapperPrimary"),
							scrollToSummary: false,
							errorData: validation
						});
					}
				});
				frmSignIn.find('#btnSignIn').bind('click', function(event) {
					frmSignIn.submit();
				});
			}
			

			
			if ($('#signInIntercept').length > 0) {
				bindLoginActionEvents($('#signInIntercept'), '#signInIntercept #frmSignIn');
			}
			
			$('#btnOrderServiceLogInTrigger, .loginModalTrigger').bind('click', function(event) {
				// TEALEAF SESSION TRACKING
				if (typeof(TeaLeaf) != "undefined" &&  typeof(TeaLeaf.Client) != "undefined") {
					TeaLeaf.Client.tlAddEvent(event);
				}
				event.preventDefault();
				
				var logInToOrderModal = $('#logInToOrderModal');
				if (logInToOrderModal.length < 1) {
					var newModal = $("<div class=\"modal\"></div>").appendTo("div.sprint div.body").hide();
					logInToOrderModal = $("<div id=\"logInToOrderModal\"></div>").appendTo(newModal);
				}
				
				logInToOrderModal.openModal({
					width: 340,
					ajaxContent: true,
					ajaxPath: $(this).attr('href'),
					openCallback: function() {
						if ($("#logInToOrderModal").find("#frmUserLoginDL").length > 0) {
							Sprint.signInFormProcess();
						}
						bindLoginActionEvents(logInToOrderModal, '#logInToOrderModal #frmSignIn');
					}
				});
			});
	
	
			$.fn.bindLoginActionEvents = function (settings) {
					
					$.extend(settings);

					bindLoginActionEvents(settings.parent, settings.frmSelector);
			
			}
		})();
		// TECH IMPLEMENTATION
		/*
		TeaLeaf.Client.tlProcessNode('document.body');
		*/
		
		/* Device User Authorization Request
		-------------------------------------------------*/
		(function() {
			var reqAccAuth = $("#requestAccountAuth, .requestAccountAuth");

			reqAccAuth.die("click").live("click", function(event) {
				// TEALEAF SESSION TRACKING
				if (typeof(TeaLeaf) != "undefined" &&  typeof(TeaLeaf.Client) != "undefined") {
					TeaLeaf.Client.tlAddEvent(event);
				}
				event.preventDefault();

				// Setup the modal
				var targetLink = $(this).attr("href");
				var reqAccAuthModal = $("#requestAccountAuthorizationModal");

				if (reqAccAuthModal.length < 1) {
					var newModal = $("<div class=\"modal\"></div>").appendTo("div.sprint div.body").hide();
					reqAccAuthModal = $("<div id=\"requestAccountAuthorizationModal\"></div>").appendTo(newModal);
				}

				// Call ajax to find out what content to show in the modal
				$.ajax({
					url: targetLink,
					data: "ajax=true",
					type: "GET",
					async: false,
					cache: false,
					dataType: "json",
					success: function(data) {

						// Open the initial modal window
						reqAccAuthModal.openModal({
							ajaxContent: true,
							ajaxPath: data.responseUrl + "?accountOwner=" + data.accountOwner,
							width: 330,
							openCallback: function() {
								var modal = $("#accountAuthorization");

								// Bind the request authorization button to load the new confirmation modal
								// if the request was sent successfully. There is no case for the request failing.
								modal.find("#btnAccountAuthorizationRequest").unbind("click").bind("click", function(event) {
									event.preventDefault();

									$.ajax({
										url: targetLink,
										data: "ajax=true&sendRequest=true",
										type: "GET",
										async: false,
										cache: false,
										dataType: "json",
										success: function(data) {
											if (data.requestSent) {
												Sprint.modal.elem.loadModalContent(data.responseUrl + "?accountOwner=" + data.accountOwner, modal.find("div.modalSummaryWrapper"));

												modal.find("#btnAccountAuthorizationCancel").unbind("click").bind("click", function(event) {
													event.preventDefault();
													$("a.closeModal").trigger("click");
												});
											}
										},
										error: Sprint.fn.ajaxError
									});

								});

								// Bind the cancel/done button.
								modal.find("#btnAccountAuthorizationCancel").unbind("click").bind("click", function(event) {
									event.preventDefault();
									$("a.closeModal").trigger("click");
								});
							}
						});
					},
					error: Sprint.fn.ajaxError
				});
			});
		})();
		//This is for community username form
		(function() {
			var commUserFormId = $("#commUserRegistration");
			var commUserFormFieds = {
				txtPreferencesDisplayName: {
					name: "txtPreferencesDisplayName",
					type: "displayName",
					required: true,
					mustNotMatch: "txtPreferencesUserName",
					emptyErrorMessage: Sprint.fn.getContentString("formFieldErrors.displayNameEmpty"),
					invalidErrorMessage: Sprint.fn.getContentString("formFieldErrors.displayNameInvalid"),
					existsErrorMessage: Sprint.fn.getContentString("formFieldErrors.displayNameExists"),
					customValidationRule: function(field) {
						var fieldValue = field.val();
						var validDisplayName = "";
						//First, make sure the value follows the correct format
						if (!Sprint.formFieldTypes.displayName.test(fieldValue)) {
							//Reset the invalid error message if it's been overwritten
							if (commUserFormFieds.txtPreferencesDisplayName.temporaryErrorMessage) {
								commUserFormFieds.txtPreferencesDisplayName.invalidErrorMessage = commUserFormFieds.txtPreferencesDisplayName.temporaryErrorMessage;
							}
							return false;
						}
						else {
							//Run an ajax request to check and see that this Username is available
							$.ajax({
								data: "validateDisplayName=true&txtPreferencesDisplayName="+fieldValue,
								type: "POST",
								url: $("#hidAjaxFormHandler").val(),
								async: false,
								success: function(data) {
									validDisplayName = parseInt(data);
								},
								error: function(event) {
									validDisplayName = false;
								}
							});								
						}

						if (!validDisplayName) {
							//re-set the invalid username message to the User Exists message (store the invalid message for use later)
							commUserFormFieds.txtPreferencesDisplayName.temporaryErrorMessage = commUserFormFieds.txtPreferencesDisplayName.invalidErrorMessage;
							commUserFormFieds.txtPreferencesDisplayName.invalidErrorMessage = commUserFormFieds.txtPreferencesDisplayName.existsErrorMessage;
						}
						
						return validDisplayName;
					}						
				},
				txtPreferencesUserName: {
					name: "txtPreferencesUserName",
					type: "username",
					required: true,
					mustNotMatch: "txtPreferencesDisplayName",
					emptyErrorMessage: Sprint.fn.getContentString("formFieldErrors.usernameEmpty"),
					invalidErrorMessage: Sprint.fn.getContentString("formFieldErrors.usernameInvalid"),
					existsErrorMessage: Sprint.fn.getContentString("formFieldErrors.usernameExists"),
					customValidationRule: function(field) {
						
						var fieldValue = field.val();
						var validUsername = "";
						var notMatchesDiaplayName = true;
						
						//First, make sure the value follows the correct format
						if (!Sprint.formFieldTypes.username(field)) {
							//Reset the invalid error message if it's been overwritten
							if (this.temporaryErrorMessage) {
								this.invalidErrorMessage = this.temporaryErrorMessage;
							}
							return false;
						}
						else {
							//Run an ajax request to check and see that this Username is available
							$.ajax({
								data: "validateUsername=true&txtPreferencesUserName="+fieldValue,
								type: "POST",
								url: $("#hidAjaxFormHandler").val(),
								async: false,
								success: function(data) {
									validUsername = parseInt(data);
								},
								error: function(event) {
									validUsername = false;
								}
							});								
						}

						if (fieldValue.toLowerCase() == commUserFormId.find("[name='txtPreferencesDisplayName']").val().toLowerCase()) {
							notMatchesDiaplayName = false;
						}

						if (!validUsername) {
							//re-set the invalid username message to the User Exists message (store the invalid message for use later)
							this.temporaryErrorMessage = this.invalidErrorMessage;
							this.invalidErrorMessage = this.existsErrorMessage;
						}
						
						if (!notMatchesDiaplayName) {
							validUsername = false;
							this.invalidErrorMessage = Sprint.fn.getContentString("formFieldErrors.usernameMatchesDisplayname");
						};
						
						return validUsername;
					}						
				}
			};
			
			
			//Do some validation on the form fields on tab-out
			commUserFormId.find("input.text").bind("blur", function(event){
				var currentField = $(this);

				//If this field already has an error, clear the error first
				if (currentField.hasClass("error")) {
					currentField.removeClass("error");
					commUserFormId.find("label.error[for='"+$(this).attr("id")+"']").remove();
				}

				validField = Sprint.fn.validateForm(commUserFormId, {field: commUserFormFieds[$(this).attr("id")]});
				if (typeof(validField) != "boolean") {
					commUserFormId.showFormErrors({					
						errorData: validField,
						showSummary: false
					});
				}
			});
			
			commUserFormId.find('#formSave').unbind("click").bind("click",function(e){
				e.preventDefault();
				var validForm = Sprint.fn.validateForm(commUserFormId, commUserFormFieds);
				
				if(validForm ==  true){
					var formData =  $("input.text").serialize()+"&commFormSubmit=true";
					$.ajax({
						data: formData,
						type: "POST",
						url: $("#hidAjaxFormHandler").val(),
						dataType: "json",
						async: false,
						success: function(result){
							if(result.validate){
								commUserFormId.find("#formSave_original").trigger("click");
								return false;
							}else{
								commUserFormId.showFormErrors({
									errorData: {
										txtPreferencesUserName: {
											name: "txtPreferencesUserName",
											errorMessage: result.errorMessage
										}
									},
									
									showInline: true,
									summaryAnchor: commUserFormId.find(".headerWrapperPrimary"),
									scrollToSummary: false
								});
							}
						},
						error: Sprint.fn.ajaxError
					});
				}else {
					$("label.error").remove();
					commUserFormId.showFormErrors({
						errorData: validForm,
						summaryAnchor: commUserFormId.find(".headerWrapperPrimary"),
						showInline: true,
						showSummary: false
					});
				}
			});
			
			
		})();
		
	});
	
	/*  Begin: 0315Merge - mysprint.js removal
		  - Merging mysprint.js into global.js
	*/

		
		(function() {
			// Set up capabilities hover states for IE6
			if ($.browser.msie && $.browser.version == 6) {
				$("ul.capabilitiesLarge > li > a.icon > img").hover(
					function() { $(this).addClass("hover");	},
					function() { $(this).removeClass("hover"); }
				);
			}
			
			// Set up the blue hover states
			$("div.bluehover .bluehover_header").each(function() {
				$(this).hoverbox();
			});
			$("div.bluehover .bluehover_header > a").bind("click", function(event) { event.preventDefault(); });
			
		})();

		/* GT: This handles the disabling of submit buttons for deep linking requiring assistance modals. */
		(function() {
		
			$(".requiringAssistance input.button0").unbind("click").bind("click", function(event) {
				event.preventDefault();
			});
		
		})();
		
		/* BEGIN: Omniture survey function for the top nav feedback link for the Biz3.0 project */
		$(document).ready(function(){
			function openFBSurvey(){
				try {
					Analytics._numeric_.omni.trackBiz3Surveys("feedback");
				} catch(e) {
				
				}
			}
			$('#feedbackSurvey').bind('click', function(e){openFBSurvey();});
			$('#feedbackSurvey').attr('href','#');
		});
		/* BEGIN: Omniture survey function for the top nav feedback link for the Biz3.0 project */
		
	/* End: 0315Merge - mysprint.js removal */

})(jQuery);
