/* ===COMMON MY SPRINT SCRIPTS=== */
(function($) {
	
	$(function() {
		
		(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(); });
			
		})();

		//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"});
				});
			}
		
			$("#iWantToAddAPhone, a.addAPhone").bind("click", function() {
				
				/* go back if you are in checkout confirmation page | Fix for defect 435243 */
				if($('#checkoutOrderConfirmation').length > 0){
					return;
				}
				
				targetLink = $(this).attr("href");
	
				var addPhoneModal = $("#addPhoneModal");
				
				if (addPhoneModal.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();
		
					addPhoneModal = $("<div id=\"addPhoneModal\"></div>").appendTo(newModal);
				}
				
				addPhoneModal.openModal({
					ajaxContent: true,
					ajaxPath: targetLink,
					openCallback: function() {
						// If they can't add a phone, show them a warning before allowing the user to proceed
						if (addPhoneModal.find("#unableToAddPhone").length > 0) {
							addPhoneModal.find("#btnCancelAddPhone").bind("click", function(event) {
								event.preventDefault();
								$("a.closeModal").trigger("click");
							});
							
							addPhoneModal.find("input.button1").bind("click", function(event) {
								event.preventDefault();
								// Load the add phones modal, then call setup.
								Sprint.modal.elem.loadModalContent("/mysprint/pages/secure/BaseAjaxServlet?pageContext=addPhone&nocheck=yes", addPhoneModal);
								setupAddPhoneModal();
							});
						}
						else {
							setupAddPhoneModal();
						}

						// TEALEAF SESSION TRACKING
						if (typeof(TeaLeaf) != "undefined" &&  typeof(TeaLeaf.Client) != "undefined") {
							TeaLeaf.Client.tlProcessNode('document.body');
						}

					}
				});
				
				return false;			
			
			});
		
			
			/* Change Plan Modal */
			var CHANGE_PLAN_MODAL_WIDTH = 700;
			
			// Bind the swap plan modal to the swap plan link
			$("a.changePlanModalTrigger, a.deviceLevelCPModalTrigger").bind("click", function() {
				targetLink = $(this).attr("href");
				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() {
						$("#swapPlanModal #selChangeAccountModal").bind("change", function(event) {
							// Hide all the plan holders
							$("#swapPlanModal div.moduleDefault").hide();
							// Merged from 10.4
							//Disable the Change Plan button until we're sure it's OK to enable
							$("#swapPlanModal #btnChangePlan").addClass("disabled");
							// END Merged from 10.4
							// Show the plan holders which match the value of the current account selection
							$("#swapPlanModal div." + $(this).val()).show();
							
							// Set up vertical scrolling
							var curPlans = $("#swapPlanModal .phonePlanHolder .moduleDefault:visible");
							var planHolder = $("#swapPlanModal .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"
								});
							}
							
							// Merged from 10.4
							//If any visible radio buttons are pre-checked, remove the disabled class from the button.
							if ($("#swapPlanModal input[name='radChangePlan']:visible").filter(":checked").length) {
								$("#swapPlanModal #btnChangePlan").removeClass("disabled");
							}
							// END Merged from 10.4
							
							// Bind the radio buttons
							$("#swapPlanModal input[name='radChangePlan']").unbind("click").bind("click", function(event) {
								$("#swapPlanModal #btnChangePlan").removeClass("disabled");
							});
						});
						
						// Trigger the change event for the initial scroll setup
						$("#swapPlanModal #selChangeAccountModal").trigger("change");
					},
					width: CHANGE_PLAN_MODAL_WIDTH
				});
				
				return false;
			});
			
			
			/* Manage Add-ons Modal */
			var MANAGE_ADDONS_MODAL_WIDTH = 700;
			
			// Bind the manage addons modal to the manage addons link
			$("a.manageAddonsModalTrigger, a.deviceLevelMAModalTrigger").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() {
						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/mysprint/myaccount/modals/swapPlanModal.php", swapPlanModal);
								setupManageAddonsModal();
							});
						}
						else {
							setupManageAddonsModal();
						}

						// TEALEAF SESSION TRACKING
						if (typeof(TeaLeaf) != "undefined" &&  typeof(TeaLeaf.Client) != "undefined") {
							TeaLeaf.Client.tlProcessNode('document.body');
						}
				
					},
					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());
						} else {
							updateMessage.hide();
							if ($(this).hasClass("active")){
								makeLiUnselected(this);
							} else {
								if ($(this).closest(".modulePlain").hasClass("selectOneItemOnly")) {
									makeLiUnselected("#manageAddonsModal ul.accountPhoneSelector li");
								}
								makeLiSelected(this);
							}
						}
					});
					
					// When the account select changes, we need to change the contents of the modal
					$("#manageAddonsModal #selChangeAccountModal").bind("change", function(event) {
						var modal = $("#manageAddonsModal div." + $(this).val());
						var button = $("#manageAddonsModal #btnManageAddonsSubmit");
						
						// Hide all the plan holders
						$("#manageAddonsModal div.moduleDefault").hide();
						
						// Show the plan holders which match the value of the current account selection
						modal.show();
						
						button[modal.find(".accountPhoneSelector .active").length > 0
							? 'removeClass' : 'addClass' ]("disabled");
						
						// Set up vertical scrolling
						manageAddonsSetUpScrolling();
					});
					
					// Trigger the change event for the initial scroll setup
					$("#manageAddonsModal #selChangeAccountModal").trigger("change");
					
					// 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");
				
				// Merged from 10.4				
				//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("");
				// Merged from 10.4
				
				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());
					$("#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("");
					$("#selectedPlanProductId").val("");
					$("#selectedSubscriberId").val("");
				});
				
				// Disable the button
				$("#manageAddonsModal #btnManageAddonsSubmit").addClass("disabled");
			}
		
		})();
          
		
		/* 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();
			});
		
		})();
		
		
		/* Device User Authorization Request
		-------------------------------------------------*/
		(function() {
			var reqAccAuth = $(".requestAccountAuth");

			reqAccAuth.die("click").live("click", function(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,
					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,
										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: function(event) {
											alert("error communicating with server\n\nStatus: " + event.status);
										}
									});

								});

								// Bind the cancel/done button.
								modal.find("#btnAccountAuthorizationCancel").unbind("click").bind("click", function(event) {
									event.preventDefault();
									$("a.closeModal").trigger("click");
								});
							}
						});
					},

					error: function(event) {
						alert("error communicating with server\n\nStatus: " + event.status);
					}

				});

			});
		})();
	
		/* START - Loading third party url in iframe modal */
			if ($("#termsConditions, .termsConditions").length){
				$("#termsConditions, .termsConditions").unbind("click").bind("click", function(event) {
					event.preventDefault();
					var terms = $(this);
					var checkExtURL = terms.attr("href");
					var termsConditionsModal = $("#termsConditionsModal");				
					if (termsConditionsModal.length < 1) {					
						var newModal = $("<div class=\"modal\"></div>").appendTo("div.sprint div.body").hide();		
						termsConditionsModal = $("<div id=\"termsConditionsModal\"></div>").appendTo(newModal);
					}				
					termsConditionsModal.openModal({
						width: 700,
						openCallback: function(){
							if(checkExtURL.indexOf('//shop2.sprint') > 0){
								termsConditionsModal.html("<div id=\"modalSpinner\">"+Sprint.fn.getContentString("modal.loadingText")+"</div><iframe id=\"modalIframe\" style=\"display:none;\" src=\""+checkExtURL+"\" frameborder=\"0\" scrolling=\"auto\" height=\"470\" width=\"700\"></iframe>");
							} else {
								termsConditionsModal.html("<div id=\"modalSpinner\">"+Sprint.fn.getContentString("modal.loadingText")+"</div><iframe id=\"modalIframe\" style=\"display:none;\" src=\""+checkExtURL+"\" frameborder=\"0\" scrolling=\"no\" height=\"470\" width=\"700\"></iframe>");
							}
							
							Sprint.modal.elem.sizeModal();
							$('#modalIframe').load(function() {
								$(this).addClass('sprint').show();
								$("#modalSpinner").hide();
								Sprint.modal.elem.sizeModal();
								$("h2.corporate").sifr({
									path: "/global/flash/",
									font: "sifr",
									textAlign: "left",
									fontSize: "26px"
								});								
							});
						}
					});				
				});
			}
		/* Show Me option option on confirmation page */
			$("#revealAccountPIN a").unbind("click").bind("click",function(e){
				if (typeof(TeaLeaf) != "undefined" &&  typeof(TeaLeaf.Client) != "undefined") {
					TeaLeaf.Client.tlAddEvent(e);
				}
				e.preventDefault();
				var pinField = $("#pinNumber");
				var newField = $("#hidPinVal");
				
				if (pinField.attr("type").toLowerCase() == "password") {
					//Change the type to a regular text field
					pinField.html('PIN: <encrp2>' + newField.val()+'</encrp2>');
					pinField.attr('type','value');
					$(this).text(Sprint.fn.getContentString("mySprint.myPreferences.preferencesModal.hidePinMessage"));
				}else {
					//Change the type to a password field
					pinField.html('PIN:<encrp2> ******</encrp2>');
					pinField.attr('type','password');
					$(this).text(Sprint.fn.getContentString("mySprint.myPreferences.preferencesModal.showPinMessage"));
				}
				return false;

			});


	});
	
})(jQuery);
