/* Search */

/* Global Variables */
var searchterm = null;
var numReturns = null;
var resultTab = null;
var community = null;
var activeTab = null;

// PageLoad function
// This function is called when:
// 1. after calling jQuery.historyInit();
// 2. after calling jQuery.historyLoad();
// 3. after pushing "Go Back" button of a browser
function pageload(hash) {
	// If hash exists, initialize the tab
	if (hash)
		if (activeTab != hash)
		{
			activeTab = hash;
			jQuery('#tab-' + hash).trigger('click');
		}
}

jQuery(document).ready(function()
{
	
	// Initialize History plugin.
	jQuery.history.init(pageload);
		
	// Initialize Result Tabs
	jQuery('#results').tabs({ fxFade: true, fxSpeed: 'fast' });

	// Initialize search in the specified tab on page initialization. Default to articles tab
	siteSearch(jQuery("#searchTerm").val().replace(/\\/g, ""), (location.hash == '' ? 'articles' : location.hash.substring(1)));
});


jQuery(function(){
	// Tab Click Event Handler
	jQuery("#results li a").click(function(){
		if (jQuery.trim(jQuery(jQuery(this).attr('href')).attr('alt')) != searchterm)
		{
			if (jQuery(this).attr('href') == "#community")
				loadCommunity();
			else
				loadSearch(jQuery(this).attr('href').substr(1), 1);
		}
	});
});

//  Search Health Advisor
function siteSearch(term, section)
{
	if (term == '')
		alert('Please enter a search term');
	else if (term.length < 3)
		alert('Your search term must be at least 3 characters in length');
	else
	{
		// Save the searchterm globally
		searchterm = term;
	
		// Show Results Tabs
		jQuery("#results").show();

		// Save Search For Tagcloud Use
		jQuery.post(ajax + 'framework.php', { 'searchterm': searchterm });

		// Clear Pagination 
		jQuery("#" + section + " #pagination").remove();
		
		// Load Results Into Active Tab
		loadSearch(section, 1);
	}
}

function loadSearch(section, pagination)
{
	resultTab = section;
	if (Number(pagination) > 0)
		currentPage = Number(pagination);
	else
		currentPage = 1;
		
	// Call Results via JSON
	jQuery.ajax({
		type: "POST",
		url: ajax + "framework.php",
		data: "search=" + searchterm + "&section=" + section + "&page=" + currentPage,
		processData: true,
		dataType: "json",
		beforeSend: function(){
			if (resultTab != "media")
			{
				jQuery("#" + section + " .pagi-elements, #" + section + " img").remove();
				jQuery("#" + section + " #resultset").html('');
				jQuery("#" + section).prepend('<img src="' + images + 'loading.gif" border="0" />');
			}
		},
		success: function(data){
			searchJson(data, ajax + "framework.php", "POST", images + "loading.gif", "#" + section);
		}
	});
}

function searchJson(data, url, method, busy, id)
{
	var html = new String();
	var currentPage = new String();
	var numPages = Math.floor(parseFloat(data.total) / 10) + Math.ceil(Math.floor(parseFloat(data.total) % 10) / 10);
	var current = data.crr;
	var record = 5;
	var j = 0;
	if (data.total > 0)
		if (id.substring(1) == 'articles')
			jQuery.each(data.items, function(i, item){
				var section = item.type.toLowerCase().replace(/\s/g, '');
				if (section == 'conditions' || section == 'medications' || section == 'naturalproducts')
					section = site + 'healthadvisor/' + section + '/';
				else
					section = healthandwellness;
				item.type += ': ';
				html += '<div class="pagi-elements"><a href="' + section + item.id + '" class="title">' + item.type.replace('Conditions: ', '') + item.name + '</a><br />' + item.summary + '</div>';
				j++;
			});
		else if (id.substring(1) == 'discussions')
		{
			html += '<table id="tbSearchDiscussions" cellspacing="0">';
			jQuery.each(data.items, function(i, item){
				html += '<tr><td class="tdDiscussions"><a href="' + item.link.replace("{healthadvisor}", healthadvisor) + '">' + item.title + '</a><br />';
				if (item.author != null)
					html += 'Latest post by ' + item.author;
				else
					html += 'Be the first to post in this thread!';
				html += '</td><td class="tdDiscussionComments">' + item.comments + '</td></tr>';
				j++;
			});
			html += '</table>';
		}
		else if (id.substring(1) == 'media')
		{
			html = '<table class="tbSearchMedia" cellspacing="0">';
			jQuery.each(data.items, function(i, item){										 
				if ((i % 2) == 0)
					html += '<tr>';
				html +='<td class="thumbnail"><img src="' + images + item.type + '/' + item.thumbnail + '" /></td><td class="info"><div class="title">' + item.title + '<span>' + item.tag + '</span></div><a class="playmedia" href="' + healthadvisor + 'mediacentre#playing:' + item.type + ':' + item.id + '">'
				if (item.type == 'videos')
					html += 'WATCH';
				else
					html += 'LISTEN';
				html += ' NOW</a></td>';
				if ((i % 2) == 1)
					html += '</tr>';
					
				j++;
			});
			if ((j % 2) == 1)
				html += '</td></tr></table>';
			else
				html += '</tr></table>';
		}
		else if (id.substring(1) == 'instore' || id.substring(1) == 'pharmacy')
			jQuery.each(data.items, function(i, item){
				html += '<div class="pagi-elements"><a href="' + site + item.link + '" class="title">' + item.title + '</a><p>' + item.description + '</p></div>';
				j++;
			});
		else if (id.substring(1) == 'products')
			jQuery.each(data.items, function(i, item){
				html += '<div class="pagi-elements"><a href="' + instore + 'Home-Health-Care/' + item.section + '#' + item.id + '" class="title">' + item.product + '</a><p>' + item.description + '</p></div>';
				j++;
			});
	if (j > 0)
	{			
		// Format "Of # results" in Result Title
		if (Number(current) * 10 > data.total)
			numReturns = data.total;
		else
			numReturns = Number(current) * 10;
				
		resultset = '<div id="resultset">Displaying ' +  ((Number(current) * 10) -9) + '-' + numReturns + ' of ' + data.total + ' ' + resultTab + ' for <b><em>' + searchterm + '</em></b></div>';
		pageNav = jQuery('<div id="pagination"><div id="pagi-wrapper">'+Pagination(record,numPages,current)+'</div></div>').css('border-top', '1px solid #CCCCCC');
	}
	else
	{
		resultset = '<div id="resultset">Unfortunately, we didn\'t find any ' + resultTab + ' about <b><em>' + searchterm + '</em></b></div>';
		pageNav = jQuery('<div id="pagination"></div>');
	}
	
	// Plug Results nto Container and Prepend Resultset Title
	jQuery("#" + id.substring(1)).html(html).prepend(resultset).append(pageNav).attr('alt', searchterm);

	// Initialize Pagination 
	jQuery(".pagi li a").click(function(){
		loadSearch(jQuery(this).parent().parent().parent().parent().parent().attr('id'), jQuery(this).attr("name").substr(4));
	});
}
