﻿var youtubeTargetControl;
var youtubeSearchPage = 0;
var youtubeMaxResult = 1;
var youtubeTotalResults;
var youtubeStartIndex=1;
var youtubeItemsPerPage;
var youtubeArtistControlId;
var youtubeTitleControlId;
var artist;
var title;

function vSearchInit() {
	var createNewItemElement = $('#createThemeForm');
	if (createNewItemElement.length == 1 && createNewItemElement.is(':visible'))
	{
		artist = $('#txtNewThemeWizardArtist');
		title = $('#txtNewThemeWizardTitle');
		queryString = $('#create_theme_txt_video_title').val() || '';
	}
	else {
		youtubeTargetControl = $('.vsTxtResult:input:first');
		artist = $('.vsArtist:input:first');
		title = $('.vsTitle:input:first');
		queryString = $('#txt_video_title').val() || '';
	}
	
	if (queryString == '') {
		if (artist != null && artist.val() != '')
			queryString = artist.val();
		if (title != null && title.val() != '')
			queryString = queryString + ' ' + title.val();
	}
		
    $(':input#QueryString', this).attr('value', queryString);
    youtubeSearchPage = 0;
    youtubeMaxResult = 3;
    youtubeSearch()
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

function youtubeSelect(url) {
	
	var theTitle = $('.youtubeSearchEmbedTitle').text();
	var match = theTitle.match(/([^-]*)\w*-\w*([^-(\[]*)\w*/);
	
	var theArtist = '';
	var theSong = theTitle;
	if (match != null && match.length >= 3) {
		theArtist = match[1];
		theSong = match[2];
	}
	
    vSearchDialogClose();
	
	var createNewItemElement = $('#createThemeForm');
	if (createNewItemElement.length == 1 && createNewItemElement.is(':visible'))
	{
		$("#create_theme_add_item").show();
		$("#create_theme_video_short_search").hide();
		$("#create_theme_txt_video_title").val(null);
		$("#txtNewThemeWizardTitle").val(theSong.trim());
		$("#txtNewThemeWizardArtist").val(theArtist.trim());
		$("#txtNewThemeWizardNote").focus();
		$("#txtNewThemeWizardYtLink").val(url);
		
		$("#txtNewThemeWizardArtist").autocomplete(
			'/Search/AutoComplete/Artist/', 
			{
				max: 10
			});
		$("#txtNewThemeWizardTitle").autocomplete(			
			'/Search/AutoComplete/Title/', 
			{
				max: 10
			});		
	}
	else
	{
		$("#divCreateNewItem").show();
		$("#video_short_search").hide();
		$("#txt_video_title").val(null);
		title.val(theSong.trim());
		artist.val(theArtist.trim());
		$("#Note").focus();
		youtubeTargetControl.val(url);
	}
	
    return false;
}
function youtubePreviousResult() {
    if (youtubeSearchPage > 0) {
        youtubeSearchPage = youtubeSearchPage - 1;
		youtubeStartIndex = (youtubeMaxResult * youtubeSearchPage) + 1; //1 based index
	}
    youtubeSearch(youtubeStartIndex);
}
function youtubeNextResult() {
    youtubeSearchPage = youtubeSearchPage + 1;
    youtubeStartIndex = (youtubeMaxResult * youtubeSearchPage) + 1; //1 based index
    youtubeSearch(youtubeStartIndex);
}
function youtubeSearch(index) {
	if (index == null) {
		index = 1;
		firstTime = true;
	}
    var youtubeQueryString = $('#QueryString').val();
	if (youtubeQueryString != '')
	{
		var link = 'http://gdata.youtube.com/feeds/api/videos/' +
							'?q=' + youtubeQueryString +
							'&start-index=' + index +
							'&max-results=' + youtubeMaxResult +
							'&v=2' +
							'&format=5' +
		//'&category=Music%2Csong' +
							'&alt=json-in-script' +
							'&callback=youtubeProcessResults';
		//create a JavaScript element that returns our JSON data.
		var script = document.createElement('script');
		script.setAttribute('id', 'jsonScript');
		script.setAttribute('type', 'text/javascript');
		script.setAttribute('src', link);

		//attach script to current page -  this will submit asynchronous
		//search request, and when the results come back callback 
		//function showMyVideos(data) is called and the results passed to it
		document.documentElement.firstChild.appendChild(script);
	}
	else
	{
		$('#divYoutubeResult').html($('#divNoResult').html());
		$('#ulYoutubeResults').html('');
		$('#QueryString').focus();
	}
}

var items = 0;
var firstTime = true;

function switchTo(index)
{
	$('#divYoutubeResult').html(items[index].embed);
}

function youtubeProcessResults(data) {
    youtubeStartIndex = data.feed['openSearch$startIndex']['$t'];
    youtubeItemsPerPage = data.feed['openSearch$itemsPerPage']['$t'];
    youtubeTotalResults = data.feed['openSearch$totalResults']['$t'];
    if (data.feed.entry != null) {
		var html = '';
		items = new Array();
		var index = 0;
        $.each(data.feed.entry, function(i, item) {
            var title = item['title']['$t'];
            var video = item['id']['$t'];
            video = video.replace('tag:youtube.com,2008:video:', 'http://www.youtube.com/watch?v=');  //replacement of link
            videoID = video.replace('http://www.youtube.com/watch?v=', ''); // removing link and getting the video ID
            //var img = 'http://img.youtube.com/vi/' + videoID + '/2.jpg'; //0.jpg big. 2.jpg small
            //$('#divYoutubeResult').append('<div><img class="youtube_img_item" src="' + img + '" alt="' + title + '" />' + title + '<br/><a href="#"  onclick="youtubePlay(\'' + videoID + '\');return false;">Play</a>&nbsp;&nbsp;<a href="#"  onclick="youtubeSelect(\'' + video + '\');return false;">Select</a></div><div class="clear" />');
            var img = '<img onclick="javascript:switchTo(' + index + ')" class="big_thumb_img_item" src="http://img.youtube.com/vi/' + videoID + '/1.jpg" title="' + title + '" alt="' + title + '"/>';
			//var item = img + '<p>' + title + '</p><a href="#" onclick="youtubeSelect(\'' + video + '\');return false;">Select</a><br clear="all"/>';
			var embed = '<object width="364" height="196"><param name="movie" value="http://www.youtube.com/v/' + videoID + '?fs=1&amp;hl=en_US">\
				</param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param>\
				<embed id="divYoutubeResultObject" src="http://www.youtube.com/v/' + videoID + '?fs=1&amp;hl=en_US" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="364" height="196"></embed></object>\
				<div style="margin-top:4px;"><p class="youtubeSearchEmbedTitle">' + title + '</p></div><a href="#" onclick="youtubeSelect(\'' + video + '\');return false;">Select</a>';

				html += '<li><div>' + img + '</div></li>';
			items.push({"url":video, "embed":embed});
			index += 1;
        });
		$('#ulYoutubeResults').html(html);
		if (firstTime == true) {
			switchTo(0);
			firstTime = false;
		}
    }
	else
	{
		$('#divYoutubeResult').html($('#divNoResult').html());
		$('#ulYoutubeResults').html('');
	}
}
