/* Search */

/* Global Variables */
var resultTab = null;
var type = null;
var id = null;
var localid = null;
var active = 'welcome';
var media = null;
var activeTab = null;
var lastTab = 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;

			hashType = hash.split(':');
			if ((hashType[0] == 'playing') && (hashType[1] == 'videos' || hashType[1] == 'podcasts' || hashType[1] == 'radio') && (hashType[2].length > 0)) {
				playMedia(hashType[1], hashType[2]);
				active = hashType[1];
			} else {
				active = hash;	
				// Hide Media Player If Open
				if (jQuery("#mediaplayer").css('display') == 'block' || jQuery("#mediacentre").css('display') != 'block')
					closePlayer();

				var tab = Number(jQuery("#tab-" + hash).attr('rel'));
				jQuery("#mediacentre").triggerTab(tab);

				if (lastTab == null)
					//Set Timeout for IE7 (Fails to load without timeout)
					loadMedia(hash, 1);
					
				lastTab = hash;
			}
		}
	} else {
		// Hide Media Player If Open
		if (jQuery("#mediaplayer").css('display') == 'block' || jQuery("#mediacentre").css('display') != 'block')
			closePlayer();
		
		hash = 'welcome';
		activeTab = 'welcome';
		jQuery("#mediacentre").triggerTab(1);
	}
}

jQuery(document).ready(function() {
	jQuery("#mediacentre .preload").remove();
	
	// Initialize History plugin.
	setTimeout(function(){ jQuery.history.init(pageload); }, 10);

	// Initialize Result Tabs
	jQuery('#mediacentre').tabs({ fxFade: true, fxSpeed: 'fast' });

	// If Media Called, Play Media. If Hash Exists, Load Media Tab
	if (playing) {
		playMedia(goto,playing);
		active = goto;
	}
});


jQuery(function() {
	// Submenu Click Event Handler
	jQuery("#navMediaCentre a").live('click', function() {
		if (jQuery(this).attr('alt').length > 0) {
			// Hide Media Player If Open
			if (jQuery("#mediaplayer").css('display') == 'block' || jQuery("#mediacentre").css('display') != 'block')
				closePlayer();
				
			jQuery("#tab-" + jQuery(this).attr('alt')).trigger('click');
			return false;
		}
	});
	
	// Tab Click Event Handler
	jQuery("#mediacentre li a").click(function() {
		if (jQuery(this).attr('href').substring(1) != activeTab)
			loadTab(jQuery(this).attr('href').substring(1));
		else
			return(false);
	});
	
	// Hide Media Player
	jQuery("#mediaplayer #closePlayer span").live('click', function(){ closePlayer(); });

	// Bind PlayMedia Click Event Handler
	jQuery(".playmedia, table td div.info, table td div.title, table td img.play, #pageBanner .play").live('click', function() {
		media = jQuery(this).attr('alt').split(':');
		playMedia(media[0], media[1]);
	});	

	// Initialize Pagination 
	jQuery("#mediacentre .pagi li a").live('click', function() {
		loadMedia(jQuery(this).parent().parent().parent().parent().parent().attr('id'), jQuery(this).attr("name").substr(4));
	});
});

// Hide the Media Player & Clear the banner
function closePlayer() {
	jQuery("#player").html('');
	jQuery("#mediaplayer").hide();
	jQuery("#mediacentre").show();
	clearMediaBanner();
}

// Load A media tab and its contents
function loadTab(tab) {
	// Set History Checkpoint Using Location Hash
	if (activeTab != tab) {
		jQuery("#" + tab).attr('id', 'placeholder');
		jQuery("#playing").append('<div id="' + tab + '" class="' + tab + 'Top"></div>');
		setTimeout(function(){ jQuery.history.load(tab); jQuery("#" + tab).remove(); jQuery("#placeholder").attr('id', tab); }, 1);
	}

	active = tab;
	lastTab = tab;
	
	// Hide Media Player If Open
	if (jQuery("#mediaplayer").css('display') == 'block' || jQuery("#mediacentre").css('display') != 'block')
		closePlayer();

	// Load the tab's media list
	if (jQuery("#" + tab).attr('alt') != jQuery("#channels").val())
		loadMedia(tab, 1);
}

function loadMedia(section, pagination) {
	jQuery('.' + section + 'Top').remove();
	resultTab = section;
	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 + "&page=" + currentPage,
		processData: true,
		dataType: "json",
		success: function(data) {
			//alert(section);
			searchJson(data, ajax + "healthAdvisor.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) {
		html = '<div id="mediaSelection"><table cellspacing="0">';
		jQuery.each(data.items, function(i, item){
			if ((i % 2) == 0)
				html += '<tr>';
			html +='<td><img class="play" alt="' + item.type + ':' + item.id + '" src="' + images + item.type + '/' + item.thumbnail + '" /><div class="info" alt="' + item.type + ':' + item.id + '"><div class="title" alt="' + item.type + ':' + item.id + '">' + item.title + '<span>' + item.tag + '</span></div><div class="playmedia" alt="' + item.type + ':' + item.id + '">'
			if (item.type == 'videos')
				html += 'WATCH';
			else
				html += 'LISTEN';
			html += ' NOW</div></div></td>';
			if ((i % 2) == 1)
				html += '</tr>';
				
			j++;
		});
		(j % 2) == 1 ? html += '</td>' : '';
		html += '</tr></table></div>';
	} else {
		html = "<div id='mediaSelection'>Unfortuantely we didn't find any media within your search, but we're always updating so check back soon!<br /><br /></div>";
	}
	
	if (numPages > 1)
		pageNav = jQuery('<div id="mediaPagination" class="pagination"><div id="pagi-wrapper">'+Pagination(record,numPages,current)+'</div></div>');
	else
		pageNav = jQuery('<div id="mediaPagination" class="pagination"></div>').css('padding-top','15px');

	// Plug Results into Container and Prepend Resultset Title
	jQuery("#" + resultTab).html(html).append(pageNav).attr('alt', jQuery("#channels").val()).append('<a id="rss" href="' + healthadvisor + 'rss">Subscribe to RSS <img src="' + images + 'iconRSS.gif" /></a>').prepend('<select class="channels">' + jQuery("#channels").html() + '</select>');
	jQuery(".channels").val(searchterm);

	// Change Channel
	jQuery(".channels").change(function(){
		searchterm = jQuery(this).val();
		jQuery("#channels").val(searchterm);
		loadMedia(active, 1);
	});
}

function playMedia(mediaType, mediaID) {
	// Set Global Media Information
	type = mediaType;
	id = mediaID;
	localid = mediaID;
	// Set History Checkpoint Using Location Hash
	if (activeTab != 'playing:' + type + ':' + id)
		jQuery.history.load('playing:' + type + ':' + id);
		
	// Call Results via JSON
	jQuery.ajax({
		type: "POST",
		url: ajax + "healthAdvisor.php",
		data: 'loadMedia=' + type + '&id=' + id,
		processData: true,
		dataType: "json",
		success: function(json){
			if (json.title != 'error') {
				// Retrieve Number of Comments
				jQuery.post(ajax + 'healthAdvisor.php', { 'countComments':type, 'id':id }, function(data) {
					commentCount = data;
					
					// Load Comment Control
					loadCommentControl();
					
					jQuery("#mediacentre").hide();
					jQuery("#mediaplayer").show();
					
					// Load Media Centre Banner
					loadMediaBanner(json.title, json.summary, json.meta, json.rating, json.date, json.thumbnail);
					
					// Set SocialShare Link
					shareAlt = mediacentre + type + "/" + id + "|Rexall Media Centre: " + json.title;
					
					if (type == 'podcasts' || type == 'radio')
						jQuery("#player").html('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="475" height="45" id="podcastplayer"><param name="movie" value="' + podcasts + 'player.swf" /><param name="flashVars" value="aud=' + podcasts + json.file + '&len=' + json.duration + '" /><param name="wmode" value="opaque" /><!--[if !IE]>--><object type="application/x-shockwave-flash" id="podcastplayer" data="' + podcasts + 'player.swf" quality="high" wmode="opaque" width="475" height="45" flashVars="aud=' + podcasts + json.file + '&len=' + json.duration + '"></object><!--<![endif]--></object>');
					else
						jQuery("#player").html(json.file);
						
					// Incase of banner ad requested under specific podcast
					// 19 = Dr.Nathan Hermann - Alzheimers (Radio Podcast)
					if(type == 'radio' && id == 19)
						jQuery("#bannerAd").css({display:'block'}).html('<div class="subSection"><a href="http://www.alzheimertoronto.org/serv_firstLinkRPP.htm" target="_blank"><img src="assets/images/healthadvisor/alzheimertoronto-firstlink.jpg" border="0"></a></div>');
					else
						jQuery("#bannerAd").css({display:'none'}).html('');	
				});
			} else
				alert("We're sorry, but the selected media file could not be accessed at this time");
		}
	});
}

function loadMediaBanner(title, summary, tag, rating, date, thumbnail) {
	jQuery("#pageBanner").load(ajax + 'mediaBanner.php', {'title':title, 'summary':summary, 'tag':tag, 'rating':rating, 'date':date, 'thumbnail':thumbnail, 'type':type, 'id':id}, function(){ initializeRatings(rating); });
}

function clearMediaBanner() {
	jQuery("#pageBanner").load(ajax + 'mediaBannerStandard.php', {'id':mediaBanner[0], 'title':mediaBanner[1], 'meta':mediaBanner[2], 'date':mediaBanner[3], 'thumbnail':mediaBanner[4], 'rating':mediaBanner[5]}, function(){ initializeRatings(mediaBanner[5]); jQuery("#rating ul li").unbind('click').unbind('mouseover'); });
}

function initializeRatings(rating) {
	jQuery("#pageBanner img, #rating").ifixpng();
	
	rating = Number(rating);
	// Display Current Rating
	jQuery("#rating ul li[alt='" + rating + "']").prevAll().andSelf().each(function(){
		jQuery(this).find('img').attr('src', images + 'iconStarOrange.gif');
	});
	
	// Initialize Hover & Click Event Triggers for Article Rating
	jQuery("#rating ul li").hover(function(){
		if (jQuery("#rating").attr('alt') != 'rated') {
			jQuery(this).prevAll().andSelf().each(function() {
				jQuery(this).find('img').attr('src', images + 'iconStarOrange.gif');
			});
			jQuery(this).nextAll().each(function() {
				jQuery(this).find('img').attr('src', images + 'iconStarBlue.gif');
			});
		}
	}, function(){
		if (jQuery("#rating").attr('alt') != 'rated') {
			if (rating == 0)
				jQuery("#rating ul li").each(function() {
					jQuery(this).find('img').attr('src', images + 'iconStarBlue.gif');
				});
			else
				jQuery("#rating ul li[alt='" + rating + "']").prevAll().andSelf().each(function() {
					jQuery(this).find('img').attr('src', images + 'iconStarOrange.gif');
				});
				jQuery("#rating ul li[alt='" + rating + "']").nextAll().each(function() {
					jQuery(this).find('img').attr('src', images + 'iconStarBlue.gif');
				});
		}
	});
	
	jQuery("#rating ul li").click(function() {
		if (jQuery("#rating").attr('alt') != 'rated') {
			rating = jQuery(this).attr('alt');
			jQuery("#rating").attr('alt','rated')
			jQuery("#rating div").text('Rated');
			jQuery("#rating ul li").css('cursor','default');
			jQuery.post(ajax + 'sessions.php', {'session':'rating', 'type':type, 'id': id});
			jQuery.post(ajax + 'healthAdvisor.php', {'rating':jQuery(this).attr('alt'), 'type': type, 'id': localid});
		}
	});

	// Revert cursor back to default
	if (jQuery("#rating").attr('alt') == 'rated')
		jQuery("#rating ul li").css('cursor','default');
}