
function getYouTubeId(s)
{
	if(s.substring(0,4) == "http"){
		var a = s.split('?v=');
		if(a[1].indexOf("&")){
			var b = a[1].split('&');
			return b[0];			
		}else{
			return a[1];
		}
	}else{
		return s;	
	}
}


function getVideo(youtubestr)
{
	var youtubeid = getYouTubeId(youtubestr);
	$.include('http://gdata.youtube.com/feeds/api/videos/'+youtubeid+'?alt=json-in-script&callback=youtubeVidCallback');
}


function youtubeVidCallback(info)
{
	var author = info.entry.author[0].name.$t;
	var title = info.entry.media$group.media$title.$t;	
	var duration = info.entry.media$group.yt$duration.seconds;
	var youtubeid = getYouTubeId(info.entry.media$group.media$player[0].url);
	addYouTubeSong(title, author, youtubeid, duration);	
}

function getUsersVideos(user, startIndex)
{
	var url = 'http://gdata.youtube.com/feeds/api/users/'
			+user+'/uploads?orderby=published&max-results=50&start-index='
			+startIndex+'&alt=json-in-script&callback=userVideoCallback';
	$.include(url);	
	
}

function userVideoCallback(feed)
{
	//console.log(feed);

	var numItems = feed.feed.entry.length;
	//console.log(numItems);

	var author = feed.feed.author[0].name.$t;
	//console.log(author);
	
	for(i=0;i<numItems;i++)
	{
		thisVid = feed.feed.entry[i];
		
		var title = thisVid.media$group.media$title.$t;	
		var duration = thisVid.media$group.yt$duration.seconds;
		var youtubeid = getYouTubeId(thisVid.media$group.media$player[0].url);
		addYouTubeSong(title, author, youtubeid, duration);
		
	}

	var itemsPerPage = parseInt(feed.feed.openSearch$itemsPerPage.$t);
	var itemsStartIndex = parseInt(feed.feed.openSearch$startIndex.$t);
	var itemsTotalResults = parseInt(feed.feed.openSearch$totalResults.$t);
	
	/*
	console.log(itemsPerPage);
	console.log(itemsStartIndex);
	console.log(itemsTotalResults);
	*/
	
	if(itemsStartIndex + itemsPerPage - 1 < itemsTotalResults)
	{
		getUsersVideos(author, itemsStartIndex + itemsPerPage);
	}
	
	
}


function renameOpen(li)
{
	li.addClass("hover");
	li.find("input.artist").val(li.find("span.original_artist").text());
	li.find("input.title").val(li.find("span.original_title").text());

	li.find("div.name").css('display', 'none');
	//if(Browser.Engine.webkit || Browser.Engine.trident) li.getElement('.inputs').setStyle('padding-top','9px');
	li.find('div.inputs').css('display','block');
}

function renameClose(li)
{
	li.find('div.inputs').css('display','none');
	li.find('div.name').css('display','block');
	li.removeClass('hover');
	
}

function addYouTubeSong(title, author, youtubeid, duration)
{
	// If title has a - or : (not first char, so > 0) , assume what's before it is the artist
	// and what's after is the title. If it doesn't exist, make title
	// the title and author the artist
	if(title.indexOf('-') > 0 || title.indexOf(':') > 0){
		title = title.replace(/(-)+/, '-');
		var index = title.indexOf('-');
		if(index == -1)
		        index = title.indexOf(':');
		var artist = title.substring(0,index-1);
		var songtitle = title.substr(index+1);
	}else{
		var songtitle = title;
		var artist = '['+author+']';
	}

	addLI(artist, songtitle, youtubeid, duration);
}

function addLI(artist, songtitle, youtubeid, duration)
{
	var html = '<li><div class="name"><span class="original_artist">'+artist+'</span>';
		html += ' - <span class="original_title">'+songtitle+'</span>';
		html += ' <span class="youtube_link"><a href="http://www.youtube.com/watch?v='+youtubeid+'" target="_blank">[YouTube (new window)]</a></span>';
		html += '</div><div class="inputs"><input type="text" class="artist field" />';
		html += ' - <input type="text" class="title field" />';
		html += '<input type="button" class="save button" value="Save" />';
		html += ' <input type="button" class="cancel button" value="Cancel" />';
		html += '</div><div class="abc">rename</div><div class="ex">delete</div>';
		html += '<div class="duration">'+duration+'</div>';
		html += '<div class="youtubeid">'+youtubeid+'</div>';
		html += '</li>';
		
	//var li = $(html).insertAfter('.sortie li:last');
	$('#nosongmsg').remove();
	var li = $(html);
	$('.sortie').append(li);
	setupLI(li);
	
}

function addNoSongsMsg()
{
	if($('.sortie li').length == 0){
			$('.sortie').append($('<li id="nosongmsg"><div class="name">Add a song above</div></li>'));
	}
}

function setupLI(lis)
{
	lis.each(function(i){
		var li = $(this);
		
		// setup hovering
		li.hover(function(){
  			li.addClass("hover");
		},function(){
 			 li.removeClass("hover");
		});
		
		// setup renaming	
		li.find("div.abc").click(function(){ renameOpen(li); });
		li.find("input.cancel").click(function(){ renameClose(li); });
		li.find("input.save").click(function(){
			li.find("span.original_artist").text(li.find("input.artist").val());
			li.find("span.original_title").text(li.find("input.title").val());
			renameClose(li);	
		});
		li.find("div.ex").click(function(){
			var name = li.find("span.original_artist").text()+' - '+
							li.find("span.original_title").text();
			if(confirm('Are you sure you want to delete "'+name+'"?')) {
				li.remove();
				addNoSongsMsg();
			}			
			
		});
		
	

	}
	);
	
}

function CreatePlaylist()
{
	if($('.sortie li').not('#nosongmsg').length == 0){
		alert('You must add at least one video below first');
		return false;
	}

	$('#banner_form .gen').remove();
	
	$('.sortie li').each(function(){
		var li = $(this);
		var artist = li.find('.original_artist').text();
		var songtitle = li.find('.original_title').text();
		var youtubeid = li.find('.youtubeid').text();
		var duration = li.find('.duration').text();
		
		//console.log(artist+'-'+songtitle+'-'+youtubeid+'-'+duration);
		
		
		var inputs  = '<input class="gen" type="hidden" name="artist[]" value="'+artist+'"/>';
			inputs += '<input class="gen" type="hidden" name="songtitle[]" value="'+songtitle+'"/>'; 
			inputs += '<input class="gen" type="hidden" name="youtubeid[]" value="'+youtubeid+'"/>'; 
			inputs += '<input class="gen" type="hidden" name="duration[]" value="'+duration+'"/>'; 
		
		$('#banner_form').append(inputs);
	});	
	
	return true;	
}

$(document).ready(function(){
	$("#color_input").addColorPicker({'colorBg':'yes', 'cursor':'pointer'}); 
	
	setupLI($('.sortie li'));
	
	$('.sortie').sortable({});

	addNoSongsMsg();
	
	$('#add_youtube_form').submit(function(){
		var youtubestr = $.trim($(this).find('#youtube_video_input').val());
		
		if(youtubestr == '')
		{
			alert('Please enter a YouTube URL or video id');
			return false
		}
		
		getVideo(youtubestr);
		
		$(this).find('#youtube_video_input').val('');
		
		return false;		
	});
	
	$('#add_youtube_user_form').submit(function(){
		var username = $.trim($(this).find('#youtube_user_input').val());
		
		if(username == '')
		{
			alert('Please enter a YouTube username');
			return false
		}
		
		getUsersVideos(username, 1);
		
		return false;		
	});	
	
	
	$('#clearall').click(function(){
		if(confirm('Are you sure you want to delete all the videos listed below?'))
		{
			$('.sortie li').remove();
			addNoSongsMsg();
		}
					
		return false;
	});
	
	$('#banner_form').submit(function(){
		if($.trim($('#banner').val()) == "" || $('#banner').val() == $('#banner').attr('title')){
			alert("Please enter a title for this playlist");
			return false;
		}else{
			return CreatePlaylist();
		}
	});
	
	$('#banner').hint();
	$('#caption').hint();
	
});



/** 
 * $.include - script inclusion jQuery plugin 
 * Based on idea from http://www.gnucitizen.org/projects/jquery-include/ 
 * @author Tobiasz Cudnik <tobiasz.cudnik/gmail.com> 
 * @link http://meta20.net/.include_script_inclusion_jQuery_plugin 
 */ 
// overload jquery's onDomReady 
if ( jQuery.browser.mozilla || jQuery.browser.opera ) { 
    document.removeEventListener( "DOMContentLoaded", jQuery.ready, false ); 
    document.addEventListener( "DOMContentLoaded", function(){ jQuery.ready(); }, false ); 
} 
jQuery.event.remove( window, "load", jQuery.ready ); 
jQuery.event.add( window, "load", function(){ jQuery.ready(); } ); 
jQuery.extend({ 
    includeStates: {}, 
    include: function(url, callback, dependency){ 
        if ( typeof callback != 'function' && ! dependency ) { 
            dependency = callback; 
            callback = null; 
        } 
        url = url.replace('\n', ''); 
        jQuery.includeStates[url] = false; 
        var script = document.createElement('script'); 
        script.type = 'text/javascript'; 
        script.onload = function () { 
            jQuery.includeStates[url] = true; 
            if ( callback ) 
                callback.call(script); 
        }; 
        script.onreadystatechange = function () { 
            if ( this.readyState != "complete" && this.readyState != "loaded" ) return; 
            jQuery.includeStates[url] = true; 
            if ( callback ) 
                callback.call(script); 
        }; 
        script.src = url; 
        if ( dependency ) { 
            if ( dependency.constructor != Array ) 
                dependency = [dependency]; 
            setTimeout(function(){ 
                var valid = true; 
                $.each(dependency, function(k, v){ 
                    if (! v() ) { 
                        valid = false; 
                        return false; 
                    } 
                }) 
                if ( valid ) 
                    document.getElementsByTagName('head')[0].appendChild(script); 
                else 
                    setTimeout(arguments.callee, 10); 
            }, 10); 
        } 
        else 
            document.getElementsByTagName('head')[0].appendChild(script); 
        return function(){ 
            return jQuery.includeStates[url]; 
        } 
    }, 
    readyOld: jQuery.ready, 
    ready: function () { 
        if (jQuery.isReady) return; 
        imReady = true; 
        $.each(jQuery.includeStates, function(url, state) { 
            if (! state) 
                return imReady = false; 
        }); 
        if (imReady) { 
            jQuery.readyOld.apply(jQuery, arguments); 
        } else { 
            setTimeout(arguments.callee, 10); 
        } 
    } 
});


jQuery.fn.hint = function () {
  return this.each(function (){
    // get jQuery version of 'this'
    var t = jQuery(this); 
    // get it once since it won't change
    var title = t.attr('title'); 
    // only apply logic if the element has the attribute
    if (title) { 
      // on blur, set value to title attr if text is blank
      t.blur(function (){
        if (t.val() == '') {
          t.val(title);
          t.addClass('blur');
        }
      });
      // on focus, set value to blank if current value 
      // matches title attr
      t.focus(function (){
        if (t.val() == title) {
          t.val('');
          t.removeClass('blur');
        }
      });

      // clear the pre-defined text when form is submitted
      t.parents('form:first()').submit(function(){
          if (t.val() == title) {
              t.val('');
              t.removeClass('blur');
          }
      });

      // now change all inputs to title
      t.blur();
    }
  });
}

