
/*
if (! console) {
	var console = console || { "log": function() {} };
}
//*/

// register gdata youtube service to global scope under key "youtube"
(function(serviceName, jQuery) {

	var youtube = window[serviceName] = {
		addGDataScript: function (id) {
			if (id) {
				addGDataScriptForConcreteVideo(id);
			} else {
				addGDataScriptForAllVideos();
			}
		},

		callback: function (data) {
			if (data.entry) {
				processOneEntry(data.entry);
			} else if (data.feed && data.feed.entry) {
				processAllEntries(data.feed.entry || []);
			}			
		}
	};
	
	var G_DATA_BASE = 'http://gdata.youtube.com/feeds/api/videos/',
	    G_DATA_PARAMS = 'v=2&alt=json-in-script&format=5&callback=' + serviceName + '.callback';
	
	var addGDataScriptForConcreteVideo = function (id) {
		jQuery.getScript(G_DATA_BASE + id + '?' + G_DATA_PARAMS);
	};	
	
	var addGDataScriptForAllVideos = function () {
		var ids = getAnchors().map(function (i, anchor) {
		             return '"' + getIdFromUrl(anchor.href) + '"';
		          }).get().join('|');
		jQuery.getScript(G_DATA_BASE + '?q=' + ids + '&fields=entry(id,title)&' + G_DATA_PARAMS);
	};
	
	var getAnchors = function () {
		return jQuery('a.youtubeAnchor');
	};

	var getIdFromUrl = function (url) {
		return url.replace(/^.*[&\?]v=([^\&#]+).*$/, '$1');
	};
	
	var processOneEntry = function (entry) {
		changeAnchorsContent(getAnchorsAsArray(), entry);
	};
	
	var processAllEntries = function (entries) {
		var notChangedAnchors = getAnchorsAsArray();
		var entriesLength = entries.length;
		for (var i = 0; i < entriesLength; i++) {
			var id = changeAnchorsContent(notChangedAnchors, entries[i]);
			notChangedAnchors[id] && delete notChangedAnchors[id];
		}
		
		loadDataForNotChangedAnchors(notChangedAnchors);
	};
	
	var getAnchorsAsArray = function () {
		var anchors = [];
		getAnchors().each(function (i, anchor) {
			var id = getIdFromUrl(anchor.href);
			anchors[id] = (anchors[id] || []).concat(anchor);	
		});
		return anchors;
	};

	var changeAnchorsContent = function (allAnchors, entry) {
		var id = entry.id.$t.replace(/^.*:video:(.*)$/, '$1');
		if (allAnchors[id]) {
			var title = entry.title.$t;
			var anchors = allAnchors[id];
			for (var i = 0; i < anchors.length; i++) {
				anchors[i].innerHTML = title;
			}
		}
		return id;
	};
	
	var loadDataForNotChangedAnchors = function (anchors) {
		for (var id in anchors) { 
			youtube.addGDataScript(id);
		}
	};
	
}) ('youtube', $);


