// Sliding headings
$(document).ready(function(){
	$("#tweets").tweet({
	avatar_size: 32,
	count: 2,
	username: "ScottMorrisonMP",
	template: "{text} &ndash; {time}"
	});
});


jQuery(document).ready( function() {               
	var isSliding = false;
	jQuery(".pointplan h3").click(function() {
		if (isSliding == false) {
			isSliding = true;
			jQuery(this).next().slideToggle("normal", function() {
				isSliding = false;
			});          
		} 
	});
	var anchor = (window.location.toString()).replace(/^.*#([a-z]+)$/, '$1');
	if (anchor != "") {
		jQuery('.pointplan h3:has(a[name=' + anchor + '])').click();
	}
});


function getFileName(place) {
var url = place,
i = url.lastIndexOf('/') + 1,
j = url.indexOf('#', i),
k = url.indexOf('?', i);

if(-1 == j) {j = url.length;}
if(-1 == k) {k = url.length;}

return url.substring(i, Math.min(j, k));
}

// Greg's sidenav attempt 1
jQuery(document).ready( function() {
   var myurl = getFileName(document.URL);
   jQuery('#backnav a').each( function(i) {
	    var itemhref = jQuery(this).attr("href");
		var convertedhref = getFileName(itemhref);
		if (convertedhref == myurl) {
			jQuery(this).addClass("active");
		}
	});
});


jQuery(function(){
	jQuery('#nav ul').superfish();
});


jQuery(function() {
	jQuery(".s-home .preview a").innerfade({
		speed: 750,
		timeout: 3000,
		containerheight: "139px"
	});
});



jQuery(function() {
	jQuery("#backnav .searchbox input").focus(function(){
		jQuery("#backnav .searchbox a").addClass("focus");
		jQuery(this).addClass("focus");
	});
	jQuery("#backnav .searchbox input").blur(function() {
		jQuery("#backnav .searchbox a").removeClass("focus");
		jQuery(this).removeClass("focus");
	});

	
	jQuery("#search .searchbox input").focus(function(){
		jQuery("#search .searchbox a").addClass("focus");
		jQuery(this).addClass("focus");
	});
	jQuery("#search .searchbox input").blur(function() {
		jQuery("#search .searchbox a").removeClass("focus");
		jQuery(this).removeClass("focus");
	});
});


jQuery(document).ready(function() {
	jQuery('form[name*=search]').submit(function() {
		var query = jQuery.trim(jQuery('input[name=q]', this).val());
		if (query == 'Search' || query == '')
			return false;
	});
});


jQuery(function(){
	
	jQuery('#photo .photo-quotes div').innerfade({ containerheight: 112 });
	
	
	jQuery('#partners').anythingSlider({
		easing: "swing",                // Anything other than "linear" or "swing" requires the easing plugin
		autoPlay: false,                 // This turns off the entire FUNCTIONALY, not just if it starts running or not
		startStopped: true,            // If autoPlay is on, this can force it to start stopped
		delay: 3000,                    // How long between slide transitions in AutoPlay mode
		animationTime: 600,             // How long the slide transition takes
		hashTags: false,                // Should links change the hashtag in the URL?
		buildNavigation: false,          // If true, builds and list of anchor links to link to each slide
		pauseOnHover: true,             // If true, and autoPlay is enabled, the show will pause on hover
		startText: "Start",             // Start text
		stopText: "Stop",               // Stop text
		navigationFormatter: null       // Details at the top of the file on this use (advanced use)
	});
	
	jQuery('#flickr').html("<ul></ul>");
	jQuery('#flickr ul').jflickrfeed({
		limit: 6,
		qstrings: {
			id: '44923402@N04'
		},
		itemTemplate: 
			'<li>' +
			'<a href="{{image_b}}"><img src="{{image_s}}" alt="{{title}}" width="80" height="80" /></a>' +
			'</li>',
		itemCallback: function(){
			$(this).find("li:nth-child(3n)").addClass("last");
		}
	});
	
  
});


/*	
 * YOUTUBE VIDEOS
 * =====================
 * 
 */

// Loads the selected video into the player.

function loadVideo(id) {
	if(ytplayer) {
		ytplayer.loadVideoById(id);
	}
}


// YouTube error handling

function onPlayerError(errorCode) {
	alert("An error occured of type:" + errorCode);
}


// This function is automatically called by the player once it loads

function onYouTubePlayerReady(playerId) {
	ytplayer = document.getElementById("ytPlayer");
	ytplayer.addEventListener("onError", "onPlayerError");
}


// Generate the video player and insert into the DOM.

function loadPlayer() {
	// Details of the default video, get this from the first thumbnail generated via API
	var	videoItem 	= jQuery("#youtube-feed").find("a:first-child"),
			videoID		= videoItem.attr("id"),
			videoTitle	= videoItem.attr("title");
	// Lets Flash from another domain call JavaScript
	var params = { allowScriptAccess: "always" };			
	// The element id of the Flash embed
	var atts = { id: "ytPlayer" };
	// Embed player using SWFObject
	swfobject.embedSWF("http://www.youtube.com/v/" + videoID + "&enablejsapi=1&playerapiid=player1&fs=1&rel=0", "youtube-player", "347", "257", "8", null, null, params, atts);
	jQuery("#youtubebox h2").text(videoTitle);

}
	
	
jQuery(function(){

	// Generate YouTube thumbnails/links from API
		
	var username = "ScottMorrisonMP";
	jQuery.getJSON("http://gdata.youtube.com/feeds/users/"+username+"/uploads?alt=json-in-script&callback=?&max-results=3", 
	function(data){
		jQuery("#youtube-feed").html("<ul></ul>");
		jQuery.each(data.feed.entry, function(i, item){
			var	id 		= item['id']['$t'],
					title 	= item['title']['$t'],
					views    = item['yt$statistics']['viewCount'],
					published = item['published']['$t'],
					listHtml;
			id = id.replace("http://gdata.youtube.com/feeds/videos/",""); // We only need the ID, the JSON data returns a complete URL.
			
			listHtml =  '<li>' +
								'<a href="http://www.youtube.com/watch?v='+id+'" id="'+id+'" title="'+title+'">' +
									'<img src="http://i2.ytimg.com/vi/'+id+'/default.jpg" height="60">' +
									'<strong>'+title+'</strong> ' +
									'<span>'+views+' views</span>' +
								'</a>' +
							'</li>';
						
			jQuery("#youtube-feed ul")
				.append(listHtml);
		});
		loadPlayer(); // Abra cadabra!
	}); 
	
	
	// Override thumbnails linking to YouTube.
	
	jQuery("#youtube-feed").find("a").live("click",function(){
		var	id = $(this).attr("id"),
				title = $(this).attr("title");
		loadVideo(id); // Load the video into the player
		jQuery
		return false; // Prevent clickthrough
	});

});
