// JavaScript Document
(function($) {

		$(function() {

		/* Accounts Topics Listing Page
		----------------------------------------------------*/

		//bind all elements which have to update the page
		bindUpdateElements();


		// Configure search tooltip
		(function() {
			$("#showSearchTips").tooltip({belowAnchor:true, overrideClass:"searchTooltip"});
			$("#searchTips").hide();
		})();

		// Class to be used for links to store locator in new browser window
		(function() {
			$("a[target='storeLocator']").bind("click", function(event) {

				event.preventDefault();

				var url = $(this).attr("href");
				var storeLocator = window.open(''+ url,'storeLocator','left=20,top=20,width=600,height=500,toolbar=0,resizable=1,location=0');

			});
		})();

		//
		//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());
            // });

			/* pSearch Module - This needs to be here to have access to getRatingClass() */
			$("#pSearchSteps li").not("li:eq(0)").hide();

			$("#frmPSearch").bind("submit", function(event) {
				event.preventDefault();
				$("#btnSubmitPSearchQuestion").trigger("click");
			});

			$("#btnSubmitPSearchQuestion").unbind("click").bind("click", function(event) {
				event.preventDefault();
				pSearchRenderArticles(event);
			});
			/* pSearch Module End */
		}


		//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 ){
			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 result rendering function to the pagination object
		Sprint.pagination.renderResults = function(pageNum) {

			//break if this element doesnt exist
			if( $("#pageUpdateServiceURL").length < 1 ) {
				return false;
			}

			//grab the service URL and append params
			var serviceURL = $("#pageUpdateServiceURL").html();
			// serviceURL += "?page="+pageNum;
			serviceURL += "&"+getCurrentFilters();

			//make the ajax call
			$.getJSON( serviceURL, {} , function(json) {
				//remove old filters
				$("a.filterSelected").removeClass("filterSelected");

				//update the pagination
                // Sprint.pagination.update( parseInt(json.response.selectedPage), parseInt(json.response.totalResults), parseInt(json.response.resultsPerPage) );

				var numArticles = 0;

				//update the articles
				var newGroupList = "";
				for( var i in json.response.groupings ) {

					var groupInfo = json.response.groupings[i];
					var group = "<div class=\"headerWrapperPrimary\">"+
								"	<h3 class=\"corporate\">"+groupInfo.title+"</h3>"+
								"</div>";

					// If we are about to display a list of phones, add a link to the online store
					if (groupInfo.phones) {
						group +=	"<ul id=\"shopFromPhoneList\" class=\"forwardLink\">" +
                        			"	<li class=\"first\"><a href=\"#\">Shop online</a></li>" +
                        			"</ul>";
					}

					group += "<ul class=\"groupListing\">";

					var newArticleList = "";
					var classCounter = 0;

					// Update Phones
					for (var index in groupInfo.phones) {

						var phone = groupInfo.phones[index];

						// Add line row separator
						if (index != 0 && index % 2 == 0) {
							newArticleList += "<li class=\"rowSeparator\"></li>";
						}

						// Add superscript for any decimals in the price
						if (phone.price.indexOf(".") > 0) {
							phone.price = phone.price.replace(".", "<sup>.") + "</sup>";
						}
						// Add superscript around registered symbol
						phone.model = phone.model.replace("&reg;", "<sup>&reg;</sup>");

						var phoneItem = "<li class=\"phoneListing\">" +
										"	<div class=\"phone\">" +
										"		<a hrf=\"" + phone.link + "\"><img src=\"" + phone.image + "\" alt=\"" + phone.model + "\" /></a>" +
										"	</div>" +
										"	<div class=\"phoneInfo\">" +
										"		<h4><sup>$</sup>" + phone.price + "</h4>" +
										"		<h5><a href=\"" + phone.link + "\">" + phone.model + "</a></h5>" +
                                        // "        <div class=\"tutorialDetails\">" +
                                        // "            <span>Overall Rating:&nbsp;</span>" +
                                        // "            <div class=\"rating " + getRatingClass(phone.rating) + "\"><em>" + phone.rating + " stars</em></div>" +
                                        // "        </div>" +
										"		<a href=\"" + phone.link + "\">View Details</a>" +
										"	</div>" +
										"</li>";

						newArticleList += phoneItem;
					}

					// Update Articles
					for( var j in groupInfo.articles ){
						classCounter++;
						var articleClasses = "";
						//this is the case for the row separator
						if( classCounter % 3 == 0 ){
							articleClasses = "rowSeparator";
							var article = 	"<li class='"+articleClasses+"'></li>";
							newArticleList += article;
							classCounter = 0;
							continue;
						//this is the case for non-row-starting articles
						} else if( classCounter % 2 == 0 ) {
							articleClasses = "topicListing";
							numArticles++;
						//ths is the case for row starting articles
						} else {
							articleClasses = "topicListing rowStart";
							numArticles++;
						}

						var articleInfo = groupInfo.articles[j];

						var article = 	"<li class='"+articleClasses+"'>"+
						 			 	"	<div class=\"icon\">"+articleInfo.icon+"</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> "+
                                        // "            <br/><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;

					}

					group += newArticleList;
					group += "</ul>";
					newGroupList += group;
				}
				$("#searchPageArticles").html(newGroupList);

				// We need to make sure any content loaded with Ajax get configured (such as sIFR)
				$("#searchPageArticles").setupComponents()

				// Get all groupings for articles and toggle its items
				$("ul.groupListing li.topicListing").parent().toggleMoreResults();

				// Get all groupings for phones and toggle its items
				$("ul.groupListing li.phoneListing").parent().toggleMoreResults({min:4, max:100, showLinkText:"See more phones", hideLinkText: "See less phones"});

			});

		}

		// On inital page load, render results for page 1
        // Sprint.pagination.renderResults(1);



		/* pSearch functionality */
		function pSearchRenderArticles(event) {

			event.preventDefault();

			var input = $("#txtEmailQuestion");
			var data = input.attr("name"); + "=" + input.attr("value");

			// Get the URL and parameters from the form
			var url = $("#frmPSearch").attr("action");
			url += "?question_box=";
			url += encodeURI(input.attr("value"));
			url += "&btnSearchSupport=Search";

			// Update Steps
			var pSearchSteps =  $("#pSearchSteps");
			var firstListItem = pSearchSteps.find("li:eq(0)");

			firstListItem.addClass("pastStep");
			firstListItem.find(".stepText").html("You entered: " + input.attr("value"));
			if (firstListItem.find(".edit").size() < 1) {
				firstListItem.html("<a href=\"#\" class=\"edit\">Change</a>" + firstListItem.html());
			}

			$("#pSearch #question").html("\"" + input.attr("value") + "\"");
		    $('#pSearch #originalQuestion').val(input.attr("value"));

			// Update Progress
			var progress = $("#pSearch #progress");
			progress.find("li:eq(0)").removeClass("current");
			progress.find("li:eq(1)").addClass("current");

			if (url && data) {
				$.getJSON(url, data, function(json) {

					var newGroupList = "";

					for (var i in json.response.groupings ) {

						// Add Header
						var groupInfo = json.response.groupings[i];
						var group = "<div class=\"headerWrapperPrimary\">" +
                                        // "<h3 class=\"corporate\">" + groupInfo.title + "</h3>" +
										"<h3 class=\"corporate\">One of these may answer your question...</h3>" +
									"</div>\n";

						group += "<ul class=\"groupListing\">\n";

						// Update pSearch Articles
						var foundArticles = false;
						for (var j in groupInfo.articles) {
							foundArticles = true;
							var articleInfo = groupInfo.articles[j];
							var article = 	"<li class=\"topicListing\">" +
												"<div class=\"icon\">"+articleInfo.icon+"</div>" +
												"<div class=\"content\">" +
													"<h3><a target=\"_new\" href=\"/inquiraapp/ui.jsp" + 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>" +
                                                        // " | Average user rating: " +
                                                        // "<div class=\"rating " + getRatingClass(articleInfo.rating) + "\"><em>" + articleInfo.rating + " stars</em></div>" +
													"</div>" +
												"</div>" +
											"</li>\n" +
											"<li class=\"rowSeparator\"></li>\n";
							group += article;
						}

						if(!foundArticles){
							group += "<li class=\"topicListing\">" +
										  "<div class=\"content\">" +
											  "<h3>No articles matched your search</h3>"
										  "</div>" +
									  "</li>\n";
						}

						group += "</ul>\n";
						newGroupList += group;
					}


					$("#pSearchResults").html(newGroupList);
					$("#pSearch #step1").hide();
					$("#pSearch #step2").show();
					$("#pSearchSteps li").show();
					$("#pSearchResults").setupComponents();
					
    			    if (typeof Analytics.Search != 'undefined') {
					    Analytics.Search.screenChangeHelperFunction('preemptiveSearchContinue', json.response.totalArticles, input.attr("value"));
				    }
				});
			}
		}
	});








	/* Search Results Page
	----------------------------------------------------*/

	$(function() {
		// Get all groupings for articles and toggle its items
		$("ul.groupListing li.topicListing").parent().toggleMoreResults();

		// Get all groupings for phones and toggle its items
		$("ul.groupListing li.phoneListing").parent().toggleMoreResults({min:4, max:100, showLinkText:"See more phones", hideLinkText: "See less phones"});

	});



	/* STAR RATING WIDGET JS */
	$(function() {

		 $("#rateSearch fieldset.ratingUserComments").hide(); //Hide the additional comments field by default

		 $("#rateSearch label").bind("click", function() {

			  var selectedRadio = $("#"+$(this).attr("for"));

			  selectedRadio.attr('checked',true);

			  if (selectedRadio.hasClass(".toggleArticleComments")) {
				  $("fieldset.ratingUserComments").slideDown("medium");
			  }


			return false;
		});



		// 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.');

				}

			}
		});

	});



	/* Answer center JS */
	$(function() {
		//the first step is included in the page
		$("#findAnswerStep2").hide();
		$("#startAnswerCenter").bind( "click", function(event){
			event.preventDefault();
			$("#findAnswerStep1").hide();
			$("#findAnswerStep2").show();
		});

		//all subsequent events will be bound due to the live event
		$(".answerCenterTrigger").live( "click", function(event){
			event.preventDefault();
			submitAnswerCenterQuestion(this);
		});
	});


	/* pSearch Functionality
	------------------------------------------------*/
	$(function() {

		var step2 		= $("#pSearch #step2");
		var info  		= $("#pSearch #info");
		var selectTopic = $("#selTopic");

		// All the topics and sub topics (this could be loaded as JSON if we wanted to)
		var topics = [
		    {
				topic: "Billing/Payment",
				cssClass: "",
				subTopics : [
					"Automatic Payments",
					"Billing Inquiry/Invoice Changes",
					"Payment Inquiries",
					"General Inquiry"
				]
			},
			{
				topic: "Equipment",
				cssClass: "",
				subTopics : [
					"Accessories",
					"Add-a-phone",
					"Insurance",
					"Order Tracking",
					"Rebate",
					"Upgrade/New Handset",
					"General Inquiry"
				]
			},
			{
				topic: "Plans, Features and Services",
				cssClass: "",
				subTopics : [
					"Coverage/Roaming",
					"New Plans",
					"Plan Change",
					"Plan Inquiries",
					"PictureMail",
					"Text Messaging",
					"General Inquiry"
				]
			},
			{
				topic: "Tech Support",
				cssClass: "callUs",
				subTopics : []
			},
			{
				topic: "General Inquiry",
				cssClass: "",
				subTopics : [
				    "General Inquiry"
				]
			}
			];

		// Initalize pSearch
		info.hide();
		step2.hide();

		// Populate Topics drop-down
		for (var i in topics) {
			var option = topics[i];
			selectTopic.append("<option class=\"" +  + option.cssClass + "\" value=\"" + option.topic + "\">" + option.topic + "</option>\n");
		}

		// If the user choose to modify a pSearch
		$("#pSearchSteps .edit").live("click", function(event) {
			event.preventDefault();
			step2.hide();
			$("#step1").show();
			$("#pSearchSteps li:eq(0)").removeClass("pastStep").find(".stepText").html("Enter your question like it's an online search");
			$("#pSearchSteps li").not("li:eq(0)").hide();
			$("#pSearchSteps li .edit").remove();
			$("#pSearch #progress li:eq(0)").addClass("current");
			$("#pSearch #progress li:eq(1)").removeClass("current");
		});


        // Cancel Button takes you back to the previous page.
        $('#btnCancel').bind('click',function(){history.back()});
 
		// Show different content if user is an existing customer or not
		$("input[name='radIsExistingCustomer']").click(function() {
			$("#frmPSearchSendEmail :input").removeAttr('disabled');
			$("#frmPSearchSendEmail :select").removeAttr('disabled');
			$("#frmPSearchSendEmail :textarea").removeAttr('disabled');
			if (this.value == "0") {
				$("#existingUserOny :input").attr("disabled", true);
				$("#existingUserOny :select").attr("disabled", true);
				$("#existingUserOny :textarea").attr("disabled", true);
				$("#existingUserOny").hide();
			}
			else {
				$("#existingUserOny").show();
    			$("#existingUserOny :input").removeAttr('disabled');
    			$("#existingUserOny :select").removeAttr('disabled');
    			$("#existingUserOny :textarea").removeAttr('disabled');
			}

            if ($("#selTopic").val() == "Tech Support") {
				$("#selSubTopic").attr("disabled", true);
            }
		});

		// Update sub-topics on topic change
		selectTopic.change(function() {

			var selectSubTopic = $("#selSubTopic");

			selectSubTopic.html('<option value="">- Select one -</option>')

			for (var i in topics) {
				if (this.value == topics[i].topic) {

					// Handle special case if user need to call instead of sending email
					if (topics[i].cssClass == "callUs") {
						selectSubTopic.attr("disabled", true);
						info.show();
						$("#emailDetails").hide();
						$("#btnSendEmail").removeClass("button1_converted").addClass("button0_converted");
						$("#btnSendEmail_original").attr("disabled", true);
					}
					else {
						for (var j in topics[i].subTopics) {
							var option = topics[i].subTopics[j];
							selectSubTopic.append("<option value=\"" + option + "\">" + option + "</option>\n");
						}
						selectSubTopic.attr("disabled", false);
						info.hide();
						$("#emailDetails").show();
						$("#btnSendEmail").removeClass("button0_converted").addClass("button1_converted");
						$("#btnSendEmail_original").attr("disabled", false);
					}
				}
			}
		});
		
      /* pSearch Validation Rules */
      
		var submitForm = false;
		var frmPSearchSendEmail = $('#frmPSearchSendEmail');
		var oldAction = frmPSearchSendEmail.attr("action");
		
		var formFields = {
        
			selTopic: {
				name: "selTopic",
				type: "select",
				required: true,
				emptyErrorMessage: Sprint.content.pSearchEmailErrors.selTopicEmpty[Sprint.currentLanguage],
				invalidErrorMessage: Sprint.content.pSearchEmailErrors.selTopicEmpty[Sprint.currentLanguage]
			},
			radIsExistingCustomer: {
				name:"radIsExistingCustomer",
				type: "radioButton",
				required: true,
				emptyErrorMessage: Sprint.content.pSearchEmailErrors.radIsExistingCustomerEmpty[Sprint.currentLanguage],
				invalidErrorMessage: Sprint.content.pSearchEmailErrors.radIsExistingCustomerEmpty[Sprint.currentLanguage]
			},
			selSubTopic: {
				name: "selSubTopic",
				type: "select",
				required: true,
				emptyErrorMessage: Sprint.content.pSearchEmailErrors.selSubTopicEmpty[Sprint.currentLanguage],
				invalidErrorMessage: Sprint.content.pSearchEmailErrors.selSubTopicEmpty[Sprint.currentLanguage]
			},
			txtEmailDetails: {
				name: "txtEmailDetails",
				type: "text",
				required: true,
				emptyErrorMessage: Sprint.content.pSearchEmailErrors.emailDetailsEmpty[Sprint.currentLanguage],
				invalidErrorMessage: Sprint.content.pSearchEmailErrors.emailDetailsEmpty[Sprint.currentLanguage],
        customValidationRule:function(field) {
        var validtxtEmailDetails = field.val().length>1200?false:true;
        if(validtxtEmailDetails==false)this.invalidErrorMessage = Sprint.content.pSearchEmailErrors.txtEmailDetailsoverflow[Sprint.currentLanguage];
      
          return validtxtEmailDetails;
        }
			},
			txtFirstName: {
				name: "txtFirstName",
				type: "firstName",
				required: true,
				emptyErrorMessage: Sprint.content.pSearchEmailErrors.firstNameEmpty[Sprint.currentLanguage],
				invalidErrorMessage: Sprint.content.pSearchEmailErrors.firstNameInvalid[Sprint.currentLanguage]
			},
			txtLastName: {
				name: "txtLastName",
				type: "lastName",
				required: true,
				emptyErrorMessage: Sprint.content.pSearchEmailErrors.lastNameEmpty[Sprint.currentLanguage],
				invalidErrorMessage: Sprint.content.pSearchEmailErrors.lastNameInvalid[Sprint.currentLanguage]
			},
			txtEmailAddress: {
				name: "txtEmailAddress",
				type: "emailAddress",
				required: true,
				emptyErrorMessage: Sprint.content.pSearchEmailErrors.emailAddressEmpty[Sprint.currentLanguage],
				invalidErrorMessage: Sprint.content.pSearchEmailErrors.emailAddressInvalid[Sprint.currentLanguage]
			},
            txtWirelessNumber: {
             name: "txtWirelessNumber",
             type: "phoneNumber",
             required: true,
             emptyErrorMessage: Sprint.content.pSearchEmailErrors.phoneNumberEmpty[Sprint.currentLanguage],
             invalidErrorMessage: Sprint.content.pSearchEmailErrors.phoneNumberInvalid[Sprint.currentLanguage]
            },
            txtAccountVerification: {
             name: "txtAccountVerification",
             type: "PIN",
             required: false,
             emptyErrorMessage: Sprint.content.pSearchEmailErrors.pinEmpty[Sprint.currentLanguage],
             invalidErrorMessage: Sprint.content.pSearchEmailErrors.pinInvalid[Sprint.currentLanguage]
            },
            txtStreet: {
             name: "txtStreet",
             type: "streetAddress",
             required: true,
             emptyErrorMessage: Sprint.content.pSearchEmailErrors.streetAddressEmpty[Sprint.currentLanguage],
             invalidErrorMessage: Sprint.content.pSearchEmailErrors.streetAddressInvalid[Sprint.currentLanguage]
            },
             txtCity: {
             name: "txtCity",
             type: "city",
             required: true,
             emptyErrorMessage: Sprint.content.pSearchEmailErrors.cityEmpty[Sprint.currentLanguage],
             invalidErrorMessage: Sprint.content.pSearchEmailErrors.cityInvalid[Sprint.currentLanguage]
            },
            selState: {
             name: "selState",
             type: "select",
             required: true,
             emptyErrorMessage: Sprint.content.pSearchEmailErrors.stateEmpty[Sprint.currentLanguage],
             invalidErrorMessage: Sprint.content.pSearchEmailErrors.stateInvalid[Sprint.currentLanguage]
            },
			txtZip: {
				name: "txtZip",
				type: "zipCode",
				required: true,
				emptyErrorMessage: Sprint.content.pSearchEmailErrors.zipCodeEmpty[Sprint.currentLanguage],
				invalidErrorMessage: Sprint.content.pSearchEmailErrors.zipCodeInvalid[Sprint.currentLanguage]
			}
		};
		
		
		frmPSearchSendEmail.bind("submit",function(e){
			e.preventDefault();
			performSearchEmailValidation(e);
		});

		frmPSearchSendEmail.find("#btnSendEmail").unbind("click").bind("click", function(event) {		
			event.preventDefault();
			performSearchEmailValidation(event);	
		});
		
		
		function performSearchEmailValidation(event){

	        	var validField =  Sprint.fn.validateForm(frmPSearchSendEmail, formFields);


				// Shouldn't be able to submit when it is disabled
				if ($('#btnSendEmail_original').attr("disabled")) {
					return false;
				}

				//Clear any errors that might already be showing
				frmPSearchSendEmail.find("label.error").remove();
				frmPSearchSendEmail.find(".error").removeClass("error");



				if (!validField) {
					event.preventDefault();
				    if (typeof Analytics.Search != 'undefined') {
	    			    Analytics.Search.trackError('user', 'Unable to submit email us form');
				    }
					return false;
				}

				if (typeof(validField) != "boolean") {
					//There's an error with this field, show inline-only error messaging.
					event.preventDefault();

					frmPSearchSendEmail.showFormErrors({					
						errorData: validField,
						showSummary: false
					});

				    if (typeof Analytics.Search != 'undefined') {
	                    var errorMessages = '';
	    				for (field in validField) {
	                        errorMessages += validField[field].errorMessage + '|';
	                    }
	    			    Analytics.Search.trackError('user', errorMessages.slice(0, -1));
				    }
				}

				if(typeof(validField)=="boolean") {

				    if (typeof Analytics.Search != 'undefined') {
	    			    Analytics.Search.trackPreemptiveSearchEmailSend();
				    }

					//Trigger the click event of the original submit button to submit the form.
					frmPSearchSendEmail.find("#btnSendEmail_original").trigger("click");
				}


	    }
	

      /* pSearch Validation Rules
    
 /* -------------------------*/   
    
	});



	//Extend jQuery's function set with Sprint specific functions
	$.fn.extend({

		/*
		* show hide more seach results
		*
		* function to toggle the number of results viewable
		* min results: 5
		* max results: 14
		* expects an unordered list
		*
		*
		* @param scriptOptions: Object, defines options that will override the defaults
		*
		*/
		toggleMoreResults: function(scriptOptions){

			//TODO: need to implement options
			var defaults = {
				min: 6,
				max: 25,
				showLinkText: "See more of this grouping",
				showLinkClass: "expandoLinkShow",
				hideLinkText: "See less of this grouping",
				hideLinkClass: "expandoLinkHide",
				moreResultsWrapperClass: "moreResultsWrapper"
			};

			var options = $.extend(defaults, scriptOptions);

			return this.each(function(i) {
				$this = $(this);

				//calculate min and max;
				var minUl = Math.ceil(options.min/2);
				var maxUl = Math.ceil(options.max/2);

				if ($this.children("li.topicListing").length > options.min || $this.children("li.phoneListing").length > options.min){
					//remove all results above the max
					var numLisToRemove = Math.ceil(options.max*1.5) - 1;
					$this.children("li:gt("+(numLisToRemove)+")").remove();

					//hide any results over the min
					var numLisToShow = Math.ceil(options.min*1.5) - 1;
					var wrapper = $this.children("li:gt("+(numLisToShow)+")").wrapAll('<li id="moreResultsWrapper'+i+'" class="'+options.moreResultsWrapperClass+'"></li>').wrapAll("<ul style=\"width: 100%\"></ul>");

					var $moreResultsWrapper = $("#moreResultsWrapper"+i);

					var expandoButton = $('<ul id="expandoLink'+i+'" class="'+options.showLinkClass+'"><li><a href="#">'+options.showLinkText+'</a></li></ul>');
					$this.append(expandoButton); //append to DOM

					var $expandoButton = $("#expandoLink"+i);
					$expandoButton.insertAfter($this); //bump button outside UL

					$moreResultsWrapper.hide();

					$expandoButton.toggle(
						function(e){
							var $this = $(this);
							e.preventDefault();
							$this.find("a").text(options.hideLinkText);
							$this.toggleClass(options.hideLinkClass);
							$this.toggleClass(options.showLinkClass);
							$moreResultsWrapper.slideToggle();
							return false;
						},function(e){
							var $this = $(this);
							e.preventDefault();
							$(this).find("a").text(options.showLinkText);
							$this.toggleClass(options.hideLinkClass);
							$this.toggleClass(options.showLinkClass);
							$moreResultsWrapper.slideToggle();
							return false;
						}
					);
				}
			});
		}
	});


	/* Find a Store Form Inline
	-------------------------------------------------*/
	(function() {
		$(document).ready( function(){
			if( $("#inlineContactUsModule").length > 0 ){
				setUpInlineContactModule();
			}

			if( $("#phoneCarousel").length > 0 ){
				setUpPhoneSelector();
			}
		});

	})();


	//this is a "global" function
	function submitAnswerCenterQuestion(element){
		//get the req'd info for the ajax call
		var theForm = $(element).parents(".answerCenterForm");
		var serviceMethod = theForm.attr("method");
		var serviceURL = theForm.attr("action");
		var questionID = theForm.attr("id");
		var questionAnswer = $(element).attr("value");

		//there are certain special cases for getting the answer
		if( $(element).attr("id")=="btnSendPhoneNum" ){
			questionAnswer = $("#txtCustPhoneNum").val();
		} else if( $(element).is("a") ){
			questionAnswer = $(element).attr("rel");
		}

		var reqData = {
			"question" : questionID,
			"answer" : questionAnswer
		}

		$.ajax({
			type: serviceMethod,
			url: serviceURL,
			data: reqData,
			dataType : "html",
			success : function(data){
				$("#AnswerCenter").html(data);
				if( $("#inlineContactUsModule").length > 0 ){
					setUpInlineContactModule();
				}

				if( $("#phoneCarousel").length > 0 ){
					setUpPhoneSelector();
					//also do the pngFix if the browser is ie6
					if ($.browser.msie && parseInt($.browser.version) < 7) {
						$(".pngFix").pngFix();
					}
				}
			}
		});
	}


	//this is a "global" function
	function setUpPhoneSelector(){
		$("#phoneCarousel").carousel({
			scroll : 3,
			visibleItems : 3
		});

		var carouselSelector = "#phoneCarousel";
		var selectorElement = $("#selManufacturer")

		//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();
		}

		var originalCarouselData = $(carouselSelector+" ul").clone();

		selectorElement.bind("change", function() {

			if ($(this).val() != -1) {
				var newList = originalCarouselData.clone();

				if ($(this).val() != 0) {
					//Filter based on manufacturer
					newList.find("li:not(.manufacturer_"+$(this).val()+")").remove();
				}

				//Replace the list
				$(carouselSelector+" ul").parent().empty().append(newList);

				if ($.browser.msie && parseInt($.browser.version) < 7) {
					$(".pngFix").pngFix();
				}
			}
		});

		//rebind the button to something more useful for us
		$("#btnSendPhoneNum").unbind("click").bind( "click", function(event){
			event.preventDefault();
			submitAnswerCenterQuestion(this);
		});

	}


	//this is a "global" function
	function setUpInlineContactModule(){
		var frmFindStore = $("#frmFindStoreInline");

		if (frmFindStore.length > 0) {

			var locationDisplay = $("#locationDisplayInline");

			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("#btnFindStoreInline").removeClass("disabled");

					frmFindStore.find("#txtFindStoreAddressInline").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("#btnFindStoreInline").trigger("click");

			});

			function findInlineStores(event, supressErrors){
				if(event){	event.preventDefault();	}

				if( supressErrors==null ){ supressErrors=false;}

				if ($(this).is(".disabled")) {
					return false;
				}

				var searchString = $.trim(frmFindStore.find("#txtFindStoreAddressInline").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("#hidFindStoreRadiusInline").val()
					},

					type: "GET",

					dataType: "json",

					success: function(data) {

						//Remove any previous results
						locationDisplay.find(".storeLocation").remove();

						if (data.error) {
							locationDisplay.prepend("<div class=\"storeLocation\"><h5>"+data.error+"</h5></div>");
						}
						else if (data.stores) {

							var outputString = "";

							//No errors, output the first 2 results
							$.each(data.stores, function(i) {

								if (i >= 2) {
									return;
								}

								outputString = outputString+"<div class=\"storeLocation\"><h5>"+data.stores[i].name+"</h5><div class=\"locationTelephone\"><em>"+data.stores[i].phone+"</em></div><div class=\"locationAddress01\">"+data.stores[i].address+"</div></div>";

							});

							locationDisplay.prepend(outputString);

						}

						frmFindStore.parent().hide();

						locationDisplay.show();

					},

					//error: errorFunction
					error: function(i){
						alert("error!");
					}
				});

			}//end of findInlineStores

			frmFindStore.find("#btnFindStoreInline").unbind("click").bind("click", function(event) {
				findInlineStores(event);
			});

			//initialize the store locator, but supress error messages
			findInlineStores(null, true);
		}
	}//end of setUpInlineContactModule

})(jQuery);