//.unique function
Array.prototype.unique =
  function() {
    var a = [];
    var l = this.length;
    for(var i=0; i<l; i++) {
      for(var j=i+1; j<l; j++) {
        // If this[i] is found later in the array
        if (this[i] === this[j])
          j = ++i;
      }
      a.push(this[i]);
    }
    return a;
  };

function loadVideo(playerUrl, autoplay, watchUrl, watchTitle) {
		/*
		swfobject.embedSWF(
				  playerUrl + '&rel=1&border=0&fs=1&autoplay=' + 
				  (autoplay?1:0), 'player', '620', '379', '9.0.0', false, 
				  false, {allowfullscreen: 'true', wmode: 'transparent'});
		*/
		
		$('#playerContainer').empty().html(function(){
				var ytVideoId = playerUrl.substr(25, 11);
				if (autoplay == true){
					var play = '&amp;autoplay=1';
				} else {
					var play = '';
				}
				 
				var ytVideo = $('<iframe></iframe>').attr({
												width: 620,
												height: 379,
												title: 'YouTube Video Player',
												frameborder: 0,
												src: 'http://www.youtube.com/embed/' + ytVideoId + '?version=3&amp;rel=0&amp;hd=1&amp;theme=dark&amp;color=red&amp;modestbranding=1' + play
											});
				return ytVideo;
		});
		
		
		//setup sharing icons
		$('#vidFaceShare').attr('href', 'http://www.facebook.com/sharer.php?u=' + encodeURIComponent(watchUrl) + '&t=' + encodeURIComponent(watchTitle));
		$('#vidEmailShare').attr('href', 'mailto: ?body=I saw this video on the Message Trust website www.message.org.uk and thought you might like it: ' + encodeURIComponent(watchUrl) + '&subject=Video from the Message Trust: ' + watchTitle);
		$('#vidTwitterShare').attr('href', 'http://twitter.com/share?text=I am loving this video I found on the Message Trust website www.message.org.uk &url=' + encodeURIComponent(watchUrl));
}
//advertslider
function slideleftright(){
	$('#advertsSlider').delay(4000).animate({left: '-310px'}, 1000, function(){
		$(this).delay(4000).animate({left: '0'}, 1000, function(){
			slideleftright();
		});	
	});
	
}

//get youtube videos by Ajax call
function ytGetVideos(){
	//put loading in place
	$('#playerContainer').css('background','url(/Message/wp-content/themes/messagev3/images/loading.gif) top center no-repeat');
	//start query
	var baseURL = 'http://gdata.youtube.com/feeds/api/users/messagetrust/uploads?v=2&alt=jsonc&max-results=24&callback=?';
	$.getJSON(baseURL, function(response){
		$.each(response.data.items, function(i, item){
			//setup variables for each entry
			var title = item.title;
			var thumb = item.thumbnail.sqDefault;
			var playerUrl = item.content['5'];
			var watchUrl = item.player['default'];
			var ytDate = item.uploaded; var date = Date.parse(ytDate);
			//create a for each entry
			$('<a></a>')
			.hide()
			.attr('href','#')
			.addClass('ytVideoThumb')
			.html('<img src="' + thumb +'" /><span class="titlec">' + title.toLowerCase() +'</span><span class="date">' + date.toString('d MMM yyyy') + '</span>')
			.appendTo('#videos')
			.fadeIn()
			.click(function(){
				loadVideo(playerUrl, true, watchUrl, title);
				return false;
			});
		});
		//get first video and play it
		var first = response.data.items[0];
		loadVideo(first.content['5'], false, first.player['default'], first.title);
		$("a.ytVideoThumb:nth-child(8n-7)").each(function(){
				$(this).nextAll("a.ytVideoThumb:lt(7)").andSelf().wrapAll("<div></div>");
		});
	});
	
}


/////////////////////////////////////////////////////////////////////////
// On events page set the tags, create filter button and istope it up! //
/////////////////////////////////////////////////////////////////////////
function tagsAndIsotope() {
		//set the month as the class
		$('div.eventItem').each(function(){
			var monthTag = $(this).find('p strong').html().split(" ");
			$(this).addClass(monthTag[0]);
		});

		//get the tags from the event class
		/*
				$('div.eventItem').each(function(){
					var tagstring = $(this).attr('title');
					var tagstring = tagstring
					  .replace(/[^,]\s/g, function (a) {
					    return a[0] + '-';
					  })
					  .replace(/,\s/g, ' ');
					$(this).addClass(tagstring);
					
				});
		*/
		
		//create filter links from tags 
		//make an array of all the various div classes of eventItems  
		var tags = [];
		$('div.eventItem').each(function(){
			tags.push(this.className);
		});
		var tags = tags.join(' ').split(' ');//join all of the various arrays into one string and then split them again so we get each class as an individual element in the array
		tags = tags.unique();//delete duplicates using the unique function above

		//output a filter link for each of the unique tags
		$(tags).each(function(i){
			var title = tags[i].replace(/-/g,' ').toLowerCase();
			$('li a[data-filter="*"]').before('<li class="filter"><a href="#" data-filter=".' + tags[i] + '">' + title + '</a></li>');
		});
		
		//remove eventItem and isotope-item links
		$('ul#filters a[data-filter=".eventItem"]').parent().hide();
		$('ul#filters a[data-filter=".isotope-item"]').parent().hide();
		
		//isotope up that eventsContainer
		$('#eventsContainer, #products').isotope({
			itemSelector: '.eventItem',
			layoutMode: 'masonry',
			animationEngine: 'best-available'
		});
		
		//filter the isotope boxes with the filter links
		var hash = window.location.hash;
		hash = hash.substr(1);
		if (hash) {
			$('#eventsContainer').delay(800).isotope({ filter: '.' + hash });
		}
		
		$('#filters a').click(function(){
		  var selector = $(this).attr('data-filter');
		  $('#eventsContainer').isotope({ filter: selector });
		  return false;
		});
}

/////////////////////////////////////////////////////////////////////////
// On shop filter by section!                                          //
/////////////////////////////////////////////////////////////////////////

function shopIsotope() {
	$('#products').isotope({
		itemSelector: '.product',
		layoutMode: 'fitRows',
		animationEngine: 'best-available'
	});
	var hash = location.hash.substring(1);
	if (hash){
		$('#products').isotope({filter: '.' + hash });
		$('#shopNav a').parent('.current').removeClass('current');
		$('#shopNav a[data-filter=".' + hash + '"]').parent().addClass('current');
	}
	$('#shopNav a').click(function(){
		var selector = $(this).attr('data-filter');
		$('#products').isotope({filter: selector });
		$('#shopNav a').parent('.current').removeClass('current');
		$(this).parent().addClass('current');	
		return false;
	});
}
