oQuestionsModule = {
	sViewAllQuestionsTrigger:'.viewAllQuestions',
	sFilterTextBox:'enter keyword',
	sFilterTextSearchBox:'#filterViewAllQuestions .textBox',
	sFilterListContainer:'#filterListContainer',
	sFilterLoading:'#filterListContainer .loading',
	sCategoryList:'#filterListContainer .categoryList',
	sCategoriesHiddenField:'#filterViewAllQuestions input[name="checkedCategories"]',
	sQuestionsHeader:'#headerQuestions',
	sQuestionsHeaderLink:'#headerQuestions a',
	sQuestionCount:'#headerQuestions span',
	sQuestionLoading:'#viewAllQuestionsTableContainer .loading',
	sQuestionsTable:'#modalViewAllQuestionsTable',
	sQuestionsTableTBody:'#modalViewAllQuestionsTable tbody',
	sQuestionsTableRows:'#modalViewAllQuestionsTable tbody tr',
	sQuestionTitle:null,
	sTruncatedTitle:null,
	nMaxTitleLength:90,
	sQuestionLoadingFadeSpeed:'slow',
	sQuestionFadeSpeed:'slow',
	sFilterLoadingFadeSpeed:'slow',
	sFilterFadeSpeed:'slow',
	jScrollPaneSettings:{showArrows:true, scrollbarWidth: 15, arrowSize: 16},
	
	init:function(viewAllQuestionsTrigger){
		if(viewAllQuestionsTrigger){oQuestionsModule.sViewAllQuestionsTrigger = viewAllQuestionsTrigger;}
		$(oQuestionsModule.sViewAllQuestionsTrigger).click(function() {
		  oQuestionsModule.openViewAllQuestions('/components/smartConversation-view-all-questions.jsp');
		  returnVal = false;
		  return false;
		});
	},
	
	openViewAllQuestions:function(contentURL){
		$.ajax({
			url: contentURL,
			cache: false,
			success: function(html){
				if($("#modalViewAllQuestions")) {
					$("#modalViewAllQuestions").remove();
				}
				$("body").append(html);
				oModalLayer.popup('#modalViewAllQuestions');
				$('#modalViewAllQuestionsTableWrapper').jScrollPane(oQuestionsModule.jScrollPaneSettings);
				$('#feedbackDialog').click(function() {
					oFeedbackModule.openForm($(this).attr('href'), oFeedbackModule.sAskId);
					returnVal = false;
					return returnVal;
				});
				var vaqUri = '/smart_conv/home/view_all_questions';
				var vaqTitle = 'Homepage Action - Smart Conversation - View all questions';
				if ($('.smartConversation')) {
				  vaqUri = '/smart_conv/engage/view_all_questions';
				  vaqTitle = 'Smart Conversation - View all questions';
				}
				dcsMultiTrack('DCS.dcsuri',vaqUri,'WT.ti',vaqTitle,'DCSext.ev_SC_Comment','','DCSext.sc_question','','DCSext.ev_SC_SocialTag','','DCSext.sc_socialSite','','DCSext.ev_SC_Email','','DCSext.sc_description','','DCSext.ev_SC_Feedback','','DCSext.SC_VAQ_Search','','DCSext.SC_VAQ_FilterEnable','');

				oQuestionsModule.loadCategories();
				oQuestionsModule.loadDefaultQuestions();
				oQuestionsModule.prepFilterForm();
			}
		});
		returnVal = false;
		return returnVal;
	},
	
	fetchCategoryJSON:function(){
		$(oQuestionsModule.sCategoryList).remove();
		$.ajax({
			url:'/engage/viewAllCategories.x',
			cache:false,
			dataType:'json',
			success:
				function(data){
				  $.each(data.categories, function(i,c){
					if(c.category[0].name === 'NWPRODUCTS'){
						$('<div class="categoryList"><ul></ul></div>').css({display:'none'}).appendTo(oQuestionsModule.sFilterListContainer);
						var newName;
						var allSelector;
						var allCategoryLabel = "All Products";
						allSelector = c.category[0].name;
						$('<li><input name="' + c.category[0].name + '" type="checkbox" value="" id="filter' + allSelector + '" checked="true" /> <label for="filter' + allSelector +'">' + allCategoryLabel + '</label></input></li>')
						.appendTo(oQuestionsModule.sFilterListContainer + ' .categoryList:last-child ul');
						$.each(c.category[0].subCategories, function(ii,categoryName){
							newName = categoryName.name;
							$('<li><input name="' + c.category[0].name +'" type="checkbox" value="' + newName + '" id="filter' + newName + ii + '" /> <label for="filter' + newName + ii +'">' + newName + '</label></input></li>')
							.appendTo(oQuestionsModule.sFilterListContainer + ' .categoryList:last-child ul');
						});
					}
				  });
					$(oQuestionsModule.sFilterLoading).fadeOut(oQuestionsModule.sFilterLoadingFadeSpeed,function(){
					  $(oQuestionsModule.sCategoryList).fadeIn(oQuestionsModule.sFilterFadeSpeed,function(){
						if($(oQuestionsModule.sCategoryList).css('display') === 'none'){
							$(oQuestionsModule.sCategoryList).css({display:'block'})
						}
					  });
					  $(oQuestionsModule.sFilterListContainer).jScrollPane(oQuestionsModule.jScrollPaneSettings);
					  oQuestionsModule.setCheckboxEvents();
					  oQuestionsModule.setFormSubmitEvent();
					});
				}
		});
	},
	
	setCheckboxEvents:function(){
		oQuestionsModule.reportCheckedCategories();
		$(oQuestionsModule.sCategoryList).each(function(i){
			$(oQuestionsModule.sCategoryList + ':eq(' + i + ') :checkbox:not(:eq(0))').click(function(){
				$(oQuestionsModule.sCategoryList + ':eq(' + i + ') :checkbox:eq(0)').attr('checked','');
				oQuestionsModule.reportCheckedCategories();
			});
			$(oQuestionsModule.sCategoryList + ':eq(' + i + ') :checkbox:eq(0)').click(function(){
				$(oQuestionsModule.sCategoryList + ':eq(' + i + ') :checkbox:not(:eq(0))').attr('checked','');
				oQuestionsModule.reportCheckedCategories();
			});
		});
	},
	
	setFormSubmitEvent:function(){
	  $('#vaqFilterForm').submit(function(){
        var sQuery = $('#vaqQuery').value;
        var filterEnable = 'no';
        if ($(this + 'input:checkbox').attr('value') !== null && $(this + 'input:checkbox').attr('value') !== '') {
          filterEnable = 'yes';
        }
	    dcsMultiTrack('DCS.dcsuri','/smart_conv/view_all_questions/go','WT.ti','Smart Conversation - View All Questions Action - Go','DCSext.SC_VAQ_Search',sQuery,'DCSext.SC_VAQ_FilterEnable',filterEnable);
	    returnVal = true;
	    return returnVal;
	  });
	},

	reportCheckedCategories:function(){
		var selectedCats = new Array();
		$(oQuestionsModule.sCategoryList).each(function() {
			var inputs = $("input[checked]",this);
			if(inputs.length > 0){
				selectedCats[selectedCats.length] = inputs.attr('name');
			}
		});
		$(oQuestionsModule.sCategoriesHiddenField).val(selectedCats.toString());
	},
	
	fetchQuestionJSON:function(){
		$.ajax({
			url:'/engage/viewAllQuestions.x',
			cache:false,
			dataType:'json',
			success:function(data){oQuestionsModule.displayQuestions(data);}
		});
	},
	
	prepFilterForm:function(){
		$('#filterViewAllQuestions .textBox').click(function(){
			if($(this).val() === oQuestionsModule.sFilterTextBox){
				$(this).val('').css({color:"#333"});
			}
		});
		
		$('#resetAll').click(function(){
			$(oQuestionsModule.sFilterTextSearchBox).val('enter keyword');
			$(oQuestionsModule.sFilterTextSearchBox).val('enter keyword').css({color:"#999999"});
			$(oQuestionsModule.sCategoryList + ' :checkbox').attr('checked','');
			$(oQuestionsModule.sCategoryList + ' :checkbox:eq(0)').attr('checked','true');
			oQuestionsModule.reportCheckedCategories();
			oQuestionsModule.loadDefaultQuestions();
			returnVal = false;
			return returnVal;
		});
		
		var ajaxFormOptions = { 
			success: oQuestionsModule.loadQueriedQuestions,
			dataType: 'json'
		};
		$('#filterViewAllQuestions form').ajaxForm(ajaxFormOptions);
	},
	
	truncate:function(s,length,endContent){
		if(typeof length == 'undefined'){var length = 100;}
		if(typeof endContent == 'undefined'){var endContent = '...';}
		s = $.trim(s);
		if(s.length < length){return s;}
		s = $.trim(s.substr(0, length) + endContent);
		return s;
	},
	
	parseSearchResponse:function(data){
		if(data.searchResults[0].result.title === ''){
			oQuestionsModule.displayNoResults(data);
		}else{
			oQuestionsModule.displayQuestions(data);
		}
	},
	
	displayNoResults:function(responseText){
		$(oQuestionsModule.sQuestionsTableRows).remove();
		$(oQuestionsModule.sQuestionsHeaderLink).fadeOut(oQuestionsModule.sQuestionFadeSpeed);
		$(oQuestionsModule.sQuestionCount).html('(-)');
		$("<tr><td>Your search for <strong>&ldquo;" + responseText.searchResults[0].term + "&rdquo;</strong> yielded no results.</td></tr>").appendTo(oQuestionsModule.sQuestionsTableTBody);
		$(oQuestionsModule.sQuestionsHeader).html('<strong style="padding-left:11px">Questions (-)</strong>');
		$(oQuestionsModule.sQuestionLoading).fadeOut(oQuestionsModule.sQuestionLoadingFadeSpeed,function(){
			$(oQuestionsModule.sQuestionsTableTBody).fadeIn(oQuestionsModule.sQuestionFadeSpeed);
		});
	},
	
	displayQuestions:function(responseText){
		$(oQuestionsModule.sQuestionsTableRows).remove();
		$.each(responseText.searchResults, function(i,searchResult){
			oQuestionsModule.sQuestionTitle = searchResult.result.title;
			oQuestionsModule.sTruncatedTitle = oTruncate.sliceText(oQuestionsModule.sQuestionTitle,oQuestionsModule.nMaxTitleLength);
			$('<tr><td><a href="../' + searchResult.result.url + '" title="' + oQuestionsModule.sQuestionTitle + '">' + oQuestionsModule.sTruncatedTitle + '</a></td></tr>').appendTo(oQuestionsModule.sQuestionsTableTBody);
		});
		$(oQuestionsModule.sQuestionsHeader).html('<a href="#" class="ascending">Questions <span>(' + $(oQuestionsModule.sQuestionsTableRows).length + ')</span></a>');
		oQuestionsModule.alternateRows();
		$(oQuestionsModule.sQuestionsTable).trigger('update');
		$(oQuestionsModule.sQuestionLoading).fadeOut(oQuestionsModule.sQuestionLoadingFadeSpeed,function(){
				$(oQuestionsModule.sQuestionsHeaderLink + ' span').show();
				$(oQuestionsModule.sQuestionsTableTBody).fadeIn(oQuestionsModule.sQuestionFadeSpeed, function(){
					$(oQuestionsModule.sQuestionsTable).tablesorter();
					$(oQuestionsModule.sQuestionsHeaderLink).click(function() {
						if($(oQuestionsModule.sQuestionsHeaderLink).hasClass('ascending')){
							var sorting = [[0,1]];
							$(oQuestionsModule.sQuestionsHeaderLink).removeClass('ascending').addClass('descending');
						}else{
							var sorting = [[0,0]];
							$(oQuestionsModule.sQuestionsHeaderLink).removeClass('descending').addClass('ascending');
						}
						
						$(oQuestionsModule.sQuestionsTable).trigger("sorton",[sorting]);
						oQuestionsModule.alternateRows();
						returnVal = false;
						return returnVal;
					});
				});
				$('#modalViewAllQuestionsTableWrapper').jScrollPane(oQuestionsModule.jScrollPaneSettings);
		});
	},
			
	loadCategories:function(){
		$(oQuestionsModule.sCategoryList).fadeOut(oQuestionsModule.sFilterFadeSpeed,function(){
			$(oQuestionsModule.sFilterLoading).fadeIn(oQuestionsModule.sFilterLoadingFadeSpeed,function(){
				oQuestionsModule.fetchCategoryJSON();
			});
		})
	},
			
	loadQueriedQuestions:function(data){
		if($(oQuestionsModule.sCategoriesHiddenField).val() === ''){
			$(oQuestionsModule.sCategoryList + ' :checkbox:eq(0)').attr('checked','true');
		}
		$(oQuestionsModule.sQuestionCount).html('(-)');
		$(oQuestionsModule.sQuestionsTableTBody).fadeOut(oQuestionsModule.sQuestionFadeSpeed,function(){
			$(oQuestionsModule.sQuestionLoading).fadeIn(oQuestionsModule.sQuestionLoadingFadeSpeed,function(){
				oQuestionsModule.parseSearchResponse(data);
			});
		});
	},
	
	loadDefaultQuestions:function(){
		$(oQuestionsModule.sQuestionCount).html('(-)');
		$(oQuestionsModule.sQuestionsTableTBody).fadeOut(oQuestionsModule.sQuestionFadeSpeed,function(){
			$(oQuestionsModule.sQuestionLoading).fadeIn(oQuestionsModule.sQuestionLoadingFadeSpeed,function(){
				oQuestionsModule.fetchQuestionJSON();
			});
		})
	},
			
	alternateRows:function(){
		$(oQuestionsModule.sQuestionsTableRows).removeClass('alt');
		$(oQuestionsModule.sQuestionsTableRows + ':odd').addClass('alt');
	}
}

$(document).ready(function(){
	oQuestionsModule.init();
});