/* 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
	haSearch(jQuery("#searchTerm").val().replace(/\\/g, ""), (location.hash == '' ? 'articles' : location.hash.substring(1)));
});


jQuery(function(){
	// Tab Click Event Handler
	jQuery("#results > ul li a").click(function(){
		// Set History Checkpoint Using Location Hash
		jQuery.history.load(jQuery(this).attr('href').substring(1));
		
		// Verify whether the content in the tab being called has already been initialized
		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 haSearch(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 + 'healthAdvisor.php', { 'searchterm': searchterm });
		
		if (section == 'community')
		{
			// Clear Community
			jQuery("#community #resultset").remove();
			
			// Load Community Provinces (If Community Exists)
			loadCommunity();
		}
		else
		{
			// Clear Pagination 
			jQuery("#" + section + " #pagination").remove();
			
			// Load Results Into Active Tab
			loadSearch(section, 1);
		}
	}
}

// Load Community Support
// Load Provinces; Initialize onload for Cities; Automatically Trigger Cities Onload
function loadCommunity()
{
	jQuery("#citiesContainer, #supportGroups").html('');
	jQuery("#provinceContainer").load(ajax + "healthAdvisor.php", { 'communities': searchterm }, function(){
		community = jQuery("#provinces").attr('alt');
		jQuery("#provinces").removeAttr('alt');
		
		// Community Support Province Dropdown
		jQuery("#provinces").change(function(){
			jQuery("#citiesContainer").load(ajax + "healthAdvisor.php", { 'community': community, 'province': jQuery(this).val() }, function(){
				jQuery("#cities").change(function(){
					jQuery("#community #pagination").remove();
					communitySearch(1);
				});
				jQuery("#community #pagination").remove();
				if(jQuery('#cities').val() == null)
				{
					jQuery("#provinces").val('').trigger('change');
					alert('There are no community support groups in this province');
				}
				else
					communitySearch(1);
			});
		}).trigger('change');
	});
}
function loadSearch(section, pagination)
{
	resultTab = section;
	
	// Validate pagination & reset accordingly
	if (Number(pagination) > 0) currentPage = Number(pagination); else currentPage = 1;
		
	// Call Results via JSON
	jQuery.ajax({
		type: "POST",
		url: ajax + "healthAdvisor.php",
		data: "search=" + searchterm + "&section=" + section.replace('podcasts', 'podcastsandradio') + "&page=" + currentPage,
		processData: true,
		dataType: "json",
		beforeSend: function(){ // Before retrieving results, format container based on section
			if (resultTab != "podcasts" && resultTab != "videos")
			{
				jQuery("#" + section + " .pagi-elements, #" + section + " img").remove();
				jQuery("#" + section + " #resultset").html('');
				jQuery("#" + section).prepend('<img src="' + images + 'loading.gif" border="0" />');
			}
		},
		success: function(data){ // Upon Results Success, Call Function to Parse JSON Data
			searchJson(data, ajax + "healthAdvisor.php", "POST", images + "loading.gif", "#" + section);
		}
	});
}

// Process JSON Search Data for all sections except community support
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;
	
	// Process Data, formatting results uniquely based on section
	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 + 'healthresource/' + 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("{healthresource}", healthresource) + '">' + item.title + '</a><br />';
				if (item.author != null)
					html += '<span>Latest post by ' + item.author;
				else
					html += '<span>Be the first to post in this thread!';
				html += '</span></td><td class="tdDiscussionComments">' + item.comments + '</td></tr>';
				j++;
			});
			html += '</table>';
		}
		else if (id.substring(1) == 'podcasts' || id.substring(1) == 'videos')
		{
			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="' + healthresource + '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++;
			});
			(j % 2) == 1 ? html += '</td>' : '';
			html += '</tr></table>';
		}
	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 into 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)); });
}

// Initialize JSON Request for Community Support Data
function communitySearch(pagination)
{
	// Validate pagination and reset accordingly
	if (Number(pagination) > 0) currentPage = Number(pagination); else currentPage = 1;
	
	// Call Results via JSON
	jQuery.ajax({
		type: "POST",
		url: ajax + "healthAdvisor.php",
		data: "province=" + jQuery("#provinces").val() + "&city=" + jQuery("#cities").val() + "&groups=" + community + "&page=" + currentPage,
		processData: true,
		dataType: "json",
		beforeSend: function(){ // Modify container elements before retrieving results
			jQuery("#community #supportGroups .pagi-elements, #community #supportGroups img,").remove();
			jQuery("#supportResults").html('');
			jQuery("#community #supportGroups").prepend('<img src="' + images + 'loading.gif" border="0" />');
		},
		success: function(data){ // Upon Results Success, Call Function to Parse JSON Data
			communityJson(data, ajax + "healthAdvisor.php", "POST", images + "loading.gif", "#community");
		}
	});
}

// Process JSON data for community support search results
function communityJson(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;
	
	// Process JSON data, build resultset
	if (data.total > 0)
		jQuery.each(data.items, function(i, item){
			html += '<div class="pagi-elements"><div class="title">' + item.name + '</div><div class="address">' + item.address + ' <br />' + item.phone + '</div><table class="tbContact" cellspacing="0">';
			if (item.website.length > 1)
				html += '<tr><td>Website:</td><td>' + item.website + '</td></tr>';
			if (item.email.length > 1)
				html += '<tr><td>Email:</td><td>' + item.email + '</td></tr>';
			html +='</table></div>';
			j++;
		});
	

	// Format results, Result title, and Pagination
	if (j > 0) // If there are any returns
	{			
		// Format "Of # results" in Result Title
		if (Number(current) * 10 > data.total)
			numReturns = data.total;
		else
			numReturns = Number(current) * 10;
				
		resultset = 'Displaying ' +  ((Number(current) * 10) -9) + '-' + numReturns + ' of ' + data.total + ' Communities for <b><em>' + searchterm + '</em></b>';
		pageNav = jQuery('<div id="pagination"><div id="pagi-wrapper">'+Pagination(record,numPages,current)+'</div></div>').css('border-top', '1px solid #CCCCCC');
	}
	else // IF there are no returns
	{
		resultset = 'No Search Results Returned for <b><em>' + searchterm + '</em></b>';
		pageNav = jQuery('<div id="pagination"></div>');
	}
	
	// Plug Results into Community Container and Prepend Resultset Title
	jQuery("#community").attr('alt', searchterm);
	jQuery("#supportResults").html(resultset);
	jQuery("#community #supportGroups").html(html).append(pageNav)

	// Initialize Pagination 
	jQuery(".pagi li a").click(function(){ communitySearch(jQuery(this).attr("name").substr(4)); });
}
