/*
 *
 * AOL HELP JS Utilities
 *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
// Custom $ namespace to prevent conflicts with other JS libs
jQuery.noConflict(); 

var default_search = "Enter your question or keywords",
	default_result_count = 10,
	sec_search_form,
	linksForm;

/*function convertEntities(myString)
{
	myString = myString.replace( /\&amp;/g, '&' );
	myString = myString.replace( /\&lt;/g, '<' );
	myString = myString.replace( /\&quot;/g, '"' );
	myString = myString.replace( /\&copy;/g, '©' );
	myString = myString.replace( /\&reg;/g, '®' );
	myString = myString.replace( /\&laquo;/g, '«' );
	myString = myString.replace( /\&raqou;/g, '»' );
	myString = myString.replace( /\&apos;/g, "'" );
	myString = myString.replace( /\&rsquo;/g, "'" );
	myString = myString.replace( /\&lsquo;/g, "'" );
	myString = myString.replace( /\&rdquo;/g, "\"" );
	myString = myString.replace( /\&ldquo;/g, "\"" );
	return myString;
}*/
	
//Create private scope to allow usage of jQuery $ notation without fear of conflicts
(function($){

$(document).ready( function() {
	
	sec_search_form = jQuery('form[name=secSearchForm]');
	linksForm = jQuery('form[name=linksForm]');
	

	// Focus/Blur toggle on all text inputs
	$("input[type=text]").inputFocusToggle(default_search);
	$("textarea").inputFocusToggle();
	
	// Create slider actions
	

	// Adding hover animation to team members
	$("#team li").hoverAnimateBackground( {in_color:"#f0f0f0", in_time:250, out_time:500} ); 
	
	// Initiate modal dialog for team bios
	$(".team_list li > a").initModal(); 

	// Initiate header popups: Login and Feedback
	//$("#login_popup").initLoginPopup(); // handled by hat include
	//$("#feedback_popup").initFeedbackPopup();
	
	// Initiate Hide/Show Answer Comment Field
	$(".comments_wrap .comments .add_comment_toggle").click(function() {
		$(this).parents(".comments").find(".add_comment_wrap").slideToggle();
		
		return false; // prevent default action
	
	});

	$("input[name=searchString]").each(function(){
		buildSearchCheck(this);
	});

	$("input[name=q]").each(function(){
		buildSearchCheck(this);
	});
	
	//$("meta[name=description]").attr("content", convertEntities($("meta[name=description]").attr("content")));
	//$("meta[name=keywords]").attr("content", convertEntities($("meta[name=keywords]").attr("content")));

	var radiosExist = sec_search_form.find('#search_radios').length > 0;
	var onHomepage = sec_search_form.find('input[name=homepage]').length > 0;
	var fromHomepage = linksForm.find('TextArea[name=homepage]').length > 0;
	var onAZ = sec_search_form.find('input[name=a-z]').length > 0;
	var fromAZ = linksForm.find('TextArea[name=a-z]').length > 0;
	var onSettings = sec_search_form.find('input[name=settings]').length > 0;
	var fromSettings = linksForm.find('TextArea[name=settings]').length > 0;
	var onAcctSettings = sec_search_form.find('input[name=acctsettings]').length > 0;
	var fromAcctSettings = linksForm.find('TextArea[name=acctsettings]').length > 0;
	var onArticleIndexPage = sec_search_form.find('input[name=article]').length > 0;
	var fromArticleIndexPage = linksForm.find('TextArea[name=article]').length > 0;
	var radioParam = (($(document).getUrlParam("radios")||"true")=="true");
	var noRadios = onHomepage || onAZ || onAcctSettings || onArticleIndexPage || fromHomepage || fromAZ || fromAcctSettings || fromArticleIndexPage || onSettings || fromSettings || !radioParam;

	if ($('fieldset[id=help_search]').length > 0)
	{
		if (fromHomepage || !radioParam)
			$('fieldset[id=help_search]').append('<input type="hidden" name="homepage"/>');
		else if (fromAZ)
			$('fieldset[id=help_search]').append('<input type="hidden" name="a-z"/>');
		else if (fromSettings)
			$('fieldset[id=help_search]').append('<input type="hidden" name="settings"/>');
		else if (fromAcctSettings)
			$('fieldset[id=help_search]').append('<input type="hidden" name="acctsettings"/>');
		else if (fromArticleIndexPage)
			$('fieldset[id=help_search]').append('<input type="hidden" name="article"/>');
	}
	
	var productTA = linksForm.find('TextArea[name=product]');
	var kanissa_idTA = linksForm.find('TextArea[name=kanissa_id]');
	var product_nameTA = linksForm.find('TextArea[name=product_name]');
	if (productTA.length > 0 && kanissa_idTA.length > 0 && product_nameTA.length > 0)
	{
		$.cookie("product",productTA.val(),{ path: '/help' });
		$.cookie("kanissa_id",kanissa_idTA.val(),{ path: '/help' });
		$.cookie("product_name",product_nameTA.val(),{ path: '/help' });
	}
	
	if($.cookie("product") && $.cookie("product_name") && $.cookie("kanissa_id") && !radiosExist && $('fieldset[id=help_search]').length > 0 && !noRadios)
	{
		if ($.cookie("product") != "all")
			buildRadioButtons();
	}	

	//little bit of a hack-y fix for axiom published content
	//&nbsp; gets turned into &amp;nbsp; so, fix it with a reg-ex
	if ($(".product_decisions li.spacer").length > 0)
		$(".product_decisions li.spacer").html($(".product_decisions li.spacer").html().replace(/&amp;nbsp;/g,"&nbsp;"));
	
	$(".az_body a").each(function() 
		{ 
			var link = $(this).attr("href");
			if (/searchEntry\.do/.test(link))
				$(this).attr("href", link + "&radios=false");
		}
	);
	
	if (navigator.userAgent.indexOf("Chrome/4.0") != -1)
	{
		$(".btn span").css("position", "relative");
		$(".btn span").css({top:"-1px",left:"1px"});
	}
	
	resizeStretchIE6();
	
	//buildAOLDefaults();  //handled by hat include
	
	$("#settings_tabs").tabs();
	$("#settings_tabs").tabs({
	   select: function() { runOmni(); }
	});
		
}); // end document.ready

$(window).load(function(){
	if($(".tab_body.community_support").length > 0)
		buildAnswersResults();

	if($(".search_tabs .tab_body.articles").length > 0)		
		loadOmniunih();
		
		
	$("#slider").horizontalSlider();		
});

$(window).resize(function() {
	resizeStretchIE6();
});


/* 
 * Specfic plugins for AOL Help:
 *  
 */
 

 
/**  
 * Initiate Login Popup
 * - Attaches fadein/fadeout actions
 * - Adds validation to input elements 
 */
$.fn.initLoginPopup =
	function() {
	
		var popup = $(this);
	
		// Fade popup in 
		$("#header a.login").click( function () {
			$("#feedback_popup").fadeOut(); // Hide feedback popup if it is showing
			popup.fadeIn();
			return false; // prevent default action
		});
		
		// Fade popup out	
		popup.find("a.close").click( function() {
			popup.fadeOut();
			return false; // prevent default action	
		});
		
		popup.find("#submit").click( function(){
			popup.find("#errors").fadeOut();
			popup.find("input").each( function() {
				if ($(this).val() == ""){
					popup.find(".errors").fadeIn();
					return false;
				}
			});
		
		
		});
	
	}

/**  
 * Initiate Feedback Popup
 * - Attaches fadein/fadeout actions
 * - 
 */
$.fn.initFeedbackPopup =
	function() {
	
		var popup = $(this);
				
		// Fade popup in 
		$("#header a.feedback").click( function () {
			$("#login_popup").fadeOut();  // Hide login popup if it is showing
			popup.fadeIn();
			return false; // prevent default action
		});
		
		// Fade popup out	
		popup.find("#cancel_feedback").click( function() {
			popup.fadeOut();
			return false; // prevent default action	
		});
	
	}

function buildRadioButtons() {

	var searchOption = $.cookie("product");
	var allChecked = searchOption == "all";
	var product_name = $.cookie("product_name");
	product_name = product_name.replace(/%20/g, " ");
	var kanissa_id = $.cookie("kanissa_id");
	var help_search = $('fieldset[id=help_search]');
	
	help_search.prepend('<ul class="radios" id="search_radios">\n' +
		'<li><input' + (!allChecked ? ' checked="checked"' : '') + ' id="' + kanissa_id + '"' +
		' name="product" type="radio" value="' + kanissa_id + '" />\n' +
		'<label for="' + kanissa_id + '">Search only within ' + product_name + '</label>\n' +
		'</li><li><input id="search_all" name="product" type="radio" value="all"/>\n' +
		'<label for="search_all">Search all of AOL Help</label></li></ul>\n' +
		'<input type="hidden" name="product_name" value="' + product_name + '"/>\n' +
		'<input type="hidden" name="kanissa_id" value="' + kanissa_id + '" />\n');
		
		help_search.find('input[id='+kanissa_id+']').attr('checked', 'Checked');

}
	
function buildAnswersResults() {
	var indexString = '',
		pageNum = getPageNumber(),
		searchString = '',
		startIndex = (pageNum > 1)? (pageNum - 1) * default_result_count : 0,
		totalPages = getTotalPages();

	if (document.secSearchForm) {
		searchString = document.secSearchForm.searchString.value;
	}

	if (totalPages)
		indexString += "&start=" + startIndex + "&numItems=" + default_result_count;

	$.ajax({
		type:		"GET",
		url: 		"/help/microsites/getRSS.jsp",
		data:		"searchString=" + escape(getSearchString()) + indexString,
		dataType:	"xml",
		success:	parseYeddaFeed,
		timeout:	20000,
		error:	setNoCSResults
	});
}

function buildAOLDefaults(){
	//Create pop functionality for more link in the hat
	$('#hat .sub_links .more > a').mouseenter(function (){
		var elem = $(this).parent(),
			elem_pop = elem.find('#more_links');

		elem.toggleClass("act");
		elem_pop.slideToggle();
		

		$(elem_pop).one('mouseleave', function(){
			elem.toggleClass("act");
			elem_pop.slideToggle();	
		});

		return false;
	});
}

//function to build pagination for the yedda feed
//could be modified to become more generic and universal
function buildFeedPagination( pg_num, total_pgs){

	if (total_pgs == 1)
		return '';

	var output = '<div class="results_pagination"><ul>',
		curr_pg = 1,
		pgs_shown = 5,
		start_pg = 1,
		end_pg = total_pgs,
		offset = 2
		searchString = escape(getSearchString())
		searchTitle = escape(getSearchTitle())
		tabName = getTabName();
	
	if (total_pgs > pgs_shown){
		//check if current page is close to start pagination
		if ((start_pg + (pgs_shown - offset)) >= pg_num)
			end_pg = (start_pg + (pgs_shown - 1));
		else if ((end_pg - (pgs_shown - offset)) <= pg_num)
			start_pg = (end_pg - (pgs_shown - 1));
		else
			start_pg = pg_num - 2;
	}

	if ((parseInt(pg_num) - 1) >= start_pg)
	{
		output += '<li class="first"><a href="' + location.pathname + '?searchString=' + searchString + 
			'&pNum=' + (parseInt(pg_num) - 1)  + '&tab=' + tabName + '&tPages=' + total_pgs + '&searchTitle=' + searchTitle +'"><span>Prev</span></a>';
	}

	for (curr_pg = start_pg; curr_pg <= end_pg && end_pg != 1; curr_pg++){

		output += '<li';

		output += (curr_pg > start_pg || (pg_num > start_pg))? '>' : ' class="first">';

		if (pg_num == curr_pg)
			output += '<span>' + curr_pg + '</span>';
		else
			output += '<a href="' + location.pathname + '?searchString=' + searchString + 
				'&pNum=' + curr_pg + '&tab=' + tabName + '&tPages=' + total_pgs + '&searchTitle=' + searchTitle + '"><span>' + curr_pg + '</span></a>';

		output += '</li>';
	}

	if (pg_num + 1 <= total_pgs && total_pgs >= 5)
	{
		output += '<li><a href="' + location.pathname + '?searchString=' + searchString + 
			'&pNum=' + (parseInt(pg_num) + 1)  + '&tab=' + tabName + '&tPages=' + total_pgs + '&searchTitle=' + searchTitle + '"><span>Next</span></a>';
	}

	return output += '</ul></div>';
}

function getPageNumber(){
	return $(document).getUrlParam("pNum") || 1;
}

function getTabName(){
	return $(document).getUrlParam("tab") || 'a';
}

function getTotalPages(){
	return $(document).getUrlParam("tPages");
}

function getSearchString(){
	var searchTerm;
	
	if($(document).getUrlParam("tab") == "cs" && !($(document).getUrlParam("searchString").length > 0))
		return "noresultscs";
		//BLT 564516
		
	if($(document).getUrlParam("searchString").length > 0) 
		searchTerm = $(document).getUrlParam("searchString");
	else if((typeof searchString != "undefined") && (searchString.length>0))
			searchTerm = searchString;
	else if($(".search_term").html().length > 0)
		searchTerm = $(".search_term");
	else if (document.secSearchForm.searchString.value != defaultTerm)
		searchTerm = document.secSearchForm.searchString.value;
		
	return unescape(searchTerm);
}

function getSearchTitle(){
	var searchTitle="";
	
		
	if($(document).getUrlParam("searchTitle").length > 0) 
		searchTitle = $(document).getUrlParam("searchTitle");
	else
		searchTitle = "";
		
	return unescape(searchTitle);
}


function getTimePosted(strDate) {
	var strRet='';
	var sDate=new Date(strDate);
	var eDate=new Date();
	var timeApart = Math.abs((sDate-eDate)/31536000000); //years apart
	var timeApartRounded = Math.round(timeApart);

	if (timeApart >= 1) {
		var s = (timeApart > 1) ? "s " : " ";
		strRet=timeApartRounded + " year" + s + "ago";
	} else {
		var timeApart = Math.abs((sDate-eDate)/2592000000); //months apart
		var timeApartRounded = Math.round(timeApart);
		if (timeApart >= 1) {
			var s = (timeApart > 1) ? "s " : " ";
			strRet=timeApartRounded + " month" + s + "ago";
		} else {
			var timeApart = Math.abs(Math.round((sDate-eDate)/86400000)); //days apart
			if (timeApart > 0) {
				var s = (timeApart > 1) ? "s " : " ";
				strRet=timeApart + " day" + s + "ago";
			} else {
				timeApart = Math.abs(Math.round((sDate-eDate)/3600000)); //hours apart 
				if (timeApart > 0) {
					var s = (timeApart > 1) ? "s " : " ";
					strRet=timeApart + " hour" + s + "ago";
				} else {
					timeApart = Math.abs(Math.round((sDate-eDate)/60000)); //min apart 
					if (timeApart > 0) {
						var s = (timeApart > 1) ? "s " : " ";
						strRet=timeApart + " minute" + s + "ago";
					} else {
						timeApart = Math.abs(Math.round((sDate-eDate)/1000)); //sec apart 
						var s = (timeApart > 1) ? "s " : " ";
						strRet=timeApart + " second" + s + "ago";
					}
				}
			}
		}
	}
  //return
  return strRet;
}

function parseYeddaFeed(feed) {
	var items = $(feed).find('item'),
		//gets the page number if available or sets it to 1
		page_num = getPageNumber(),
		//sets number of items on page
		items_on_page = default_result_count,
		//sets the start item based on the page number
		//start_item = (page_num > 1)? (page_num - 1)*items_on_page : 0,
		// Start item should always be 0 because getRSS.jsp is starting at the correct index
		start_item = 0;
		//sets the end item based on the page number
		//end_item = start_item + items_on_page || items.length,
		// Start Item should always be 10 because we want 10 results per page, and startItem is always 0
		end_item = 10;
		//sets the total number of pages
		total_pages = getTotalPages() || Math.ceil(items.length / items_on_page);

		
	//try {
		if (items.length > 0){
			var output = '<ul class="results_list">',
				first = 'class="first"',
				item_first_check = true;

			if (items.length > default_result_count)
				items = items.slice(start_item, end_item);

			items.each(function(){
				var feed_item = $(this);
				output += '<li';
				output += (items[0] !== this)? '>' : ' ' + first + '>';

				var author = feed_item.find('[nodeName="foaf:maker"]').find('[nodeName="foaf:Person"]');

				if(author.find('[nodeName="foaf:homepage"]') && 
					author.find('[nodeName="foaf:img"]'))
				{
					//output image container
					output += '<a class="img_link" href="' + author.find('[nodeName="foaf:homepage"]').attr('rdf:resource') + 
						'"><span><img alt="Username" src="' + author.find('[nodeName="foaf:img"]').attr('rdf:resource') + '"/></span></a>';
				}	

				output += '<div class="question"><h5>Asked: <a href="' + 
					feed_item.find('link').text() + '"><span>' + feed_item.find('title').text() + "</span></a></h5>";

				output +=  feed_item.find('description').text();

				output += '<p class="timestamp">Posted by <a href="' + author.find('[nodeName="foaf:homepage"]').attr('rdf:resource') +
					'"><span>' + feed_item.find('[nodeName="dc:creator"]').text() + '</span></a> ' +
					getTimePosted(feed_item.find('pubDate').first().text()) + '</p>';

				// create variables for all values related to answer list
				var recentAnswer = feed_item.find('[nodeName="yeddax:mostRecentAnswer"]'),
					ra_homepage = recentAnswer.find('[nodeName="foaf:homepage"]').attr('rdf:resource') || '',
					ra_person = recentAnswer.find('[nodeName="foaf:Person"]').text() || '',
					ra_pub_date = recentAnswer.find('pubDate').text() || '',
					y_answers = feed_item.find('[nodeName="yedda:answers"]').text() || '',
					yvc_text = feed_item.find('[nodeName="yeddax:viewCount"]').text() || '';

				if( yvc_text.length > 0 || y_answers.length > 0 || ra_homepage.length > 0 || 
					ra_person.length > 0 ||	ra_pub_date.length > 0)
				{

					output += '<ul class="info">';
					var ra_first_check = false,
						yvc = ( yvc_text.length > 0 )? parseInt(yvc_text) : 0;
					
					output += '<li ' + first + '>Viewed ' + yvc + ' times</li>'
					ra_first_check = true;

					if (y_answers.length > 0)
					{
						if (y_answers=="0") {
							output += '<li';
							output += (ra_first_check == false)? ' ' + first : '' ;
							output += '><a href="' + feed_item.find('link').text() + 
								'"><span>Be the first to answer</span></a></li>';
							ra_first_check = true;
						} else { 
							output += '<li';
							output += (ra_first_check == false)? ' ' + first : '' ;
							output += '>' + y_answers + ' Answers</li>';
							ra_first_check = true;
						}
					}

					if( ra_homepage.length > 0 || ra_person.length > 0 || ra_pub_date.length > 0)
					{				
						output += '<li';
						output += (ra_first_check == false)? ' ' + first + '>' : '>' ;

						if (ra_homepage.length > 0 || ra_person.length > 0)
						{
							output += 'Last Answer by <a href="' + ra_homepage + '"><span>' +
								ra_person + '</span></a> ';
						}
					
						if(ra_pub_date.length > 0)
							output += getTimePosted(ra_pub_date);
					
						output += '</li>';
					}

					output += '</ul>';
				}
				output += '</div></li>';
			});

			output += '</ul>';

			//get pagination html
			var pagination = buildFeedPagination(page_num, total_pages);

			$('.community_support .no_results').replaceWith(output);
			$('.search_tabs').append(pagination);
			noCSSearchResults=false;
			loadOmniunih();
		}
		else
			setNoCSResults();
	//} catch(err) {
	//	setNoCSResults();
	//}

	$(".cs_loading").css("display", "none");

}

function setNoCSResults(){

	$(".cs_loading").css("display", "none");

	var ctxVal = ($.cookie("product_name") && $.cookie("product_name").length > 1)? $.cookie("product_name") : "Other";

	$('#no_results_search input[name=ctxtags]').val( ctxVal );	
	$('.no_results').css('display', 'block');
	loadOmniunih();
}

})(jQuery);
 

function checkSearchTerm(term){
	term = term.replace(/^\s*|\s*$/g,''); //remove whitespace for checks
	if(term.length < 1 || term == default_search)
	{
		//alert('Please enter a keyword, phrase or question.');
		return false;
	}
	return true;
}

function deleteCookies(){
	if (jQuery.cookie("product")) jQuery.cookie("product", null, { path: '/help' });
	if (jQuery.cookie("kanissa_id")) jQuery.cookie("kanissa_id", null, { path: '/help' });
	if (jQuery.cookie("product_name")) jQuery.cookie("product_name", null, { path: '/help' });
}

function productSearchAction(){
	if (!(sec_search_form.find('input[name=product]').length > 0 && sec_search_form.find('input[name=product_name]').length > 0 && sec_search_form.find('input[name=kanissa_id]').length > 0))
		return true;
	deleteCookies();
	jQuery.cookie("product",sec_search_form.find('input[name=product]:checked').val(), { path: '/help' });
	jQuery.cookie("kanissa_id",sec_search_form.find('input[name=kanissa_id]').val(), { path: '/help' });
	jQuery.cookie("product_name",sec_search_form.find('input[name=product_name]').val(), { path: '/help' });
}

//function to trigger a search term check on all forms that have an input
function buildSearchCheck(s_input){
	var parent_form = jQuery(s_input.form),
		form_submit = parent_form.find('button'),
		input_id = s_input.id;

	//checks for the enter key pressed, if it has been it prevents auto form submission
	//then triggers a "click" of the submit button which checks the search term
	jQuery(s_input).keypress(function(e){
		if(e.keyCode == 13){
			e.preventDefault();
			form_submit.trigger('click');
		}
	});
	
	//if the form button doesn't have a click function this attaches one which checks the value
	//of the search term
	if(!form_submit.attr('onclick'))
	{
		form_submit.live('click', function (){
			return checkSearchTerm(jQuery('#' + input_id).val());
		});
	}
}

function strToNum(str) {
	return str.replace(/\./g, '').replace(/,/g,'.').replace(/[^\d\.]/g,'');
}
function repositionModalIE6() {
	var isIE6 = navigator.userAgent.indexOf("MSIE 6.0") != -1 && navigator.appName == "Microsoft Internet Explorer";
	if (isIE6) {
		var modal = jQuery(".modal_wrap");
		modal.css('position',"absolute");
		modal.css('left',jQuery(window).scrollLeft()+(jQuery(window).width()/2)-((strToNum(modal.css('width')))/2));
		modal.css('top',jQuery(window).scrollTop()+((jQuery(window).height()/3)-((strToNum(modal.css('height')))/2)));
	}
}
function resizeStretchIE6() {
	var isIE6 = navigator.userAgent.indexOf("MSIE 6.0") != -1 && navigator.appName == "Microsoft Internet Explorer";
	if (isIE6) {
		jQuery('.stretch').css({height:jQuery("body").height(), width:jQuery("body").width()});
	}
}

