

var divScripts;
var videoIDSend;
var playersCount = 0;
var divResponse;
function checkYoutubeLink ()
{
	button = $(this);
	savedButtonForBinding = button;
	
	var value = attachWorks.find('.inputAttach').val();
	
	if (!/^https?:\/\//i.test(value))
	{
		value = 'http://' + value;
	}
	
	/***     Good check for whether it's a youtube link. Need to add "http://" if it doesn't exist      ***/
	var matches = value.match(/https?:\/\/(?:[a-zA_Z]{2,3}.)?(?:youtube\.com\/watch\?)((?:[\w\d\-\_\=]+&amp;(?:amp;)?)*v(?:&lt;[A-Z]+&gt;)?=([0-9a-zA-Z\-\_]+))/i);
	//var matches = value.match(/watch\?v=([a-zA-Z0-9\-_]+)/);	
	if (matches)
	{
		var videoID = value.split('v=')[1];
		var ampersandPosition = videoID.indexOf('&');
		if(ampersandPosition != -1)
		{
			videoID = videoID.substring(0, ampersandPosition);			
		}
		videoIDSend = videoID;
		divScripts = $('#divScripts');
		queryScript = '<script type="text/javascript" src="http://gdata.youtube.com/feeds/api/videos?q='+videoID+'&alt=json-in-script&callback=checking&format=5"></script>'; //&format=5  ||  invalid:FURd2SfS3yk, valid: rUtglloFnDQ  
		divScripts.append(queryScript);
		
		var inputDiv = attachWorks.find('.divInputAttach');
		var loading = $('#templates  .squareLoading').clone(true);
		loading.addClass('loadingCloned');
		loading.css('display','inline');
		loading.css('margin','0px');
		inputDiv.append(loading);
		button.unbind();
	}
	else
	{
		messageSpan = attachWorks.find('.newTagError');
		messageSpan.html('not a valid link');
		messageSpan.show();
		messageSpan.fadeOut(4000);
	}	
}

function checking (data)
{
	$('.loadingCloned').remove();
	var feed = data.feed;
	var entries = feed.entry || [];
	if(entries.length>0)
	{
		var entry = entries[0];
		var attachmentType = 'video';
		var attachmentLink = entry.media$group.media$content[0].url;
		var attachmentThumb = entry.media$group.media$thumbnail[0].url;
		var attachmentTitle = entry.title.$t;
		var responseArray = new Array ('valid',attachmentTitle,attachmentThumb,attachmentLink,attachmentType,'no error');
		addAttachmentYoutube (responseArray);
		
	}
	else
	{
		var responseArray = new Array ('invalid','','','','','video not found');
		addAttachmentYoutube (responseArray);
	}
}

function addAttachmentYoutube (response)
{
	var array = response;
	var valid = array[0];
	var title = array[1];
	var thumbnail = array[2];
	var link = array[3];
	var type = array[4];
	var errorMessage = array[5];
	var divAttachments = attachWorks.parents('.composePost').find('.divAttachments');
	if (valid == 'valid')
	{
		
		var pAttachment = $('#templates > .pAttachment').clone(true);
		var spanType = pAttachment.find('.spanAttachmentType');
		var spanText = pAttachment.find('.spanAttachmentText');
		var checkbox = pAttachment.find('.checkboxAttachment');
		spanType.text(type);
		spanText.text(title);
		checkbox.attr('attachmentlink',link);
		checkbox.attr('attachmenttype',type);
		checkbox.attr('attachmentthumb',thumbnail);
		checkbox.attr('attachmenttitle',title);
		divAttachments.append(pAttachment);
		if (type != "imageSrc")
		{
			attachWorks.hide();
		}
	}
	else
	{
		messageSpan = attachWorks.find('.newTagError');
		messageSpan.html(errorMessage);
		messageSpan.show();
		messageSpan.fadeOut(4000);
		
		savedButtonForBinding.click(checkYoutubeLink);
	}
}

function searchTube (btn)
{
	button = $(btn);
	input = popupWrapper.find('.youtubeInput');
	divResponse = popupWrapper.find('.divResponse');
	var searchTerm = input.val();
	usto = searchTerm;
	usio = 1;
	var queryScript = '<script type="text/javascript" src="http://gdata.youtube.com/feeds/api/videos?q='+searchTerm+'&alt=json-in-script&callback=showVideoSearchResults&max-results=6&format=5"></script>' //  &start-index=26

	divScripts = $('#divScripts');
	divScripts.append(queryScript);
	
	var loading = $('#templates  .squareLoading').clone(true);
	loading.addClass('loadingClone');
	divResponse.append(loading);
}
var usto;
var usio;

function youtubeFlipPage ()
{
	var arrow = $(this);
	divResponse = popupWrapper.find('.divResponse');
	var si = parseInt(arrow.attr('startindex'));
	if (si > 0)
	{		
		var queryScript = '<script type="text/javascript" src="http://gdata.youtube.com/feeds/api/videos?q='+usto+'&alt=json-in-script&callback=showVideoSearchResults&max-results=6&format=5&start-index='+si+'"></script>' //  &start-index=26
		divScripts = $('#divScripts');
		divScripts.append(queryScript);
		usio = si;
		var loading = $('#templates  .squareLoading').clone(true);
		loading.addClass('loadingClone');
		divResponse.prepend(loading);
	}
}

function showVideoSearchResults (data)
{
	$('.loadingClone').remove();
	var feed = data.feed;
	var entries = feed.entry || [];
	divResponse.find('.divVideoResult').remove();
	var el = entries.length;
	var cl;
	if (el >= 5) {cl = 5;} else {cl = el;}
	if(entries.length>0)
	{		
		for (var i = 0; i<cl; i++)
		{
			var entry = entries[i];
			var link = entries[i].media$group.media$content[0].url;
			var thumbnail = entries[i].media$group.media$thumbnail[0].url;
			var title = entry.title.$t;
			var type = 'video';
			divResult = $('#templates .divVideoResult').clone(true);			
			resultImage = divResult.find('.videoResultImage');
			spanTitle = divResult.find('.videoResultSpan');
			resultImage.attr('src',thumbnail);
			spanTitle.text(title);
			buttonPreview = divResult.find('.buttonPreview');
			buttonPreview.attr('previewlink',link);
			
			buttonAttach = divResult.find('.videoSearchAttachButton');
			buttonAttach.attr('attachmentLink',link);
			buttonAttach.attr('attachmentThumb',thumbnail);
			buttonAttach.attr('attachmentTitle',title);
			buttonAttach.click(attachVideoFromPopup);
			
			divResponse.append(divResult);			
		}
		arrows = $('.youtubeArrowsDiv');
		arrows.show();
		var previousArrow = arrows.find('.buttonPageArrowPrevious');
		var nextArrow = arrows.find('.buttonPageArrowNext');
		prevI = usio - 5;
		nextI = usio + 5;
		previousArrow.removeClass('youtubeArrowDis');
		nextArrow.removeClass('youtubeArrowDis');
		if (prevI < 0)
		{
			previousArrow.addClass('youtubeArrowDis');
		}
		previousArrow.attr('startindex',prevI);
		nextArrow.attr('startindex',nextI);
		previousArrow.unbind();
		nextArrow.unbind();
		previousArrow.click(youtubeFlipPage);
		if (el == 6)
		{
			nextArrow.click(youtubeFlipPage);
		} else {
			nextArrow.addClass('youtubeArrowDis');
		}
	}
	else
	{
		$('.youtubeArrowsDiv').hide();
		divResponse.append('<p class="noVideoResultsP">no results were found</p>');
	}
}

function attachVideoFromPopup ()
{
	var buttonAttach = $(this);
	var link = buttonAttach.attr('attachmentLink');
	var thumbnail = buttonAttach.attr('attachmentThumb');
	var title = buttonAttach.attr('attachmentTitle');
	var responseArray = new Array ('valid',title,thumbnail,link,'video','no error');
	addAttachmentYoutube (responseArray);
	closeVideoPopup();
}

function previewVideo (btn)
{
	var previewButton = $(btn);
	var div = previewButton.parents('.divVideoResult');
	var imageCell = div.find('.cellVideoResultImage');
	imageCell.empty();
	var id = "player"+playersCount;
	playersCount ++;
	imageCell.append('<object id="'+id+'"></object>');
	var url = previewButton.attr('previewlink');
	loadVideo(url,true,id,'290','250');
}

function openVideoAttachment ()
{
	var clickedItem = $(this);
	var thisPost = clickedItem.parents('.post');
	var row = clickedItem.parents('.rowVideoAttachmentItem');
	row.empty();
	var videoObjectCell = $('#templates .videoObjectCell').clone(true);
	var id = "player"+playersCount;
	playersCount ++;
	videoObjectCell.append('<object id="'+id+'"></object>');
	row.append(videoObjectCell);
	var url = clickedItem.attr('previewlink');
	var playWidth = '625';
	var playHeight = '398';
	if (thisPost.hasClass('replyPost'))
	{
		var playWidth = '555';
		var playHeight = '354';
		var lineWrap = thisPost.next();
		var theLine = lineWrap.find('.divReplyLine');
		var beHeight = theLine.height();
		var afHeight = beHeight + 354;
		var afHeightPX = afHeight + 'px';
		theLine.attr('style','height:'+afHeightPX+';');
	}
	loadVideo(url,true,id,playWidth,playHeight); //loadVideo(url,true,id,'650','414');
}

function loadVideo(playerUrl, autoplay, objectID, width, height) {
  swfobject.embedSWF(
	  playerUrl + '&rel=0&border=0&fs=1&autoplay=' + 
	  (autoplay?1:0), objectID, width, height, '9.0.0', false, 
	  false, {allowfullscreen: 'true',wmode:'opaque'});
}

function showMyVideos2(data) {
	var feed = data.feed;
	var entries = feed.entry || [];
	var html = ['<ul class="videos">'];
	for (var i = 0; i < entries.length; i++)
	{
	var entry = entries[i];
	var title = entry.title.$t.substr(0, 20);
	var thumbnailUrl = entries[i].media$group.media$thumbnail[0].url;
	var playerUrl = entries[i].media$group.media$content[0].url;
	html.push('<li onclick="loadVideo(\'', playerUrl, '\', true)">',
			  '<span class="titlec">', title, '...</span><br /><img src="', 
			  thumbnailUrl, '" width="130" height="97"/>', '</span></li>');
	}
	html.push('</ul><br style="clear: left;"/>');
	document.getElementById('videos2').innerHTML = html.join('');
	if (entries.length > 0)
	{
		loadVideo(entries[0].media$group.media$content[0].url, false);
	}
}
