/**
 * @author Tyler Gaw <tylerg@arc90.com>
 *
 * Javascript document for the GradeGuru homepage
 *
 */

GradeGuru.home = {
	
	// Initializing function
	init: function ()
	{
		this.findSchool.init();
		
		$('#news-ticker ul').innerfade({ speed: 750, timeout: 5000, containerheight: '14px' });
		$('#home-callout-link-more').colorbox({ initialWidth: 100, initialHeight: 100, transition: 'elastic' });
		$('#guru-container em, #guru-container .guru-discipline').truncate({max_length: 32});
		
		// Turn on left-right sliding of top gurus @see jquery.transporter.js
		$('#guru-container').transporter({nextControl: '#arrow-next', prevControl: '#arrow-prev' });
		
		// Make each top guru link to it's profile
		$('#guru-container > li').click(
			function ()
			{
				window.location = $(this).find('a').attr('href');
			}
		);
		
		// Grab the latest Twitter Status @see jquery.tweet.js
		//$('#twitter-status').tweet({ username: 'gradeguru', count: 1, loading_text: "fetching latest tweet..." });
	},
	
	// Filter the list of universities by what the user enters
	findSchool: {
		init: function ()
		{
			$('#find-school-list li strong').truncate({max_length: 45 });
			
			$('#find-school-input')
				.smartinput({blurAction: this.reset})
				.attr({'autocomplete': 'off'}).filterlist(
				{
					// @config - NOTE: This is a special circumstance because of the paths on the homepage
					url: GradeGuru.config.universities.homePage.collection,
					
					data: function (element)
					{
						//return 'university=' + element.val();
						return 'university='+element.val()+'&page=home';
					},
					
					// @config - NOTE: This is a special circumstance because of the paths on the homepage
					resetUrl: GradeGuru.config.universities.homePage.collection,
					minChars: 3,
					success: function (data) 
					{ 
						GradeGuru.home.findSchool.parse(data.universities);
					}
				}
			);
			
			// Return false on form submit in case the user hits the enter key
			$('#find-your-school').submit(
				function () 
				{ 
					return false;
				}
			);
		},
		
		// Create html from the Uni JSON Object
		// @param JSON universities
		// @param INT  startPoint
		parse: function (universities, startPoint)
		{
			var html  = '',
			
				// We need the total number of returned items for quite
				// a few things in the script, so store it here
				total = universities.length,
				
				// The item to start at, we run parseInt on the param
				// pass to our function just as a fail-safe. Default to 0
				start = parseInt(startPoint, 10) || 0,
				
				// The max number of items to display on each 'page'
				max = 5,
				
				// The correct noun to use in the no results message
				noun = '';
			
			// We first hide the list so we can finagle with it
			$('#find-school-list').hide();
			
			// First an initial check to see if there are any items returned
			if (total > 0)
			{

				// Build the the html for all returned items
				$.each(universities, 
					function (i, university)
					{
						// NOTE: Putting on two lines just for readability
						html += "<li><a href='" + university.url + "'><strong>" + university.name;
						html += "</strong> <em>" + university.noteCount + "</em></a></li>";
					}
				);
				
				// Append the generated html to the DOM
				$('#find-school-list').html(html);
				
				// Check to see if we have more items than we can show at once
				if (total > max)
				{
					// Hide all of the item <li>s
					$('#find-school-list li').hide();
					
					// Show only the current five items
					$('#find-school-list li').slice(start, (start + (max - 1))).show();
					
					// Append the paging controls
					$('#find-school-list').append(this.generatePagingHtml(total, start, max));
					
					// Bind a click event to the paging controls
					$('#find-school-paging a').click(
						function ()
						{
							GradeGuru.home.findSchool.parse(universities, $(this).attr('rel'));
							return false;
						}
					);
				}
				
				// Truncate any school names that are too long
				$('#find-school-list li strong').truncate({max_length: 45});
				
				// Finally show the updated list
				$('#find-school-list').show();
			}
			else
			{
				$('#find-school-list').hide();
				
				// Set the correct noun to use
				if (GradeGuru.core.user.location === 'us')
				{
					noun = 'schools';
				}
				else if(GradeGuru.core.user.location === 'uk')
				{
					noun = 'universities';
				}
				
				
				// Show the "none found" text, if it's already showing,
				// just update the searched text. If not, create the <p> element
				if ($('#find-school-not-found').length !== 0)
				{
					$('#find-school-not-found').html('Sorry, no ' + noun + ' for <strong>"' + $('#find-school-input').val() + '"</strong>');
				}
				else
				{
					$('#find-your-school fieldset').append('<p id="find-school-not-found">Sorry, no ' + noun + ' found for <strong>"' + $('#find-school-input').val() + '"</strong></p>');
				}
			}
			
		},
		
		// Build prev/next controls for a set of data
		// @param INT total - The total number of items
		// @param INT start - The number of the item to start with
		// @param INT max   - The total number that should be displayed at a time
		// @return STRING   - The full html for the controls
		generatePagingHtml: function (total, start, max)
		{
			var controls = '',
				countLastDisplay = ((start + 1) + max - 2);
			
			// Do a quick check that the last item to display
			// is not greater than the total items
			if (countLastDisplay > total)
			{
				countLastDisplay = total;
			}
			
			// Build the prev page control
			if (start > 0)
			{
				controls += "<a rel='" + (start - (max - 1)) + "'>prev</a>";
			}

			// Build the next page control
			if (total > ((start + 1) + max - 2))
			{
				controls += "<a rel='" + (start + (max - 1)) + "'>next</a>";
			}
			
			return "<li id='find-school-paging'>Displaying " + (start + 1) + "-" +  countLastDisplay + " of " + total + controls + "</li>";			
		},
		
		// Clear any user input and reset the list
		reset: function ()
		{
			$("#find-school-input").trigger("filterlist.clear");
		}
	}
};

$(document).ready(function () {
	
	// We don't want this just running everywhere,
	// so check for the correct id.
	if ($('#home').length !== 0)
	{
		GradeGuru.home.init();
	}
});