// JavaScript Document
(function($) {

/* ===COMMON SUPPORT SCRIPTS=== */

/* DEVICE SELECTOR */
	/* override disclosure styles for .deviceSelector */
	$(function() {
		$(".deviceSelector").disclosure({
			startClosed: true	
			//startClosed: false
		});
	});
		
	/* position device selector content absolute with javascript */
	$(function() {
		$("#selectDevice .disclosureContent").css("position","absolute");	
	});
	
	
	/* Phone Manufacturer/Model Filter */
	/* USAGE: All phone models are loaded initially. Manufacturer option VALUE in markup must match model option CLASS. */
	$(function() {
	
		var originalModelList = $("#frmFindSupport #selPhoneModel").children().clone();

		//check the initial value of the manufacturer dropdown
		if ($("#frmFindSupport #selPhoneManufacturer").val() != "0") {
			$("#frmFindSupport #selPhoneModel option").not(".label, ."+$("#frmFindSupport #selPhoneManufacturer").val()).remove();
		}

	
		$("#frmFindSupport #selPhoneManufacturer").bind("change", function() {
			var newList = originalModelList.clone();
			
			$("#frmFindSupport #selPhoneModel").empty().append(newList);
			
			if ($(this).val() != "0") {
				$("#frmFindSupport #selPhoneModel option").not(".label, ."+$(this).val()).remove();
			}
		});
	
	});

	// Configure search tooltip
	$(function() {
		$("#showSearchTips").tooltip({belowAnchor:true, overrideClass:"searchTooltip"});
		$("#searchTips").hide();
	});

/* Support Landing Page
----------------------------------------------------*/
	/* PHONE CAROUSEL */
	$(function() {
		
		//carousel shim "constants"
		var SHIM_ID = "IESHIM_CAROUSEL";
		
		/*
			use this function instead of addShim because of the fancy positioning of this element		
			@param targetElementSelector String the element to put the shim on (usually the carousel selector)
		*/
		function addCarouselShim(targetElementSelector){
			
			//Only run this function for IE6-
			if ($.browser.msie && parseInt($.browser.version) < 7) {
				
					//only rub this function if the shim does not exist
					if( $("#"+SHIM_ID).length > 0 ){
						return false;
					}

					var el = $(targetElementSelector);

					//Get the current element's position on the page and its dimensions, then create a shim that's the same size and place it behind the current element.
					var props = {				
						offset: el.offset(),
						width: el.outerWidth(),
						height: el.outerHeight()
					}

					//modify the args for the fancy positioning (very specific)
				var parent = el.parents(".phoneCarouselWrapper");
					//var parent = $("#modalHolder");
					
					props.height += 80;
					props.width = 705;

					var newShim = $("<iframe src=\"javascript:false;\" id=\""+SHIM_ID+"\"></iframe>").css({
						position:  "absolute",
						top:       props.offset.top+"px",
						left:      props.offset.left+"px",
						margin:    0,
						padding:   0,
						width:     props.width+"px",
						height:    props.height+"px",
						border:    "none",
						opacity:   0,
						"z-index": 10
					});

					newShim.appendTo("body");
			}
		}
		
		
		/*
			this function used in conjunction with the above for shimming
			
		*/
		function removeCarouselShim(){
			//Only run this function for IE6-
			if ($.browser.msie && parseInt($.browser.version) < 7) {
				if( $("#"+SHIM_ID).length > 0 ){
					$("#"+SHIM_ID).remove();
				} else {
					return false;
				}
			}
		}
	
		/* 
			sets up the phone selector carousel
			@param String carouselSelector - the css selector for the phone carousel (<div> which contains a <ul> with lis for each phone)
			@param String manufacturerSelectSelector - the css selector for the <select> which filters carousel based on mfg
			@param Array chromeList - an array of Objects, each element looking as follows:
						{	selector: "css selector for chrome element", order: "(before|after)" }
						Where order determines whether or not the animation happens before or after the carousel
		*/
		function setUpCarousel(carouselSelector, manufacturerSelectSelector, chromeList, parentHiderSelector, inModal){
			//set up defaults
			if(!inModal){
				inModal = false;
			}	
			
			//setUpCarousel("#selectorPhoneCarousel", "#selectorSelManufacturer", chrome, "#selectDevice .disclosureToggle");
			//cache all frequently used elements
			var carouselElement = $(carouselSelector);
			var selectorElement = $(manufacturerSelectSelector);
			
			var originalCarouselData = $(carouselSelector+" ul").clone();
			//If the manufacturers drop-down has a selected value on page load, filter the carousel right away
			if (selectorElement.val() != 0 && selectorElement.val() != -1) {
				$(carouselSelector+" ul").find("li:not(.manufacturer_"+selectorElement.val()+")").remove();
			}

			if(inModal){
				selectorElement.bind("change", function() {
				//Omniture :Tracking the opening of the device carousel
					if($("#OmnitureCalls").val() == "false") {
						Analytics.Support.screenChangeHelperFunction("deviceSelector");
					}
					if ($(this).val() == "-1") {
						return false
					}

					$("#selManufacturerModal").val($(this).val());

					anchorTarget = "#phoneSelector";
					
					$(anchorTarget).openModal({

						openCallback: function() {
							
							$('#IESHIM_'+Sprint.ieShims.currentShims).css("zIndex","11");

							$(anchorTarget).setupComponents({
								buttons: false
							});

							var originalModalCarouselData = $("#modalPhoneCarousel ul").clone();

							//If the manufacturers drop-down has a selected value on page load, filter the carousel right away
							if ($("#selManufacturerModal").val() != 0) {
								getSelMDevices($('#selManufacturerModal').val(),$('#modalPhoneCarousel'),$('#frmSelPhoneNumberModal'));
								addCarouselShim(anchorTarget); 

								//$("#modalPhoneCarousel ul").find("li:not(.manufacturer_"+$("#selManufacturerModal").val()+")").remove();
							}

							$("#selManufacturerModal").bind("change", function() {
								if ($(this).val() != -1) {
									var newList = originalModalCarouselData.clone();


							//Filter based on manufacturer
							// newList.find("li:not(.manufacturer_"+$(this).val()+")").remove();
							/* Send an AJAX Request out for the selected manufacturer.
							1.@mId: Manufacturer ID as the value of the combobox.
							2.@carouselContainer: jQuery Object of the Carousel container.
							3.@Dataholder: jQuery Object where the lists which have been already printed will be stored using the jQuery Data method.
							*/
							getSelMDevices($('#selManufacturerModal').val(),$('#modalPhoneCarousel'),$('#frmSelPhoneNumberModal'));
							
									//Replace the list
									$("#modalPhoneCarousel").empty().append(newList);

									$("#modalPhoneCarousel").carousel().slideDown("medium");
								}
								else {
									
									$("#modalPhoneCarousel").slideUp("medium");
								}

							});

							$("#modalPhoneCarousel").carousel();
								
							//Hide the carousel to begin with as long as no value is selected
							if ($("#selManufacturerModal").val() == -1) {
								$("#modalPhoneCarousel").hide();
							}

						}	,
							closeCallback:function() {
								removeCarouselShim();
							}
					});
				});
			} else {
				var originalCarouselData = $(carouselSelector+" ul").clone();
						
				selectorElement.bind("change", function() {
					if ($(this).val() != -1) {
						var newList = originalCarouselData.clone();


							//Filter based on manufacturer
							//newList.find("li:not(.manufacturer_"+$(this).val()+")").remove();
							/* Send an AJAX Request out for the selected manufacturer.
							1.@mId: Manufacturer ID as the value of the combobox.
							2.@carouselContainer: jQuery Object of the Carousel container.
							3.@Dataholder: jQuery Object where the lists which have been already printed will be stored using the jQuery Data method.
							*/
							getSelMDevices($(this).val(),$('#phoneCarousel'),$('#modulePhoneSelector'));
						

						//Replace the list
						$(carouselSelector+" ul").parent().empty().append(newList);

						$(carouselSelector).carousel().slideDown("medium");
					}
					else {
						$(carouselSelector).slideUp("medium");
					}

				});
				
			}//if(inModal)
			carouselElement.css('display', 'block');
			carouselElement.carousel();
			
			//Hide the carousel to begin with as long as no value is selected
			/*if (selectorElement.val() == -1) {
				
				carouselElement.hide();
				for( var i in chromeList ){
					$(chromeList[i].selector).hide();
				}
			}*/
			
			
			//bind the parent disclosure to kill the shim, if necessary
			if ( parentHiderSelector && $.browser.msie && parseInt($.browser.version) < 7) {
				$(parentHiderSelector).bind("click",  function(){
					if( $("#"+SHIM_ID).length > 0 ){
						//alert("carouselElement: " + carouselElement + " , " + SHIM_ID)
						removeCarouselShim();
					} else if( $("#"+SHIM_ID).length < 1 && $(carouselSelector+":visible").length > 0 ) {
						
						addCarouselShim(carouselSelector);
					}
				});
			}
			
		}//end of setUpCarousel
		
		//set content to absolute for visual purposes (it is set relative for accessibility purposes
		$(".selectorPhoneCarouselContent").css("position", "absolute");
		$(".selectorPhoneCarouselBottom").css("position", "absolute");
		$(".selectorPhoneCarouselBottom").css("top", "225px");
		
		
		var chrome = new Array({ selector: "#frmFindSupport .selectorPhoneCarouselTop", order: "before" },
								{ selector: "#frmFindSupport .selectorPhoneCarouselContent", order: "before" },
								{ selector: "#frmFindSupport .selectorPhoneCarouselBottom", order: "before" }
						);
								
		setUpCarousel("#phoneCarousel", "#selManufacturer");
		setUpCarousel("#selectorPhoneCarousel", "#selectorSelManufacturer", chrome, "#selectDevice .disclosureToggle", true);
		
		/* to open carousel in a modal */
		$("#changeDeviceLink").bind("click", function() {
		
			//Omniture : tracking the opening of the device Selecptor.
			if($("#OmnitureCalls").val() == "false"){
				Analytics.Support.screenChangeHelperFunction("deviceSelector");
			}

			//Find the anchor target that this links to (id for carousel)
			var anchorTarget = $(this).attr("href");
			
			//strip off everything before the "#"
			anchorTarget = anchorTarget.substr(anchorTarget.indexOf("#"));
			
			$(anchorTarget).openModal({

				openCallback: function() {
					
					$(anchorTarget).setupComponents({
						buttons: false
					});
					
					var originalModalCarouselData = $("#modalPhoneCarousel ul").clone();
					$('#modalPhoneCarousel .phoneSelector').css('display', 'block');
					//If the manufacturers drop-down has a selected value on page load, filter the carousel right away
					if ($("#selManufacturerModal").val() != 0) {
						//$("#modalPhoneCarousel ul").find("li:not(.manufacturer_"+$("#selManufacturerModal").val()+")").remove();
						
					}
			
					$("#selManufacturerModal").bind("change", function() {
						if ($(this).val() != -1) {
							var newList = originalModalCarouselData.clone();
				
								
								//Filter based on manufacturer
								//newList.find("li:not(.manufacturer_"+$(this).val()+")").remove();
								/* Send an AJAX Request out for the selected manufacturer.
							1.@mId: Manufacturer ID as the value of the combobox.
							2.@carouselContainer: jQuery Object of the Carousel container.
							3.@Dataholder: jQuery Object where the lists which have been already printed will be stored using the jQuery Data method.
							*/
							getSelMDevices($('#selManufacturerModal').val(),$('#modalPhoneCarousel'),$('#frmSelPhoneNumberModal'));
							
				
							//Replace the list
							$("#modalPhoneCarousel").empty().append(newList);
							
							$("#modalPhoneCarousel").carousel().slideDown("medium");
						}
						else {
							$("#modalPhoneCarousel").slideUp("medium");
						}
					
					});

					$("#modalPhoneCarousel").carousel();

					//Hide the carousel to begin with as long as no value is selected
					if ($("#selManufacturerModal").val() == -1) {
						$("#modalPhoneCarousel").hide();
					}
			
				}	

			});
			
			return false;
			
		});
		
		
		
		/*
		  getSelMDevices(): Prints out Manufacturer lists via JSON Queries and Re-creates Carousels.
		  @mID: String: The Manufacturer ID
		  @carouselContainer: jQuery Object that contains the Carousel Container.
		  @dataHolder: Data container that holds already printed lists
		  -> serviceURL: Provided as the value of the div id ="manufacturerService" from the HTML.
		*/

		function getSelMDevices(mId,carouselContainer,dataHolder) {
		
		

		// The URL of the JSON file.
		var serviceUrl = $('#manufacturerService').html();
		
		// Store the existing Carousel, only the default list has the .phoneSelector class
		if($(carouselContainer).find("ul").hasClass(".phoneSelector")){
				// Add our custom class and change the ID.
				 newAllCarouselID = '#allPhoneCarousel_'+$(carouselContainer).attr("id");
				//store
				dataHolder.data("carouselID",$(carouselContainer).attr("id"));
				$(carouselContainer).attr("id",'allPhoneCarousel_'+$(carouselContainer).attr("id")).attr("class","aCarousel");
				dataHolder.data("newAllCarousel",$(newAllCarouselID));

				// Store it for future use when someone selects "All Manufacturer".
				$(newAllCarouselID).hide();
				// Store the parent node of the original Carousel for other Carousels to use it.
				dataHolder.data("carouselParent",$(newAllCarouselID).parent())
				
		}
		var carouselID = dataHolder.data("carouselID")==undefined ? $(carouselContainer).attr("id") : dataHolder.data("carouselID");
		var newAllCarousel = dataHolder.data("newAllCarousel");

		var carouselParent = dataHolder.data("carouselParent");
		//The List ID that would be generated based on this selection.
		var manId = carouselID+"_"+mId+"_list";
		
		// User Chose the "All Manufacturer" link, show the default list and stop processing.
		if(mId==0) {
			// For consistency sake, store that the Carousel we are currently processing.
			dataHolder.data(manId,"allPhoneCarousel");
			//hides any visible carousels and toggles the visibility of the selected Carousel.
			carouselParent.find('div.aCarousel').each(function(i,o){$(o).hide()});
			newAllCarousel.show().carousel();
			$(newAllCarouselID).css('display', 'block');
			$(newAllCarouselID).find('ul').css('display', 'block');
			return;
		}
		
		// Locate if the current Carousel has already been requested.
		var loadedList = dataHolder.data(manId);
		
		// The Carousel list is not found, generate an JSON request.
		if(loadedList == undefined) {

		
		// loading image.
		var currentCarousel = dataHolder.data("currentCarousel");
		if(currentCarousel) $(currentCarousel).hide();
		var loadingImgPath = "/global/images/template/widgets/modal/pb_loading_spinner.gif";
		var showinsloadimg = $('#imageLoader').html()? $('#imageLoader').show():carouselParent.append("<div id=\"imageLoader\"><img src=\""+ loadingImgPath +"\" alt=\"Loading\" title=\"Loading\"</div>");

			//position the loading img
			var loadingImg = $('#imageLoader');
			if(loadingImg.css("marginTop")=="0px") {
				var leftmg = (Math.round(loadingImg.width() / 2) -50) + "px";
				loadingImg.css("marginLeft",leftmg);
				loadingImg.css("height","210px");
				loadingImg.verticalCenter();
			}
	
			
		// send the JSON request out, mId as the manufacturer ID.
				$.ajax({
					data: {manufacturerId:mId},
					type: "GET",
					// The value of the serviceUrl is picked from the DIV content of div id="manufacturerService" in the HTML markup.
					url: serviceUrl,
					dataType: "json",
					success: function(data) {
					loadingImg.hide();
							var manufacturerCarousel = "<ul id=\""+carouselID+"_"+mId+"_list\">";
							for( var i in data.device) {
							var deviceItem = data.device[i];
							// build our list out with the JSON Data.
							 manufacturerCarousel += "<li class=\"manufacturer_"+carouselID+"_"+mId+"\">"+
							 "<a href=\""+ deviceItem.link +"\">" +
							 "	<img src=\""+ deviceItem.thumb +"\" class=\"pngFix\" title=\""+ deviceItem.title +"\" height=\"130\" width=\"75\" alt=\"\" />" +
								"<span class=\"deviceName\">"+deviceItem.title+"</span>"+
								"</a></li>";
							}
							manufacturerCarousel += "</ul>";
					
					//Store a Reference that this list has been loaded already.
							dataHolder.data(manId,mId);
					//Hide any existing Carousels.
					carouselParent.find('div.aCarousel').each(function(i,o){$(o).hide()});
	
					// write the new Carousel out.
						var manufCarousel = carouselParent.append("<div class=\"aCarousel\" id=\""+carouselID+"_"+mId+"_carousel\">");
						var newCarousel = $('#'+carouselID+"_"+mId+"_carousel").append(manufacturerCarousel);
						
						$('#'+carouselID+"_"+mId+"_carousel").show();

						// Store the reference to the Current Carousel
						dataHolder.data("currentCarousel",$('#'+carouselID+"_"+mId+"_carousel"));
						newCarousel.carousel();
						
						//Activate the PNG Fix Function
							if ($.browser.msie && parseInt($.browser.version) < 7) {
									$('.pngFix').ifixpng();
							}
				
					},
					error: Sprint.fn.ajaxError
					
					});
			}
			else {
						// We have the list already, hide other Carousels and Show this one.
						carouselParent.find('div.aCarousel').each(function(i,o){$(o).hide()});
						// Show the Selected Carousel.
						$('#'+carouselID+"_"+mId+'_carousel').show();
			}
		}

	});
		

	

/* Product Profile Page
----------------------------------------------------*/

	//funtions to show/hide flyout menus
	$(function() {
		//hide flyoutInfo by default
		$("div.flyoutInfo").hide();
		
		$("a.flyout").bind("click", function() {
			//Find the anchor target that this links to
			var anchorTarget = $(this).attr("href");
			
			//strip off everything before the "#"
			anchorTarget = anchorTarget.substr(anchorTarget.indexOf("#"));
			
			if ($(anchorTarget).hasClass("visible")) {
				$(anchorTarget).hide().removeClass("visible");
				$(this).removeClass("flyoutOpen");
				$(this).parent("li.hasFlyout").removeClass("flyoutSelected");
				$(this).find("span span").removeClass("showFlyoutInfo");
				$(this).find("img.toggleArrow").attr("src","/global/images/icons/ico_flyout_arrow_open.gif");
			}
			else {
			
				//Hide any other open flyouts
				$("div.flyoutInfo").hide().removeClass("visible");
				$("a.flyout").removeClass("flyoutOpen").find("span span").removeClass("showFlyoutInfo");
				$("a.flyout").find("img.toggleArrow").attr("src", "/global/images/icons/ico_flyout_arrow_open.gif");
				$(this).parent("li.hasFlyout").removeClass("flyoutSelected");
				
				//Open the requested flyout.
				$(anchorTarget).show().addClass("visible");
				$(this).parent("li.hasFlyout").addClass("flyoutSelected");
				$(this).addClass("flyoutOpen");
				$(this).find("span span").addClass("showFlyoutInfo");
				$(this).find("img.toggleArrow").attr("src","/global/images/icons/ico_flyout_arrow_close.gif");
				
				//Scroll to the flyout if it's not entirely in view
				if (!Sprint.fn.isItemInView($(anchorTarget))) {
				
					//Determine the top offset for this flyout (we don't want to scroll to the top, we just want to scroll into view)
					var topOffset = 0;
					
					if ($(anchorTarget).outerHeight() < $(window).height()) {
						topOffset = $(window).height() - $(anchorTarget).outerHeight() - $(this).outerHeight();
					}
				
					$(this).scrollTo({
						speed: "slow",
						topOffset: topOffset
					});
				}
			}
			
			return false;
		});
	
	});

	
	$(function() {
	
		//Setup the tabs
		$(".supportCustomTab").tabbedContent({
			indexClass: "tabs"
		});
		
		$("#imageTabCarousel").carousel({
			scroll: 1,
			speed: "medium"
		});
	
	});
	
	
	/* Services Module */
	$(function() {
			   
		// By default, hide list of services for all categories
		$("#servicesModule ul.default").hide();
	   
		// Initalize Services Module and populate services on page load
		var url = $('#frmServicesModule').attr('action');
		if (url) {
			$("#servicesModule .columnDivideWrapper").load(url, "isInMyPlan=0", 
					// Callback function
					function() {
						$("#servicesModule ul.default").hide();
					}
				);
		}
		
		// Event handler to hide/show list of services for clicked category
		$("#servicesModule a.categoryHeader").live("click", function(e) {
			e.preventDefault();
			$(this).siblings(".default").slideToggle("fast", function() {
				if ($(this).is(":hidden")) {
					$(this).parent().removeClass("categoryHover");
				}
			});
			$(this).children("span").toggleClass("expanded");
		});
		
		// Add hover class on LI elements 
		$("#servicesModule li.category").live("mouseover", function(e) {
			$(this).addClass("categoryHover");
		});
			
		// Only remove hover class if the services item is collapsed
		$("#servicesModule li.category").live("mouseout", function(e) {
			if ($(this).children(".default").is(":hidden")) {
				$(this).removeClass("categoryHover");
			}
		});
		
		
		// Event handler for checkbox to only show services in user's plan
		$("#chkShowServicesInPlan").bind("click", function(e) {

			var action = $(this).parents('form:first').attr('action');
			var isInMyPlan = "0";
			
			if(this.checked) {
				isInMyPlan = "1";
			}
			
			if (action) {
				$("#servicesModule .columnDivideWrapper").load(action, "isInMyPlan=" + isInMyPlan, 
					function () {
						$("#servicesModule ul.default").hide();
					}
				);
			}

		});

	});

	
/* IMPORT VIDEO PLAYER */
/* NOTE: Intermittent loading issue with IE6 and IE7 described here:
http://www.longtailvideo.com/support/forum/Setup-Problems/5180/Intermitent-load-issue-with-I-E-6
This issue can be circumvented by setting the Flash version to v10, but works on all browsers as v9.*/

	$(function() {
		/*  flashvars used by videoPlayerBuilder.swf:
			xml_path is path to file or service which returns the video XML
			view_service_url is path to service which tracks video views (sends param called videoid)
			xml is string of actual XML.  This will be used if it is provided, otherwise the xml_path will be used to load xml
			main_swf_path (required) - path to main.swf, the companion to VideoPlayerBuilder.swf
		*/
/*
		var params = {};
		params.scale = "showall";
		params.wmode = "transparent";
		params.allowfullscreen = "true"; 	// This tells flash security that full screen flash is allowed on this page
	
		var flashvars = {};
		flashvars.xml_path = "/support/pages/herospaceVideoXml.jsp";
		flashvars.view_service_url = "/support/pages/userClickTracking.jsp";
		flashvars.main_swf_path = "/global/flash/video_player/main.swf";		
		
		var source	= "/global/flash/video_player/videoPlayerBuilder.swf?";
		for(prop in flashvars)
		{
			source += prop + "=" + flashvars[prop] + "&"
		}
		source += source.slice(0,(source.length -1));
		//source += "t=" + new Date().getTime();
		
		swfobject.embedSWF(source, "videoPlayerArea", "502", "390", "9.0.0", "/global/flash/expressInstall.swf", flashvars, params);		
		
	});
*/
/* BEGIN : Services Ribbon Carousel */
	$(function() {
		var servicesCarouselData = $("#servicesCarousel ul").clone();
		
		var servicesCarouselOptions = {
			numRows: 2,
			scroll: 1,
			visibleItems: 6,
			speed: "medium"
		};
		
		//check the initial value of the services dropdown
		if ($("#selServiceCategory").val() != "0") {
			$("#servicesCarousel ul").find("li:not(.category_"+$("#selServiceCategory").val()+")").remove();
		}
		
		$("#selServiceCategory").bind("change", function() {
		
			var newList = servicesCarouselData.clone();

			if ($(this).val() != 0) {
				
				//Filter based on category
				newList.find("li:not(.category_"+$(this).val()+")").remove();
				
			}

			//Replace the list
			$("#servicesCarousel").empty().append(newList);
			
			$("#servicesCarousel").carousel(servicesCarouselOptions);
		});
		
		$("#servicesCarousel").carousel(servicesCarouselOptions);
		
	});
/* END : Services Ribbon Carousel */

/* Carousel on Images Tab */
	$(function() {
		$('#imageTabCarousel li').click(function(){
			var thumbNailImage = $(this).children(0).children(0);
			var spanContent = $(this).children(0).children(1);
			var thumbNailSrc = thumbNailImage.attr("src");
			var description = thumbNailImage.attr("title")
			var imageTitle = spanContent.text();
			/*The Herospace image naming convention coming from CMS*/
			var orgImageSrc = thumbNailSrc.replace(/107x78/, "463x407");
			$('#largeImageDescription h4').text(imageTitle);
			$('#largeImageDescription p').text(description);
			$('#largeImageVersion img').fadeOut("fast", function() {
				$('#largeImageVersion img').attr("src", orgImageSrc);
				$('#largeImageVersion img').fadeIn("slow");
			});
			
			return false;
		});
	});
	

/* Services Features Landing Page
----------------------------------------------------*/
	
	$(function() {
	
		function mycarousel_initCallback(carousel) {
			/*
			when user clicks on any anchor tag whose parent is a li with class name "number"
			Call the carousel function
			*/
		    $('#numberedLinks li.number a').bind('click', function() {
		        carousel.scroll($.jcarousel.intval($(this).text()));
		        return false;
		    });
			
			/*Function to handle click of next link Arrow*/
			$('#numberedLinks .pageNext a').bind('click', function() {
				carousel.next();
				return false;
			});
			
			/*Function to handle click of previous link Arrow*/
			$('#numberedLinks .pagePrev a').bind('click', function() {
				carousel.prev();
				return false;
			});
		};
		
		$('#serviceCarousel').jcarousel({
			scroll: 1,
			initCallback: mycarousel_initCallback,
			/*Prevent carousel from creating next and previous buttons by default*/
			buttonNextHTML: null,
			buttonPrevHTML: null
		});
	});
	
	
	$(function() {
		
		//add the serviceFeatureSelector o jQuery's functions
		$.fn.serviceFeatureSelector = function(o) {
			//for each matched element, apply the serviceFeatureSelector constructor
	        return this.each(function() {
	            new $.serviceFeatureSelector(this, o);
	        });
	    };
		
		/**
	     * The serviceFeatureSelector object.
	     *
	     * @constructor
	     * @name $.serviceFeatureSelector
	     * @param Object e The element to create the carousel for.
	     * @param Hash o A set of key/value pairs to set as configuration properties.
	     * @cat Plugins/serviceFeatureSelector
	     */
		$.serviceFeatureSelector = function(e, o){
			//init to default state
			$(e).find(".serviceFlyout").css("display", "none");
			$(e).find(".serviceFlyoutRowTwo").css("display", "none");
			$(e).children("li").css("clear", "none");
			$(e).children("li.colFirst").css("clear", "both");
			$(e).children("li").removeClass("open");
			$(e).children("li").addClass("closed");
			
			//hover to each of the li.closed
			$(e).children("li.serviceButton").hover(
				function(event){
					var element =event.currentTarget;
					if($(element).hasClass("closed")){
						$(element).addClass("hover");
					}
				},
				function(event){
					var element =event.currentTarget;
					if($(element).find("hover")){
						$(element).removeClass("hover");
					}
				}
			)
			
			//bind clck to each of the li
			$(e).children("li.serviceButton").bind("click", function(event){
				var element = event.currentTarget;
				
				var earlyExit = false;
				
				//see if this is the li that is currently "open"
				if( $(this).hasClass("open") || $(this).hasClass("openRowTwo") ){
					earlyExit = true;
				}
				
				//clear open class from all other li's
				$(e).children("li").removeClass("open");
				$(e).children("li").removeClass("openRowTwo");
				$(e).children("li").addClass("closed");
				
				//hide any flyout that may be open, and clear all classes
				$(".serviceFlyoutSpacer").html("");
				$(".serviceFlyoutSpacer").attr("class", "serviceFlyoutSpacer");
				$(".serviceFlyoutSpacer").css("height", "1px");
				
				//exit if we're "closing" this button
				if(earlyExit){	return true; }
				
				$(this).removeClass("closed");
				$(this).removeClass("hover");
				
				//do different things based on whetehr or not it's row 1
				var flyoutSpacer = null
				var flyoutClass = ".serviceFlyout";
				
				if( $(this).prevAll().length < 4 ){	
					$(element).addClass("open");					
					flyoutSpacer = $( $(this).nextAll("li.serviceFlyoutSpacer").get(0) );
				} else {
					$(element).addClass("openRowTwo");
					flyoutSpacer = $( $(this).prevAll("li.serviceFlyoutSpacer")[0] );
					
					flyoutClass = ".serviceFlyoutRowTwo";
				}
							
				//now grab the classes/content
				var flyoutContent = $(this).children(flyoutClass);
				var flyoutClasses = flyoutContent.attr("class").split(" ");

				//insert content/classes and display
				flyoutSpacer.html( flyoutContent.html() );	
				flyoutSpacer.css( "height", "auto" );
					
				for( var i in flyoutClasses ){
					flyoutSpacer.addClass(flyoutClasses[i]);
				}	
				flyoutSpacer.css("display", "block");
			});
		};
		
		$(".serviceClassification").serviceFeatureSelector();
		$(".serviceClassificationContent").equalizeHeights();
	});
	
	
	
/* Services Profile Page
----------------------------------------------------*/
	
	/* Function for carousel displaying 3 mobile phones on each click of arrow  */
	$(function() {
		$('#supportedPhones').carousel({
			scroll: 3,
			visibleItems: 3
		});
	});
	

/* Video Article Page
----------------------------------------------------*/	
/*		
	// Setup Video Player
	//"sa" suffix stands for "stand-alone"
	var params = {};
	params.scale = "showall";
	params.wmode = "transparent";
	params.allowfullscreen = "true"; 	// This tells flash security that full screen flash is allowed on this page
	var flashvars = {};
	flashvars.swf_path = "/global/flash/video_player/main-sa.swf";
	flashvars.video_path = "";
	flashvars.placeholder_path = "/global/flash/video_player/images/placeholder.jpg";
	flashvars.caption_path = "/global/video/common/captions/direction_captions.xml";	// Comment out this line if there is no caption file
	flashvars.allow_fullscreen = "true";	// This determins if the 'full screen' button visibly shows up in the player controls
	
	var source	= "/global/flash/video_player/videoPlayerBuilder-sa.swf?";
	for(prop in flashvars)
	{
		source += prop + "=" + flashvars[prop] + "&"
	}
	source += source.slice(0,(source.length -1));
	
	swfobject.embedSWF(source, "supportVideoArticle", "339", "289", "9.0.0", "/global/flash/expressInstall.swf", flashvars, params);
	
*/
/* Article Page
----------------------------------------------------*/

	/* override tab content styles for iconTabs */
	$(function() {
		$(".iconTabbed").tabbedContent({
			indexClass: "iconTabs"
		});
	});
	
	
	/* Show or hide a comments form if the star rating is 2 or less. */
	$(function() {
		
		$("#frmRateArticle fieldset.userComments").hide(); //Hide the additional comments field by default
	
		$("#frmRateArticle .rating label").bind("click", function() {

			var selectedRadio = $("#"+$(this).attr("for"));

			//Start : Added to Omniture Tracking
			if($("#OmnitureCalls").val() == "false"){
					if(selectedRadio.val() > 2)
					{
							var articleId=$.trim($("#currentArticleId").val());
							var rating=selectedRadio.val();
							var pageId=$.trim($("#pageId").val());

							if( pageId == 'videoArticleDetails')
								{
									Analytics.Support.trackVideoRated(rating);
								}
									else if(pageId == 'textArticleDetails')
								{
									Analytics.Support.trackArticleRated(articleId,rating);
								}
									else if(pageId == 'tutorialArticleDetails')
								{
									Analytics.Support.trackTutorialTopicRated(articleId,rating);
								}	
						}
			}
			//End : Added to Omniture Tracking
			
			// determines if the comment box has already been triggered.
			if(!selectedRadio.closest('form').hasClass('ratingsDone')){
				if (selectedRadio.hasClass(".toggleArticleComments")) {
					$("fieldset.userComments").slideDown("medium");
				}
				else {
					$("#frmRateArticle fieldset.userComments").slideUp("medium");
					
					var target = selectedRadio;
					var formData = target.closest('form').serialize();
					var formServerAddress = target.closest('form').attr('action');
			
					$.ajax({
						type: "POST",
						data: formData,
						url: formServerAddress,
						dataType: "json",
						success: function(msg){
							if(msg.success){
								var ratingInfo = $('#frmRateArticle .ratingInfo');
								ratingInfo.find('.avgRating').text('Average User Rating');
								ratingInfo.find('.currentRatingInfo').remove();
								ratingInfo.find('.avgRating').after('<div class="currentRatingInfo">'+'<div class="bigRating '+ msg.averageRating+'"><em>'+msg.averageRatingValue+'</em></div>'+'<div class="tertiary">('+msg.numberOfRaters+')</div></div>');
							}
						},
		     			error: Sprint.fn.ajaxError
					})
			

				}
			}

			return false;
		});
		
		// 334120 - Handled only for IE6.
		// Setting cursor position in a textarea - http://blog.josh420.com/archives/2007/10/setting-cursor-position-in-a-textbox-or-textarea-with-javascript.aspx
		if ($.browser.msie && parseInt($.browser.version) < 7) {
		
		// Submit event being triggered on Enter. Doing only return false  or event.preventDefault() causes no carriage returns on the textarea.
		//  Bind the Enter Key of the textarea to our custom function.
		$("#textAreaUserComments").bind("keydown",function(event) {
			
			if(event.keyCode==13) {
			var ta = $('#textAreaUserComments');
			//Dom Object for use with IE JScript specific functions.
			var taobj =  $('#textAreaUserComments')[0];
			
			//Figure out the Caret Position as the textarea value length.
			var caretPos = ta.val().length;
			// User Pressed the Enter key add our AI carriage return.
			ta.val(ta.val()+"\n");
			
			// Ensure that the textarea supports the IE specific createTextRange function.
        if(taobj.createTextRange) {
            var range = taobj.createTextRange();
						// Move the cursor position to the end.
            range.move('character', caretPos);
            range.select();
        }
			// Don't submit the form.
			return false;
			}
		})
		}

		
		// Submit Button Handler 
		$("#btnSendComments").unbind("click").bind("click", function(event) {

			event.preventDefault();
			
			// Make sure the user can't submit empty comments
			if ($.trim($("#textAreaUserComments").val()) == "") {
				var targetSubmitButton = $('#articleContainer #btnSendComments');
				if(targetSubmitButton.siblings('.errorHolder').length > 0){
	     			targetSubmitButton.siblings('.errorHolder').remove();
	     		}
				targetSubmitButton.siblings('textarea').before(
     						'<div class="errorHolder"><ul class="formErrors"><li><a href="#lblTxtRecipientEmail">'+"Please enter comments"+'</a></li></ul></div>');
				return false;
			}
			
			// Submit form
			// $("#frmRateArticle")
			// Omniture Added to track the onclick event for submitting comment

			var articleId=$.trim($("#currentArticleId").val());
			var rating=$('.toggleArticleComments:checked').val();
			var pageId=$.trim($("#pageId").val());

			
			if(pageId == 'textArticleDetails')
			{
				if($("#OmnitureCalls").val() == "false"){
					
					//Tracking the rating for article
					Analytics.Support.trackArticleRated(articleId,rating);
				
					//Tracking the comment entered under comment section.
					Analytics.Support.trackArticleComment(articleId);
				}
			}
			else if(pageId == 'videoArticleDetails')
			{
				if($("#OmnitureCalls").val() == "false"){
					
					//Tracking the rating for article
					Analytics.Support.trackVideoRated(rating);
	
					//Tracking the comment entered under comment section.
					Analytics.Support.trackVideoComment();
				}
			
			}
			else if(pageId == 'tutorialArticleDetails')
			{
				if($("#OmnitureCalls").val() == "false"){
					
					//Tracking the rating for Tutorial Topic
					Analytics.Support.trackTutorialTopicRated(articleId,rating)
	
					//Tracking the comment entered under comment section.
					Analytics.Support.trackTutorialTopicComment(articleId);
				}
				
					
			}
			var target = $(this);
			var formData = target.closest('form').serialize();
			var formServerAddress = target.closest('form').attr('action');
			
			$.ajax({
				type: "POST",
				data: formData,
				url: formServerAddress,
				dataType: "json",
				success: function(msg){
     				var targetSubmitButton = $('#articleContainer #btnSendComments');
	     				
     				if(msg.success){
     					
     					if(targetSubmitButton.siblings('.errorHolder').length > 0){
     						targetSubmitButton.siblings('.errorHolder').remove();
     					}
     					
						targetSubmitButton.siblings('textarea').before('<div class="confMessage">'+msg.message+'</div>');
						var ratingInfo = $('#frmRateArticle .ratingInfo');
						ratingInfo.find('.avgRating').text('Average User Rating');
						ratingInfo.find('.currentRatingInfo').remove();
						ratingInfo.find('.avgRating').after('<div class="currentRatingInfo">'+'<div class="bigRating '+ msg.averageRating+'"><em>'+msg.numberOfRaters+'</em></div>'+'<div class="tertiary">('+msg.numberOfRaters+')</div></div>');
								
     				} else {
						if(targetSubmitButton.siblings('.errorHolder').length > 0){
	     						targetSubmitButton.siblings('.errorHolder').remove();
	     				}
     					targetSubmitButton.siblings('textarea').before(
     						'<div class="errorHolder"><ul class="formErrors"><li><a href="#lblTxtRecipientEmail">'+msg.message+'</a></li></ul></div>');
							targetSubmitButton.siblings('textarea').val(msg.commentFiltered);
							return false;
     				}		
     				
     				setTimeout(function(){
     					if(targetSubmitButton.closest('.userComments').css('display') == 'block'){
     						targetSubmitButton.closest('.userComments').slideUp();
     					}
     					setTimeout(function(){
	     					if(targetSubmitButton.siblings('textarea').siblings('.confMessage').length > 0){
	     						targetSubmitButton.siblings('.confMessage').remove();
	     					}
	     					if(targetSubmitButton.siblings('.errorHolder').length > 0){
	     						targetSubmitButton.siblings('.errorHolder').remove();
	     					}
     					}, 1000);
     				}, 3000);		
     			},
     			error: Sprint.fn.ajaxError
			})
						
			return false;
		});
		
		// Cancel Button Handler
		$("#btnCancelComments").bind("click", function(event) {
			event.preventDefault();
			$("#frmRateArticle fieldset.userComments").slideUp("medium");									   
		});
	
	});
	
	/* THIS WAS DROPPED TO TECH JUNE 2, BUT TECH WAS UNABLE TO IMPLEMENT AS-IS. LEAVE IN FOR NOW. */
	/* Star Rating 	 */
	
	/*$(function() {
		// the function below binds a click event to .starRating anchors, clicking on a star will submit it's value to the server
		$("#frmRateArticle .rating a").bind('click', function(){
			// variable below approves the rating data to be submitted to the server, 
			// after the first AJAX submit, this variable should be false via cookie or session ID
			// we would eventually need to build out this user preference persistance function.
			var ajaxSubmit = true;
			
			// hides user's stars and addes a "Saving..." message
			$('.ratingInfo .rating').hide().siblings('h4').append("<span>Saving...</span>");
			
			//checks if the user rating has been counted, if not, then the user who rated a given article will increase by one
			if(!$('.ratingInfo .tertiary').hasClass('ratingUpdated')){
				var oldNumRating = parseInt($('.ratingInfo .tertiary').text().match(/[\d\.]+/g)) + 1;
				$('.ratingInfo .tertiary').text("(" + oldNumRating + " ratings)");
				$('.ratingInfo .tertiary').addClass('ratingUpdated');
			}
			
			var starValue = 'rating=' + $(this).text();
			
			/* if(!$('#frmRateArticle .ratingInfo .rating').hasClass('ratingsDone')){
				$.ajax({
					data: starValue,
					type: "GET",
					url: '/ajax/starRating.php',
					dataType: "json",
					success: function(data) {
						var dataRating = data.rating.toString();
						var newRating = 'bigRating bigRating' + dataRating.replace('.', '') + 'Stars';
						$('.currentRatingInfo .bigRating').removeAttr('class').addClass(newRating).children('em').text(data.rating);
						
						// shows user's stars after a successful AJAX return and removes h4's "Saving..." span
						$('.ratingInfo .rating').show().siblings('h4').children('span').remove();
						
						// adds a class to starRating to turn off the triggering of ajax requests, comment box, updates to star rating
						// each user gets one vote
						// $('#frmRateArticle .ratingInfo .rating').addClass('ratingsDone');
					},
					error: Sprint.fn.ajaxError
				})
			} */
			
		/*})	
		
		// the function below prevents general form submit and the resulting page refresh from occuring
		$('.userComments #btnSendComments_original').bind('click', function(){
			return false;
		});
		
		// the function below binds a click event to the user comment submit and cancel anchor buttons
		$('.userComments a').bind('click', function(e){
			
			// start event delegation
			var tagElement = e.target;
			
			// determine which button was pressed.
			if($(tagElement).closest('a').attr('id') == 'btnCancelComments'){
			
				$("#frmRateArticle #textAreaUserComments").attr('value', '').parent('.userComments').slideUp("medium");
				
			} else if($(tagElement).closest('a').attr('id') == 'btnSendComments'){
			
				if($("#frmRateArticle #textAreaUserComments").attr('value') != ''){
					
					// get the text area value in the user comments fieldset
					var userComment = $("#frmRateArticle #textAreaUserComments").attr('value');
					
					$.ajax({
						data: userComment,
						type: "GET",
						url: '/ajax/userComments.php',
						success: function(data) {
							// hides user comment box
							$('fieldset.userComments').slideUp("medium");
							
							// Backup Plan, just in case we would like to insert a success message
							// $('.userComments input, .userComments a, .userComments textarea').hide();
							// $('.userComments label').after(data);
						},
						error: Sprint.fn.ajaxError
					})
					
				} 
				/*
				else {
				
					alert('Please type out your comment before submitting.');
					
				}
				*/	
			/*}
		});
	});*/

	
	/* Form Validation */
	$(function() {
			
			// Email Article
			$('#btnEmailArticle_original').bind("click", function(event) {
				

			//Start :Added for omniture tracking
			var pageId=$.trim($("#pageId").val());
			var articleId=$.trim($("#currentArticleId").val());
	
				if($("#OmnitureCalls").val() == "false"){
		
						if( pageId == 'videoArticleDetails')
						{
							Analytics.Support.trackVideoEmailSend();
						}
							else if(pageId == 'textArticleDetails')
						{
								Analytics.Support.trackArticleEmailSend(articleId);
						}
						else if(pageId == 'tutorialArticleDetails')
						{
							Analytics.Support.trackTutorialTopicEmailSend(articleId);
						}
				}

				//End :Added for omniture tracking
				var frmEmailArticle = $("#frmEmailArticle");
				
				var emailArticleFormFields = {
					txtYourEmail: {
						name: "txtYourEmail",
						type: "emailAddress",
						required: true,
						invalidErrorMessage: Sprint.content.support.formErrors.emailArticleForm.invalidSenderEmailError[Sprint.currentLanguage],
						emptyErrorMessage: Sprint.content.support.formErrors.emailArticleForm.missingSenderEmailError[Sprint.currentLanguage]
						
					},
					txtRecipientEmail: {
						name: "txtRecipientEmail",
						type: "emailAddress",
						required: true,
						invalidErrorMessage: Sprint.content.support.formErrors.emailArticleForm.invalidRecipientEmailError[Sprint.currentLanguage],
						emptyErrorMessage: Sprint.content.support.formErrors.emailArticleForm.missingRecipientEmailError[Sprint.currentLanguage],
						customValidationRule:function(field){
							// Allow multiple emails to be sent but individually validate them. emails are to be separated by ","
							var emailListArray = new Array(); 
							if(field.val().indexOf(",")>0) {
								emailListArray=	field.val().split(",")
							}
							else{
								// If this is just one email address register this as the 0th element.
								emailListArray[0] =jQuery.trim(field.val());
							}
							// Test each address and store them in a custom error object Array.
							var isaddressValid = new Array();
							if(jQuery.isArray(emailListArray)) {
									jQuery.each(emailListArray,function(i,obj){
										isaddressValid.push(Sprint.formFieldTypes.emailAddress.test(jQuery.trim(obj)));
									})
							}
							
							// Check if any errors are present in our error object Array.
							var chkerrorflds = jQuery.inArray(false,isaddressValid);
							// If an error object is present and there are multiple addresses throw a helpful error.
							if(chkerrorflds>=0&&emailListArray.length>1) {
							this.invalidErrorMessage = Sprint.content.support.formErrors.emailArticleForm.invalidMultipleRecipientEmailError[Sprint.currentLanguage];
							return false;
							}
							// One email address, throw the standard error message.
							else if(chkerrorflds>=0&&emailListArray.length==1) {
								this.invalidErrorMessage = Sprint.content.support.formErrors.emailArticleForm.invalidRecipientEmailError[Sprint.currentLanguage];
								return false;
							}
							else{
							// Email address(es) appear(s) to be valid.
								return true;
							}

						}
					}
				};
				
				var validForm = Sprint.fn.validateForm(frmEmailArticle, emailArticleFormFields);
				
				if (validForm == true){
					//OLD MESSAGE NO LONGER VALID: we don't have to do anything here, just let the POST form submit proceed proceed
					
					//clear old errors
					frmEmailArticle.prev().html("");
					frmEmailArticle.find("input").removeClass("error");
					
					var target = $(this);
					var formData = target.closest('form').serialize();
					var formServerAddress = target.closest('form').attr('action');
			
					$.ajax({
						type: "POST",
						data: formData,
						url: formServerAddress,
						success: function(msg){
							var targetSubmitButton = $('#articleContainer .articleTools #btnEmailArticle_original')
							targetSubmitButton.closest('form').before('<div class="confMessage">'+msg+'</div>');
							
		     				setTimeout(function(){
		     					if(targetSubmitButton.closest('.flyoutInfo').hasClass('visible')){
		     						targetSubmitButton.closest('.flyoutInfo').removeClass('visible').slideUp()
		     							.siblings('a').removeClass('flyoutOpen');
		     					}
		     					if(targetSubmitButton.closest('form').siblings('.confMessage').length > 0){
		     						targetSubmitButton.closest('form').siblings('.confMessage').remove();
		     					}
		     				}, 2000);
		  				},
		  				error: Sprint.fn.ajaxError
					})
					
					return false;
				} else {
					event.preventDefault();
					
					//clear old errors
					frmEmailArticle.prev().html("");
					frmEmailArticle.find("input").removeClass("error");
					
					//Form has errors, show messages.
					frmEmailArticle.showFormErrors({
						errorData: validForm,
						summaryAnchor: frmEmailArticle.prev(),
						scrollToSummary: false,
						showInline: false
					});
				}
			
			});
						
			
	
			// Phone Context Selector
			$("#btnSendPhoneNumModal_original").bind("click", function(event) {
								
				var frmFindSupport = $("#frmSelPhoneNumberModal");
								
				var phoneContextSelectorFields = {
					txtCustPhoneNumDS: {
						name: "txtCustPhoneNumModal",
						type: "phoneNumber",
						required: true,
						invalidErrorMessage: Sprint.content.formFieldErrors.phoneNumberInvalid[Sprint.currentLanguage],
						emptyErrorMessage: Sprint.content.formFieldErrors.phoneNumberEmpty[Sprint.currentLanguage]
					}
				};
				
				var validForm = Sprint.fn.validateForm(frmFindSupport, phoneContextSelectorFields);
				
				if (validForm == true) {
					// If the form is valid we don't have to do anything
				}
				else {
					event.preventDefault();
					
					// Clear old errors
					frmFindSupport.find(".errorHolder").html("");
					frmFindSupport.find("input").removeClass("error");
					
					//Form has errors, show messages.
					frmFindSupport.showFormErrors({
						errorData: validForm,
						summaryAnchor: frmFindSupport.find(".errorHolder"),
						scrollToSummary: false,
						showInline: false
					});
				}
				
			});
			
			/* PTN validation device caurosel support landing page*/
			/* (Added by tech team) */

			$("#btnSendPhoneNumDS_original").bind("click", function(event) {
				var frmFindSupport = $("#frmFindSupport");
						var phoneContextSelectorFields = {
									txtCustPhoneNumDS: {
												name: "txtCustPhoneNumDS",
												type: "phoneNumber",
												required: true,
												invalidErrorMessage: Sprint.content.formFieldErrors.phoneNumberInvalid[Sprint.currentLanguage],
												emptyErrorMessage: Sprint.content.formFieldErrors.phoneNumberEmpty[Sprint.currentLanguage]
									}
						};

						var validForm = Sprint.fn.validateForm(frmFindSupport, phoneContextSelectorFields);

						if (validForm == true) {

									// If the form is valid we don't have to do anything

						}
						else {
									event.preventDefault();
									// Clear old errors

									frmFindSupport.find(".errorHolder").html("");
									frmFindSupport.find("input").removeClass("error");

									//Form has errors, show messages.
									frmFindSupport.showFormErrors({
												errorData: validForm,
												summaryAnchor: frmFindSupport.find(".errorHolder"),
												scrollToSummary: false,
												showInline: false
									});

						}

						

			});
			
			/* PTN validation for Device Section in support landing page */
			/* (Added by tech team) */

			$("#txtSendPhoneNum_original").bind("click", function(event) {
				var frmFindSupport = $("#frmSelPhoneNumber");
						var phoneContextSelectorFields = {
									txtCustPhoneNumDS: {
												name: "txtCustPhoneNum",
												type: "phoneNumber",
												required: true,
												invalidErrorMessage: Sprint.content.formFieldErrors.phoneNumberInvalid[Sprint.currentLanguage],
												emptyErrorMessage: Sprint.content.formFieldErrors.phoneNumberEmpty[Sprint.currentLanguage]
									}
						};

						var validForm = Sprint.fn.validateForm(frmFindSupport, phoneContextSelectorFields);

						if (validForm == true) {

									// If the form is valid we don't have to do anything

						}
						else {
									event.preventDefault();
									// Clear old errors

									frmFindSupport.find(".errorHolder").html("");
									frmFindSupport.find("input").removeClass("error");

									//Form has errors, show messages.
									frmFindSupport.showFormErrors({
												errorData: validForm,
												summaryAnchor: frmFindSupport.find(".errorHolder"),
												scrollToSummary: false,
												showInline: false
									});

						}

						

			});

			// Article Tag validation
			$("#btnTagArticle_original").bind("click", function(event) {

						//Start : Added for Omniture Tracking
						var pageId=$.trim($("#pageId").val());
						var articleId=$.trim($("#currentArticleId").val());
	
						if($("#OmnitureCalls").val() == "false"){
		
							if( pageId == 'videoArticleDetails')
							{
								Analytics.Support.trackVideoTag();
							}
							else if(pageId == 'textArticleDetails')
							{
								Analytics.Support.trackArticleTag(articleId);
							}
							else if(pageId == 'tutorialArticleDetails')
							{
								Analytics.Support.trackTutorialTopicTag(articleId);
							}
						//End : Added for Omniture Tracking
						}
				
				
				var target = $(this);
				var formData = target.closest('form').serialize();
				var formServerAddress = target.closest('form').attr('action');
				
				if(target.siblings('#txtTagArticle').attr('value') == ''){
				var targetSubmitButton = $('#articleContainer .articleTools #btnTagArticle_original');
					if(targetSubmitButton.closest('form').siblings('.errorHolder').length > 0){
						targetSubmitButton.closest('form').siblings('.errorHolder').remove();
					}
					target.closest('form').before(
		     			'<div class="errorHolder"><ul class="formErrors"><li><a href="#lblTagArticle">Error: Please enter any tag.</a></li></ul></div>');
		     			
				} else {
					$.ajax({
						type: "POST",
						data: formData,
						url: formServerAddress,
						dataType: "json",
						success: function(msg){
					
		     				var targetSubmitButton = $('#articleContainer .articleTools #btnTagArticle_original');
		     				
		     				if(msg.success){
		     					if(targetSubmitButton.closest('form').siblings('.errorHolder').length > 0){
		     						targetSubmitButton.closest('form').siblings('.errorHolder').remove();
		     					}
		     					
								targetSubmitButton.closest('form').before('<div class="confMessage">'+msg.message+'</div>');
								var tagsListofArticle = $('#articleContainer .tagCloudContainer')
								tagsListofArticle.hide();
								tagsListofArticle.empty();

								
			     				setTimeout(function(){
			     					if(targetSubmitButton.closest('.flyoutInfo').hasClass('visible')){
			     						targetSubmitButton.closest('.flyoutInfo').removeClass('visible').slideUp()
			     							.siblings('a').removeClass('flyoutOpen');
			     					}
			     					if(targetSubmitButton.closest('form').siblings('.confMessage').length > 0){
			     						targetSubmitButton.closest('form').siblings('.confMessage').remove();
			     					}
									
			     				}, 2000);
								
								setTimeout(function(){
									tagsListofArticle.html('<h5>Tags :</h5> <ul class="tagList">'+msg.tags+'</ul>');
			     					tagsListofArticle.show('slow');
									$('#articleContainer .tagCloudContainer ul.tagList li:last-child').addClass('last');
			     				}, 2000);
								
								
		     				} else {
								targetSubmitButton.closest('form').siblings('.errorHolder').remove();
								/*Above line written to remove the null validation error message*/
		     					targetSubmitButton.closest('form').before(
		     						'<div class="errorHolder"><ul class="formErrors"><li><a href="#lblTagArticle">'+msg.message+'</a></li></ul></div>');
		     						
		     					targetSubmitButton.siblings('#txtTagArticle').attr('value', msg.tagFiltered);
		     					
		     					setTimeout(function(){
								
									/* if(targetSubmitButton.closest('.flyoutInfo').hasClass('visible')){
										targetSubmitButton.closest('.flyoutInfo').removeClass('visible').slideUp()
											.siblings('a').removeClass('flyoutOpen');
									}*/
									
									if(targetSubmitButton.closest('form').siblings('.errorHolder').length > 0){
			     						targetSubmitButton.closest('form').siblings('.errorHolder').slideUp();
			     						setTimeout(function(){
			     							targetSubmitButton.closest('form').siblings('.errorHolder').remove();
			     						}, 1000);
			     					}
	
			     				}, 3000);
			     				
		     				}	  				
		     			},
		     			error: Sprint.fn.ajaxError
					})
				}
				
				return false;
			});
			

			// Article Comment validation
			$("#btnSendComments").bind("click", function(event) {
				var frmFindSupport = $("#frmRateArticle");
								
				var phoneContextSelectorFields = {
					txtCustPhoneNumDS: {
						name: "textAreaUserComments",
						type: "text",
						required: true,
						emptyErrorMessage: Sprint.content.formFieldErrors.commentIsEmpty[Sprint.currentLanguage]
					}
				};
				
				var validForm = Sprint.fn.validateForm(frmFindSupport, phoneContextSelectorFields);
				if (validForm == true) {
					// If the form is valid we don't have to do anything
				}
				else {
					event.preventDefault();
					
					// Clear old errors
					frmFindSupport.find(".errorHolder").html("");
					frmFindSupport.find("input").removeClass("error");
					
					//Form has errors, show messages.
					frmFindSupport.showFormErrors({
						errorData: validForm,
						summaryAnchor: frmFindSupport.find(".errorHolder"),
						scrollToSummary: false,
						showInline: false
					});
				}
				
			});
	});
	

		
		/* Accounts Topics Listing Page
		----------------------------------------------------*/
		
		//bind all elements which have to update the page
		bindUpdateElements();
		
		//
		// THESE ARE ALL HELPER FUNCTIONS...ONLY PUT PAGE PROCESSING ABOVE THIS LINE AN HELPER FUNCTIONS BELOW
		//
		
		function bindUpdateElements(){
			$("input.topicFilter").bind("click", function(e){
				Sprint.pagination.renderResults(Sprint.pagination.getCurrentPage());
			});
			
			$("a.topicFilter").bind("click", function(e){
				$(this).addClass("filterSelected");
				e.preventDefault();
				Sprint.pagination.renderResults(Sprint.pagination.getCurrentPage());
			});
		}
	
		
		//returns the list of filters that are checked on this page in format:
		// 	category_0=<category_id>&category_1=<category_id>&article_type_0=<article_type_id>&article_type_1=<article_type_id>
		function getCurrentFilters(){
			var paramString = "";
			
			$("ul.topicFilterCategory").each( function(i){
				var param_prefix = $(this).attr("id")+"_";
			
				$(this).find("li input:checked").each( function(j){
					paramString += param_prefix+j+"="+$(this).attr("id")+"&";
				});
			});
			
			$("ul.topicLinkCategory").each( function(i){
				var param_prefix = $(this).attr("id")+"_";
				
				$(this).find("li a.filterSelected").each( function(j){
					paramString += param_prefix+j+"="+$(this).attr("id")+"&";
				});
			});
			
			return paramString.substr(0, paramString.length-1);
		}
		
		function getRatingClass( rating ){
			// kindly dont remove single quotes from case bcoz the parameter rating is coming as string
			var newRating = rating*10;
			return("rating"+newRating+"Stars");
			
			/*var ratingClass = "";
			switch(rating){
				case '1': 	return "ratingOneStar"; break;
				case '2': 	return "ratingTwoStars"; break;
				case '3': 	return "ratingThreeStars"; break;
				case '4': 	return "ratingFourStars"; break;
				case '5': 	return "ratingFiveStars"; break;
				default: 	return "";
			}*/
		}
		
		// Pass the search results rendering function to the pagination object
		Sprint.pagination.renderResults = function( pageNum ) {
			
			//get the ajax url from the forms action attribute
			var serviceURL = $("#frmTopicFilters").attr('action');
			
			//break if there is no action attribute
			if (!serviceURL) { return false; }
			
			//append params
			serviceURL += "&page="+pageNum;
			serviceURL += "&"+getCurrentFilters();
			
			//make sure we don't stack up multiple ajax calls, we only need to execute the most recent
			if (Sprint.lastHttpRequest) {
				//aborting only affects unfinished requests
				Sprint.lastHttpRequest.abort();	
			}
			
			//make the ajax call
			Sprint.lastHttpRequest = $.getJSON( serviceURL, {} , function(json) {
				
				//update the pagination
				Sprint.pagination.update(parseInt(json.response.selectedPage), parseInt(json.response.totalResults), parseInt(json.response.resultsPerPage));
				
				//update the articles
				var newArticleList = "";
				
				for (var i in json.response.articles ){
					
					var articleInfo = json.response.articles[i];
					var article = 	"<li>"+
					 			 	"	<div class=\"icon\"><img src=\""+articleInfo.icon+"\" alt=\"article\" /></div>"+
									"	<div class=\"content\">"+
									"		<h3><a href=\""+articleInfo.link+"\">"+articleInfo.title+"</a></h3>"+
                            		"		<p class=\"last\">"+articleInfo.description+"</p>"+
                            		"		<div class=\"tutorialDetails\">"+
                                	"			<span class=\"tertiary\">Created on</span> "+
                                	"			<span class=\"date\">"+articleInfo.date+"</span> "+
                                	"			<span class=\"tertiary\">Average user rating: </span>"+
                                	"			<div class=\"rating "+getRatingClass(articleInfo.rating)+"\"><em>"+articleInfo.rating+" stars</em></div>"+
                            		"		</div>"+
									"	</div>"+
									"	<div class=\"bottom\"> </div>"+
                    				"</li>";

					newArticleList += article;
				}
				
				$("ul.tutorialList").html(newArticleList);
				
			});
		}
	
	/* Device Landing Page
		----------------------------------------------------*/
		// Defect 334229
		$(function() {
				$('.deviceList').each(function() {
					$(this).find('li a').equalizeHeights();
				});
		});
	
		
		// On inital page load, render results for page 1
		Sprint.pagination.renderResults(1);
	});
	
})(jQuery);