/**
 * @author Tyler Gaw <tylerg@arc90.com>
 *
 * Javascript document for University Page specifics.
 *
 */
var defaultDiscipline='';

$(document).ready(function()
{
	$('#subjects-list li a strong').truncate({ max_length: 25 });
	$('#courses-list li a').truncate({ max_length: 25 });
	$('#subjects-list li').click(SubjectClickHandler);
	TruncateUniName();
	
	/**
	 * Course Live Searching / Suggest thingy
	 *
	 */
	$('#course-search-input').smartinput();
	$('#course-search-input').attr('autocomplete', 'off').filterlist({
		url: function (element) { return $('#course-search-form').attr('action') + '&q=' + element.val(); },
		dataType: 'json',
		minChars: 3,
		before: SearchPrepareResults,
		success: function(data) { 
			ParseSearchResults(data.courses);
		}
	});
	
	/**
	 * Load the first subject, and init subject paging
	 * NOTE: We'll most likely need the ability to access a subject directly by URL
	 *       These two will need to be handled differenly in that case
	 *
	 */
	
	var newsubjecttext = '#'+defaultDiscipline;
	
	if(document.getElementById(defaultDiscipline) != null)
	{
		
		if(navigator.appName == 'Netscape')
		{
			$(newsubjecttext).click();
			SubjectPaging(defaultDisciplinePage);
		}
		else
		{
			document.getElementById(defaultDiscipline).click();
			SubjectPaging(defaultDisciplinePage);
		}
	}
	else
	{
		$('#subjects-list li:first').click();
		SubjectPaging(1);
	}
});


/**
 * Long uni names need to be truncated, but sometimes there is a school crest
 * and sometimes there isn't. So, the allowed length before truncating is different.
 * We need to determine if the school crest is present or not to set the correct length
 *
 */
var TruncateUniName = function ()
{
	var length;
	
	if ($('#uni-crest').length === 0) 
	{
		$('#university-header h2').css({'max-width': '48%', 'min-width': '48%'})
		length = 30;
	}
	else
	{
		length = 25;
	}
	
	$('#university-header h2 span').truncate({max_length: length});
};

/**
 * Create an empty Object to house data about the selected subject
 *
 */
var SubjectData = {};


/**
 * Prepare University Subject List for paging
 *
 */
var SubjectPaging = function(page)
{
	var displayMax = 10;
	var startPoint = (page - 1) * displayMax;
	var endPoint   = startPoint + displayMax;
	
	var itemsObject = $('#subjects-list li').each(
		function(i)
		{
			if(i < startPoint || i > endPoint - 1)
			{
				$(this).css('display', 'none');
			}
			else
			{
				$(this).css('display', 'block');
			}
		}
	);
	
	var numItems = itemsObject.length;
	
	/**
	 * Set pages/current display text
	 */
	var displayEndPoint = (endPoint > numItems) ? numItems : endPoint;
	$('#subjects-paging dt').html((startPoint + 1) + "&ndash;" + displayEndPoint + " of " + numItems + " Subjects");
	
	/**
	 * Init Paging
	 */
	var pageCount  = Math.ceil(numItems / displayMax);
	var opts = getSubjectPagingOpts(page, pageCount);
	$('#subjects-paging dd').pager(opts);
};


/**
 * Handle loading a new subject when clicked
 *
 */
var SubjectClickHandler = function()
{	
	
	$('#courses-list').html('<p id="course-loading">Loading...</p>');
	
	/**
	 * Converting a jQuery object back into DOM object then back to a jQuery object :)
	 *      because, I can't do this: $(this + ' a');
	 */
	var $this = $(this)[0];
	var anchor = $($this.getElementsByTagName('a')[0]);
	var url = anchor.attr('href');
	
	
	setTimeout(function(){
		jQuery.ajax({
			dataType: 'json',
			url: url,
			success: function(data) { 
				ParseSubject(data.subject);
			}
		});
	}, 500);
	
	
	/**
	 * Deactivate the previously selected item, activate the current
	 */
	$(this).addClass('active').siblings().removeClass('active');
	return false;
};


/**
 * Create html from a subject JSON object
 *
 * @param object subject - a JSON object containing the subject data
 *
 */
var ParseSubject = function(subject)
{
	SubjectData.name         = selectedDisciplineName;
	SubjectData.url          = '';
	SubjectData.totalCourses = totalModuleCount;
	
	$('#subject-meta h4').remove();
	$('#subject-meta').prepend("<h4 id='subject-name'>" + SubjectData.name  + "</h4>");
	$('#subject-name').truncate({ max_length: 56 });
	
	/**
	 * Be sure to remove the previous top guru element
	 */
	$('#top-guru').remove();
	
	/*if (subject.topGuru != null)
	{
		ParseTopGuru(subject.topGuru);
	}
	*/
	if(SubjectData.totalCourses != 0)
	{
		CoursesPaging(1);
	}
	else
	{
		$('#courses-paging dt, #courses-paging dd').html('');
		SubjectSetEmptyState();
	}
};


/**
 * If a subject has no courses
 *
 */
var SubjectSetEmptyState = function()
{	
	if(universityCountry == 'United States of America')
	{
	var msg = '<strong>There are no courses for this subject yet.</strong> Get things started by sharing notes and inviting your classmates now.';
	}
	else
	{
		var msg = '<strong>There are no modules for this subject yet.</strong> Get things started by sharing notes and inviting your classmates now.';
	}
	var inviteUrl = 'invitationViewActionnlu.do?universityId='+selectedUniversityId+'&selectedDisciplineId='+selectedDisciplineId;
	var opts = '<ul><li><a href="notesUploadViewAction.do" class="btn-share-notes">Share Notes</a></li><li><a href="'+inviteUrl+'" class="btn-invite-classmates">Invite Classmates</a></li></ul>';
	
	/**
	 * NOTE: We are not implementing the Add Course functionality yet. Don't show the button
	 */
	addBtn = "";
	$('#courses-list').html('<div id="subject-empty-state"><p>' + msg + '</p>' + opts + '</div>');
};


/**
 * Create the TopGuru badge for the selected subject
 *
 * @param object topGuru - a json object containing the top guru data
 *
 */
var ParseTopGuru = function(topGuru)
{
	/**
	 * Determine status display based on status
	 */
	var testStatus = topGuru.status.toLowerCase();
	var statusDisplay = '';
	
	switch(testStatus)
	{
		case 'uber':
		case 'gold':
		case 'silver':
		case 'bronze':
			statusDisplay = ucwords(testStatus) + " Guru";
			break;
		case 'newbie':
		case 'member':
			statusDisplay = ucwords(testStatus);
	}
	
	/**
	 * Build the html output
	 */
	var html = '\
	<p id="top-guru">\
		<strong>Top Guru:</strong>\
		<a href="'+ topGuru.url +'" class="guru-tab">\
			<img src="'+ topGuru.image +'" alt="" /> '+ topGuru.name +' \
			<span class="status-'+ testStatus +'">'+ statusDisplay +'</span>\
		</a>\
	</p>';

	$('#courses-header').append(html);
};


/**
 * Load a new set of courses, either when a subject is selected or
 *      a new course page of a subject
 *
 * @param int page - The requested page of courses
 *
 */
var LoadCourses = function(page)
{	
	/**
	 * For development/testing
	 */
	var resourcesUrl    = "moduleListViewActionnlu.do?SearchModule=false&disciplineId="+selectedDisciplineId+"&startIndex="+startIndex;
	
	$('#courses-list').html('<p id="course-loading">Loading...</p>');
	
	/**
	 * A quick pause for the previous courses to be removed completely
	 */
	setTimeout(function(){
		jQuery.ajax({
			dataType: 'json',
			url: resourcesUrl,
			success: function(data) { 
				ParseCourses(data.courses);
			}
		});
	}, 500);
};


/**
 * Create html from the courses JSON object
 *
 */
var ParseCourses = function(courses)
{ 
	var html, displayMax, breakPoint, count, hasNotes;

	html = '<ul>';
	displayMax = 36;
	breakPoint = 12;
	count      = 0;
	
	$.each(courses, function(i, item)
	{
		
		escapedModuleName = escape(item.name);
		count++;
		if(i < displayMax)
		{
			hasNotes = (item.notes > 0) ? "class='has-notes'" : "";
			html += "<li " + hasNotes + "rel='" + item.notes+"|"+item.country+"|"+escapedModuleName+"' id=" + item.id + " ><a href='" + item.url + "'>" + item.name + "</a></li>";
			if(count == breakPoint)
			{
				html += '</ul><ul>';
				count = 0;
			}
		}
		else
		{
			return false;
		}
	});

	$('#courses-list').html(html);
	$('#courses-list ul:last').addClass('last-item');
	
	$('#courses-list li').click(CourseClickHandler);
	$('#courses-list li a').truncate({ max_length: 25 });
};


/**
 * When a course is clicked, display the course context menu
 *
 */
var CourseClickHandler = function()
{		
	$('.course-context-menu').remove();
	var relDisc = $(this).attr('rel').split('|');
	var notes = relDisc[0];
	var courseId = $(this).attr('id');
	var countryId = relDisc[1];
	var moduleName = relDisc[2];
	var countryId='';
	
	
	if(universityCountry!='United Kingdom')
	{
		countryId=2;
	}else
	{
		countryId=1;
	}
	 /**
	 * These are temporary urls
	 *
	 */
	if(notes != 0)
	{
		var viewUrl   = 'ModuleDetailViewActionnlu.do?moduleexist=true&module_id='+courseId+'&countryId='+countryId+'&moduleName='+moduleName+'';
	}
	else
	{
		var viewUrl   = 'ModuleDetailViewActionnlu.do?moduleexist=false&module_id='+courseId+'&countryId='+countryId+'&moduleName='+moduleName+'';
	}
	 
	
		window.location = viewUrl;
		
	//$('body').append(html);
	
	return false;
};


/**
 * Create and/or modify the status, results, and clear elements before the results come back
 *
 */
var SearchPrepareResults = function()
{
	
	/**
	 * If the status message is not displayed, display it
	 *  if it is, just modify it
	 */
	if($('#course-search-status').length == 0)
	{
		$('#course-search-form fieldset').append('<span id="course-search-status" class="searching">Searching...</span>');
	}
	else
	{
		$('#course-search-status').attr('class', 'searching').html('Searching...');
	}
	
	/**
	 * Append the results container to the DOM if it doesn't exist
	 */
	if($('#course-search-results').length == 0)
	{
		$('#course-search-container').append('<div id="course-search-results" style="display:none;"></div>');
		
		/**
		 * Remove the context menu if the results section is scrolled
		 */
		$("#course-search-results").scroll(function()
		{
			$('.course-context-menu').fadeOut(400);
		});
	}
	
	if($('a.btn-clear').length == 0)
	{
		$('#course-search-container').append('<a class="btn-clear"></a>');
		$('.btn-clear').click(CourseSearchClear);
	}
}


/**
 * Parse search results
 *
 * @param object results - JSON Object with course search results
 *
 */
var ParseSearchResults = function(results)
{
	var totalResults = results.length;
	
	if(totalResults > 0)
	{
		var searchQuery = $('#course-search-input').val();
		var minColCount = 80;
		var midPoint    = Math.ceil(totalResults * 0.5);
		var breakPoint = (midPoint < minColCount) ? minColCount : midPoint;
		
		var html = '<ul>';
		var count = 0;
		
		$.each(results, function(i, item)
		{
			count++;
			
			/**
			 * RegEx check to bold the searched-for value in each result
			 *
			 */
			var str = item.name;
			var exp = new RegExp(searchQuery, 'ig');
			var matched = exp.exec(str);
			var displayName = str.replace(exp, '<span>' + matched + '</span>');
			var hasNotes = (item.notes > 0) ? " class='has-notes' " : "";
			
			html += "<li "+ hasNotes +" rel='" + item.notes+"|"+item.country+"|"+item.name+"' id=" + item.id + "><a href=" + item.url + ">" + displayName + "</a></li>";
			
			if(count == midPoint)
			{
				html += '</ul><ul>';
			}
		});
		
		$('#course-search-results').html(html).slideDown();
		$('#course-search-results li').click(CourseClickHandler);
		$('#course-search-status').attr('class', 'has-results').html('Your search returned ' + totalResults + ' results');
	}
	else
	{
		$('#course-search-status').attr('class', 'no-results').html('Your search returned 0 results');
	}
};


/**
 * Reset the search input and clear the results (if any)
 *
 */
var CourseSearchClear = function()
{
	$(this).remove();
	$('.course-context-menu').fadeOut(400);
	$('#course-search-status').remove();
	$('#course-search-input').val('').blur();
	$('#course-search-results').slideUp(200, function()
	{
		$(this).remove();
	});
};


/**
 * Retrieve the options for subjects paging
 *
 */
var getSubjectPagingOpts = function(page, pagecount)
{
	return SubjectPagingOpts = {
						pagenumber: page, pagecount: pagecount, 
						buttonClickCallback: SubjectPaging,
						emptyClass: 'disabled', currentClass: 'active', specialClass: 'arrow',
						prevLabel: '&lt;', nextLabel: '&gt;',
						displayFirstLast: false
					};
};


/**
 * Prepare University Courses List for paging
 *
 */
var CoursesPaging = function(page)
{	
	
	var displayMax = 36;
	var startPoint = (page - 1) * displayMax;
	var endPoint   = startPoint + displayMax;
	var numItems   = totalModuleCount;
	
	/**
	 * Set pages/current display text
	 */
	var displayEndPoint = (endPoint > numItems) ? numItems : endPoint;
	
	if (universityCountry == 'United States of America')
	{
	$('#courses-paging dt').html((startPoint + 1) + "&ndash;" + displayEndPoint + " of " + numItems + " Courses");
	}
	else
	{
		$('#courses-paging dt').html((startPoint + 1) + "&ndash;" + displayEndPoint + " of " + numItems + " Modules");
	}
	
	/**
	 * Init Paging
	 */
	var pageCount  = Math.ceil(numItems / displayMax);
	var opts = getCoursesPagingOpts(page, pageCount);
	$('#courses-paging dd').pager(opts);
	
	startIndex = startPoint;
	
	LoadCourses(page);
};


/**
 * Retrieve the options for courses paging
 *
 */
var getCoursesPagingOpts = function(page, pagecount)
{
	return CoursesPagingOpts = {
						pagenumber: page, pagecount: pagecount, 
						buttonClickCallback: CoursesPaging,
						emptyClass: 'disabled', currentClass: 'active', specialClass: 'arrow',
						prevLabel: '&lt;', nextLabel: '&gt;',
						displayFirstLast: false
					};
};