//<![CDATA[

/** 
*
* @package Jumz
* @version v2.0, index.js - "Prasand J." - cyrano423[at]hotmail.com
* @copyright (c) 2011 In.Alias, Inc.
* @license Non-distributable / Proprietary
*
*/

// define the global variables.
var audio='article.pages #audio',
    audio_links=audio+' ul.tracks li',
    audio_caption='article.pages h2',
    audio_player=false,
    body_object='body',
    posts='section article',
    thumb='article.pages #videos',
    thumb_iframe=false,
    thumb_links=thumb+' li',
    thumb_player=false,
    video='#media',
    video_caption=video+' figcaption',
    video_iframes=false,
    video_links=video+' a',
    video_links_thumbnails=video+' a[href!="'+video+'"]',
    video_player=video+' iframe',
    video_player_last=video_player+':last',
    video_player_list=[];

// function that is launched when the youtube API loads.
jQuery.api_loaded=function(){
	// grab all of the youtube videos on the page, and process them.
	$(video_player+'[src*="youtube"]').each(function(){
		// initialize the youtube functions for this video.
		// video_player_list[$(this).attr('id')]=new YT.Player($(this).attr('id'),{ events:{ 'onStateChange':jQuery.fn.player_state }});
	});
	// exit this function.
	return true;
};

// function to correct the syndicated feeds display.
jQuery.correct_imported_posts=function(){
	// delete the unncessary information from the post.
	$(posts+' div.feedflare, '+
	  posts+' div.PDS_Poll, '+
	  posts+' p:empty, '+
	  posts+' img[src*="feedburner"], '+
	  posts+' noscript, '+
	  posts+' script').empty().remove();
	// remove any CSS set by the original website.
	$(posts+' div, '+
	  posts+' embed, '+
	  posts+' object, '+
	  posts+' img').removeAttr('style').removeAttr('class');
	// find all media players.
	$(posts+' embed, '+posts+' object').each(function(){
		// get the current player's height.
		var this_object=$(this), height=this_object.attr('height');
		// if the height is 81 pixels, then it's a soundcloud player.
		if (height==81) this_object.addClass('h81');
		// if the height is 24 pixels, then it's a generic music player.
		else if (height==24) this_object.addClass('h24');
		// exit this function.
		return this;
	});
	// find all images / photos.
	$(posts+' img').each(function(){
		// get the current photo's height, and address.
		var this_object=$(this), height=this_object.attr('height'), address=this_object.attr('src');
		// if this is a complex magazine photo.
		if (address.indexOf('complex.com')>-1){
			// if the image dimensions exist, remove them.
			if (this.src.indexOf('310x205/')>-1) this_object.attr('src',this.src.replace(/\/310x205/g,''));
			// otherwise let the image set it's own size.
			else this_object.addClass('hauto');
			// center the image because it might be small.
			this_object.parent().addClass('center');
		}
		// otherwise, if the photo is within thumbnail height range.
		if (height>90&&height<160){
			// get the image's parent.
			var this_parent=this_object.parent(), that_parent=this_parent.parent();
			// add the thumbnail CSS.
			this_object.addClass('h130');
			// if the parent is a link, add the thumbnail class.
			if (this_parent.is('a')) this_parent.removeAttr('class').addClass('thumbnail');
			// find the p tag.
			that_parent=(this_parent.is('p'))?this_parent:(that_parent.is('p')?that_parent:false);
			// if the p tag was found, set the class.
			if (that_parent&&!that_parent.hasClass('center')) that_parent.removeAttr('class').addClass('center');
		}
		// exit this function.
		return this;
	});
	// re-center any items which were uncentered but should've been.
	$(posts+' .center').removeAttr('style').addClass('center');
	// exit this function.
	return true;
};

// function to fade the song info and arrows that overlay the video.
jQuery.fade_overlay=function(visibility){
	// exit this function.
	return this;
};

// function to get the variables from a string.
String.prototype.parse_string=function(){
	// create an array to store the variables.
	var variables=[];
	// find the variable sections, and store them.
	this.substring(1).replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function($0,$1,$2){ if ($1) variables[$1]=$2; });
	// return the variables.
	return variables;
};

// function to pause the currently playing video.
jQuery.fn.player_pause=function(){
	// exit this function.
	return this;
};

// function to fire when the video's state changes (to know when to fade the overlay).
jQuery.fn.player_state=function(event){
	// get the object's source.
	var source=$(this).attr('src');
	alert(event);
	// exit this function.
	return this;
};

// function to switch the current audio.
jQuery.switch_audio=function(link){
	// if the link is not provided.
	if (!link){
		// get the track list.
		var tracks=document.getElementById('audio').getElementsByTagName('li');
		// loop through the tracks, until we find an unplayed track.
		for (var i=-1,count=tracks.length,check;++i<count;) if ((check=tracks[i].className.indexOf('played')<0)) break;
		// use the unplayed track found.
		link=tracks[i].firstChild;
	}
	// get the current link's parent node.
	var parent=$(link).parent();
	// if the item clicked was not already selected.
	if (!parent.hasClass('current')){
		// hide the previously selected item, move it to the end of the list, then unhide it.
		$(audio_links+'.current').hide('slow',function(){ $(this).parent().append($(this).removeClass('current').show(300)); return true; });
		// mark the current item as selected.
		parent.addClass('current');
		// change the audio caption.
		$(audio_caption).html($(link).html());
	}
	// if the audio player was initalized.
	if (audio_player){
		// if the song was never played.
		if (!audio_player.played){
			// play the song.
			audio_player.api_play();
			// mark the song as played.
			audio_player.played=true;
		}
		// load the next track.
		audio_player.api_load(link.href);
	}
	// exit this function.
	return true;
};

// function to switch the status of the playing media.
jQuery.switch_status=function(){
	// find the current track.
	var current_track=$(audio_links+':contains("'+($(audio_caption).html())+'")');
	// if the current track has not been marked as played, yet, do so.
	if (!current_track.hasClass('played')) current_track.addClass('played');
	// if all of the songs have been played.
	if ($(audio_links+'.played').length==$(audio_links).length){
		// remove all of the links' play status.
		$(audio_links).removeClass('played');
		// mark the current track as played.
		current_track.addClass('played');
	}
	// exit this function.
	return true;
};

// function to switch the current video thumbnail.
jQuery.switch_thumb=function(link){
	// if the current item is already selected, exit.
	if ($(link).parent().hasClass('current')) return true;
	// function to activate the current video.
	function initialize_video(link){
		// if the hover effects were already disabled, re-enable them.
		if ($(thumb_links+' a').hasClass('nohover').length) $(thumb_links+' a').removeClass('nohover');
		// disable all hover effects.
		$(thumb_links+' a').addClass('nohover');
		// correctly align the parent item.
		if ($(link).parent().position().left>750) $(link).parent().addClass('right');
		// move the current video into position.
		$(link).css('display','none').parent().removeClass('fade').animate({ width:'466px',height:'325px' },'slow',function(){
			// mark this item as current, and load the iframe.
			$(this).addClass('current').removeAttr('style').append(thumb_iframe);
			// unhide the iframe, and change its address.
			$(thumb_iframe).attr('src',link.address).fadeIn('slow');
			// enable the thumbnail hover effects.
			$(thumb_links+' a').removeClass('nohover');
			// always return something;
			return true;
		});
		// exit this function.
		return true;
	};
	// if there is a previous video.
	if ($(thumb_links+'.current').length){
		// disable the hover effects.
		$(thumb_links+' a').addClass('nohover');
		// hide the iframe.
		$(thumb_iframe).fadeOut('slow',function(){
			// reset the iframe source.
			$(this).removeAttr('src');
			// move the current video to it's original position.
			$(thumb_links+'.current').animate({ width:'142px',height:'95px' },'slow',function(){
				// if this track hasn't already been played, mark it as played.
				if (!$(this).hasClass('played')) $(this).addClass('played');
				// remove this float, and show the thumnail.
				$(this).removeClass('current').removeClass('right').removeAttr('style').children('a').fadeIn('slow').removeAttr('style');
				// slide the new video into position.
				initialize_video(link);
				// always return something;
				return true;
			});
		});
	}
	// move the current video into position.
	else initialize_video(link);
	// exit this function.
	return true;
};

// function to switch the current video.
jQuery.switch_video=function(link){
	// store the song title and iframe ID.
	var song=link.song, iframe=link.iframe;
	// if the song doesn't exist, the arrow navigation was clicked.
	if (!song){
		// store the iframe positions, and number of videos.
		var positions=[], videos=$(video_links_thumbnails).length;
		// get the iframe positions, and update the storage.
		$(video_player).each(function(index){ positions.push($(this).position().left); return true; });
		// find the item currently visible.
		positions=jQuery.inArray(0,positions);
		// get the item that's next in the list.
		positions=($(link).hasClass('prev'))?(positions-1<0?videos-1:positions-1):(positions+1>videos-1?0:positions+1);
		// now we can grab the song title and iframe ID.
		link=$(video_links_thumbnails)[positions]; song=link.song; iframe=link.iframe;
	}
	// slide out the caption, change it, then slide it back in.
	$(video_caption).slideToggle('fast',function(){ $(this).html(song).slideToggle('slow'); return true; });
	// the iframe to be displayed's position.
	var position=$('#'+iframe).position().left;
	// based on the position, set the direction of the slide.
	var direction=(position<0)?'+':'-';
	// process all of the videos displaying.
	$(video_player).each(function(index){
		// stop any previous animations, store the current position, and check if the item clicked is already displayed.
		var this_object=$(this), position=this_object.stop().position().left, item=(iframe==this_object.attr('id'));
		// since we stopped the animation mid-cycle, correct any positions which are out of place.
		if (position>0&&position<940){ this_object.css('left','0px'); position=0; }
		else if (position>940){ this_object.css('left','940px'); position=940; }
		else if (position<-940){ this_object.css('left','-940px'); position=-940; }
		// if this current video is visible, move it out of view, or if it's the video selected slide into view.
		if (!position&&!item||position&&item) this_object.animate({ left:direction+'=940px' },'slow').player_pause();
		// exit this process.
		return true;
	});
	// deselect all of the video navigation bar links.
	$(video_links_thumbnails).removeClass('current');
	// select the clicked link, transitioning it as necessary.
	$(link).addClass('hover').delay(350).queue(function(){ $(this).addClass('current').delay(350).
		queue(function(){ $(this).removeClass('hover').dequeue(); return true; }).dequeue(); return true;
	});
	// exit this function.
	return true;
};

// function to preload specific images.
jQuery.fn.preload_images=function(){
	// loop through the arguments supplied and load each.
	for (var i=-1,count=arguments.length;++i<count;) jQuery('<img>').attr('src',arguments[i]);
	// exit this function.
	return this;
};

// operations to be triggered after the page loads.
jQuery(function($){
	// set the jquery animation speed.
	jQuery.fx.interval=70;
	// delete the excess data from syndicated posts.
	jQuery.correct_imported_posts();
	// if the video player exists, initialize it.
	if ($(video).length){
		// activate the video player controls, and disble the default action.
		$(video_links).click(function(event){ event.preventDefault(); jQuery.switch_video(this); return false; });
		// process the video player thumbnail navigation links.
		$(video_links_thumbnails).each(function(index){	
			// store this link's address.
			this.address=$(this).attr('href');
			// create an iframe ID for this link.
			this.iframe='video_'+Math.floor(Math.random()*1000);
			// grab the song name of this link.
			this.song=$(this).html();
			// if the song name contains html tags, remove them.
			if (this.song.indexOf('<')>-1) this.song=this.song.substring(0,this.song.indexOf('<'));
			// create a new iframe for this link, using the link's iframe ID.
			if (index) $(video_player_last).after('<iframe class="offset" id="'+this.iframe+'" name="'+this.iframe+'" src="'+this.address+'" seamless="seamless">'+this.song+'</iframe>');
			else $(video_player_last).attr({ id:this.iframe, name:this.iframe });
			// exit this function.
			return this;
		});
		// create an alias for the youtube api to fire.
		var onYouTubePlayerAPIReady=jQuery.api_loaded;
		// load the youtube video player api.
		$('head script:first').before($(document.createElement('script')).attr({ src:'http://www.youtube.com/player_api', type:'text/javascript' }));
	}
	// if the audio player exists.
	if ($(audio_links+' a').length){
		// activate the audio player controls, and disble the default action
		$(audio_links+' a').click(function(event){ event.preventDefault(); jQuery.switch_audio(this); return false; });
		// load the soundcloud api.
		$('head script:first').before($(document.createElement('script')).attr({ src:'blog/wp-content/themes/jumz/soundcloud.js', type:'text/javascript' }));
		// initialize the soundcloud options.
		soundcloud.addEventListener('onPlayerReady',function(player,data){ if (!audio_player){ player.api_setVolume(100); player.played=false; audio_player=player; return true; }});
		// initialize the track memory.
		soundcloud.addEventListener('onMediaPlay',function(player,data){ jQuery.switch_status(); return true; });
		// initialize continuous play.
		soundcloud.addEventListener('onMediaEnd',function(player,data){ jQuery.switch_audio(false); return true; });
	}
	// if the thumb player exists.
	if ($(thumb_links+' a').length){
		// activate the thumb player controls, and disble the default action
		$(thumb_links+' a').click(function(event){ event.preventDefault(); jQuery.switch_thumb(this); return false; });
		// process each of the thumbnails.
		$(thumb_links+' a').each(function(index){
			// function to replace the thumbnail contents.
			function build_thumbnail(link){
				// replace the thumbnail contents.
				$(link).html('<span>'+($(link).html())+'</span><img src="'+(link.thumbs[0])+'" />');
				// fade the parent object.
				$(link).parent().addClass('fade');
				// always return something.
				return true;
			}
			// set the type of video, and the video id.
			var type=(this.href.indexOf('vimeo')>-1)?1:0,video_id=false;
			// if there is a query string, try to grab the video ID.
			if (this.search&&this.search.indexOf('v=')>-1) video_id=this.search.parse_string()['v'];
			// if the video ID isn't set, get it from the link's pathname.
			if (!video_id) video_id=this.pathname.substring(this.pathname.lastIndexOf('/')+1);
			// if this is a youtube video.
			if (!type){
				// build the iframe address.
				this.address='http://www.youtube.com/embed/'+video_id+'?controls=1&autohide=1&fs=1&egm=1&rel=0&showinfo=0&wmode=transparent&autoplay=1';
				// set the thumbnail array.
				this.thumbs=['http://img.youtube.com/vi/'+video_id+'/0.jpg','http://img.youtube.com/vi/'+video_id+'/1.jpg',
					'http://img.youtube.com/vi/'+video_id+'/2.jpg','http://img.youtube.com/vi/'+video_id+'/3.jpg'
				];
				// build the thumbnail.
				build_thumbnail(this);
			}
			// if this is a vimeo video.
			else {
				// build the iframe address.
				this.address='http://player.vimeo.com/video/'+video_id+'?byline=0&color=dd0000&title=0&portrait=0&autoplay=1';
				// create storage for the thumbnail.
				var vimeo=this; vimeo.thumbs=[];
				// get the thumbnail, and add it to the storage.
				$.ajax({
					url:'http://vimeo.com/api/v2/video/'+video_id+'.json',
					type:'GET',
					dataType:'jsonp',
					async:false,
					success:function(data){
						// store the image.
						vimeo.thumbs[0]=data[0].thumbnail_medium;
						// build the thumbnail.
						build_thumbnail(vimeo);
						// always return something.
						return true;
					}
				});
			}
		});
		// create the thumb iframe.
		thumb_iframe=document.createElement('iframe');
		// set the iframe ID.
		thumb_iframe.setAttribute('id','video');
	}
	// when everything else loads.
	$(window).load(function(){
		// there's nothing to do yet, everything else is done already.
	});
	// exit these operations.
	return true;
});

//]]>
