// set the intiial value for facebook selected tab on social feeds on the bottom
feedID=1;

// set the easing to Penner's method ease in and out globally
jQuery.easing.def = "easeInOutExpo";

// set init thumbnail index to 0 as it is the first element on page load
thumbIndex=0;

// Prepare stuff on the page

$(function(){
	
	// limit some text stuff on the page to specific number of characters just in case guys entering stuff into CMS put too much content
	limitTextSizeInElement("#footer_featurette #happiertimes #description",240);
	limitTextSizeInElement("#videodata p",330);
	limitTextSizeInElement("#gamecolumn .row #contenttext_noicon",55);
	limitTextSizeInElement("#gamecolumn .row #contenttext_noicon2",55);
	
	// reset glass element on thumbnails the true value is to determine whether or not it's the initial page load so we can setup the glass on the latest video
	resetThumbnailGlass(true);
	
	// bind click event to thumbnail, check for clicked thumbnail index and compare it to the active thumbnail to know which is the new glass fade in and which is the old one that needs to fade out
	$('.thumbnail').click(function() {
 		var element=this;
		var newIndex=$('.thumbnail').index(element);
		if(newIndex===thumbIndex){
			return;
		}else{
			resetThumbnailGlass();
			thumbIndex=newIndex;
			showGlass($("#glass",this));
		}
	});
	
	
	// hide and position inactive social feeds
	$('#twitter_feedbox, #headlines_feedbox').css('left','450px');

	// initial bind
	$('#fbbttn').click(function() {
 		if(feedID===1){ return } else { socialfeedBttnClick(1, '#fbbttn', templatePath+'assets/social_facebookbttn_selected.png'); };
	});
	$('#twbttn').click(function() {
 		if(feedID===2){ return } else { socialfeedBttnClick(2, '#twbttn', templatePath+'assets/social_twitterbttn_selected.png'); };
	});
	$('#hdbttn').click(function() {
 		if(feedID===3){ return } else { socialfeedBttnClick(3, '#hdbttn', templatePath+'assets/social_headlinesbttn_selected.png'); };
	});
});

// reset the social feed box buttons to their original state
function resetButtons(){
	$('#fbbttn img').attr("src",templatePath+"assets/social_facebookbttn.png");
	$('#twbttn img').attr("src",templatePath+"assets/social_twitterbttn.png");
	$('#hdbttn img').attr("src",templatePath+"assets/social_headlinesbttn.png");
}

// reset glass overlay for thumbnails to hidden
function resetThumbnailGlass(isInit){
	$(".thumbnail #glass").each(function(index) {
		if(!isInit){
			
			if(thumbIndex===index){
				// fade out current thumbnail
				$(this).fadeOut(750);
			} else {
				$(this).css("display","none");
			}
			
		}else{
			if(thumbIndex===index){
				$(this).fadeIn(750);
			} else {
				$(this).css("display","none");
			}
		}
    });

}

// fade in the thumbnail glass on activate
function showGlass(target){
	$(target).fadeIn(750);
}

// execute click on social feed buttons
function socialfeedBttnClick(selectID, bttnID, imgSrc){
		resetButtons();
		$(bttnID+' img').attr("src",imgSrc);
		SlideToFeedbox(selectID);
		feedID=selectID;
}

// truncate the number of characters in a specific DOM element containing text
function limitTextSizeInElement(element, size){
	var string = $(element).text();
	var truncatedString = string.substr(0,size) + "...";
	$(element).text(truncatedString);
}

// FACEBOOK FEED
$(function(){
	
	// load Facebook wall information
	$('#facebook_feedbox #feed').fbWall({
	id:'divorcecourt',
	accessToken:'206158599425293|7461a02619d0140f00ca7c63.1-100002023558915|maaVooMGzQVbAjxRRYAsaZ3_2CQ',
	showGuestEntries:true,
	showComments:true,
	avatarAlternative:true,
	max:10,
	timeConversion:24
	});
	
});


// TWITTER FEED
$(function($){
	
		// load Twitter Feed
      $("#twitter_feedbox #feed").tweet({
        join_text: "auto",
        username: "divorcecourt",
        avatar_size: 48,
        count: 10,
        auto_join_text_default: "we said,",
        auto_join_text_ed: "we",
        auto_join_text_ing: "we were",
        auto_join_text_reply: "we replied",
        auto_join_text_url: "we were checking out",
        loading_text: "loading tweets..."
      });
    });

// run sliding animations for the social feed boxes and do a switcharoo
function SlideToFeedbox(box){
	
	var selectedFeed=identifyFeed(box);
	var currentFeed=identifyFeed(feedID);
	
	var $selectedFeedElement = $('#' + selectedFeed);
	var $currentFeedElement = $('#' + currentFeed);
	

	// animate the current feed out of the view
	$currentFeedElement.animate({
    left: '-400px',
  }, 500, function() {
    // Animation complete.
	// hide the feed when it's out of the view
  });
  	
	// reset the selected feed x position and visibility
	$selectedFeedElement.css('left','450px');


	// animate in the selected feed
	$selectedFeedElement.animate({
    left: '0px',
  }, 500, function() {
    // Animation complete.
  });
}

// Identify what Social Feed you want to be active by their ID and return element name holding the feed
function identifyFeed(activebox){
	var retval="";
	
	switch(activebox)
	{
	case 1:
	  retval="facebook_feedbox";
	  break;
	case 2:
	  retval="twitter_feedbox";
	  break;
	case 3:
	  retval="headlines_feedbox";
	  break;
	  
	default:
	  retval="facebook_feedbox";
	}
	return retval;
}


// Preloader images functions
function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('<img/>')[0].src = this;
    });
}

// preload images
preload([
    templatePath+'assets/social_facebookbttn_selected.png',
    templatePath+'assets/social_headlinesbttn_selected.png',
    templatePath+'assets/social_twitterbttn_selected.png',
	templatePath+'assets/social_facebookbttn.png'
]);

$(function($){
	
	
// populate video thumbnails with youtube thumbnails
	$('.thumbnail').each(function(index) {
		var imgPath=getScreen(getYTidOnly($('a', this).attr('href')));
		$('a #ytthumb',this).attr('src',imgPath);
  	});
	
// setup clicks when document loaded
	$('.thumbnail').click(function(event){
		
		/*
		prevent default a href behavior because we don't really
		need to go to youtube url and it's good for SEO to have
		the video link in a href in the page
		*/
		event.preventDefault();
		

		// youtube video example link: http://www.youtube.com/watch?v=u_RW2KTrDgQ
		
		var yturl=$('a',this).attr('href');
		var ytvidID=yturl.slice(31);
		LoadYTVideo(ytvidID);
		
		// replace the video info
		var title=$('p',this).text();
		var description=$('#youtube_description',this).text();
		$('#videodata span').html(title);
		$('#videodata p').html(description);
		
		if(sectionID==="home"){
		$('#happiertimes #leftname').html($('#hp_manshortname', this).text());
		$('#happiertimes #rightname').html($('#hp_womanshortname', this).text());
		$('#happiertimes #description').html($('#hp_shortdescription', this).text());
		$('#happiertimes #couple').attr("src",$('#hp_thumbnail', this).text());
		$('#happiertimes a').attr("href",$('#hp_pageurl', this).text());
		}
	});
});

// retrieve youtube screen
function getScreen( url, size )
{
  if(url === null){ return ""; }

  size = (size === null) ? "big" : size;
  var vid;
  var results;

  results = url.match("[\\?&]v=([^&#]*)");

  vid = ( results === null ) ? url : results[1];
/*
  if(size == "small"){
    return "http://img.youtube.com/vi/"+vid+"/2.jpg";
  }else {
    return "http://img.youtube.com/vi/"+vid+"/0.jpg";
  }
  */
  //alert(vid);
return "http://img.youtube.com/vi/"+vid+"/0.jpg";

}

function getYTidOnly(fullpath){
	return fullpath.slice(31);
}


/* Load YouTube Video based on ID without refreshing the page */ 
function LoadYTVideo(videoID){

	// write the new html string (iframe) into the video player container div
	var htmlStr='<iframe width="470" height="297" src="http://www.youtube.com/embed/'+videoID+'?autoplay=1&rel=0&hd=1&wmode=transparent&controls=1" frameborder="0" allowfullscreen></iframe>';


	$('#facebook_like').html('<iframe src="//www.facebook.com/plugins/like.php?app_id=224092647640469&amp;href=http://www.youtube.com/watch?v='+videoID+'&amp;send=false&amp;layout=standard&amp;width=65&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font=lucida+grande&amp;height=25" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:65px; height:25px;" allowTransparency="true"></iframe>');
	$('#twitter_like').html('<a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.youtube.com/watch?v='+videoID+'" data-text="Check out this Divorce Court case!" data-count="none" data-via="DivorceCourt">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>');
		
	// replace it now
    $('#player').html(htmlStr);
}

// Write out YouTube Information (about clip -views, duration etc)
function youtubeFeedCallback( data ) {
	document.writeln(data.entry[ "media$group" ][ "media$description" ].$t.replace( /\n/g, '<br/>' ));
}


