var vivigas = (function($, win, doc, undefined) {
	
	var api = {
		query : function (selector, context) {
			var $el = $(selector, context || doc) || [];
			
			return !!$el.length ? $el : false;
		},
		
		randomNumber : function (min, max){
			return Math.floor(Math.random() * (max - min + 1) + min);
		}
	};
	
	//the YouTube channel Object
	api.YouTube = function (userID) {
		//https://gdata.youtube.com/feeds/api/users/VIVIgasVideo/uploads/?v=2&alt=jsonc&callback=functionName	
		this.userID = userID;
		this.userFeed = api.YouTube.GDATA_URL + 'users/' + userID;
		this.items = []; //array of videos
		this.totalItems = 0;
		this.response; //the result from the youtube query
		this.request; //the request contro property, when a request is running it'll be a jquery AJAX object
		
	};
	
	//setting some statics
	api.YouTube.GDATA_URL = 'https://gdata.youtube.com/feeds/api/';
	api.YouTube.DEFAULT_QUERY_OBJ = { 'v' : 2, 'alt' : 'jsonc'};
	
	//instance object
	api.YouTube.prototype = {
		
		onError : $.noop, //when AJAX call fails
		
		onQueryError : $.noop, //when YouTube query fails
		
		/**
		 * prece
		 */
		_processResponse : function (response) {
			var data;
			
			this.response = null; //clean the response
			this.items = []; //reset the video list
			if (response.hasOwnProperty('error')) {
				this.onQueryError(response);
				return false;
			}
						
			this.response = response;
			this.totalItems = response.data.totalItems;
			
			if (this.totalItems) {
				this.items = response.data.items;
				return true;
			}
			
			return false;
		},
		
		/**
		 * Get videos from the user's channel
		 */
		get : function (queryObj, callback) {
			var queryObj = $.extend({
					//some defaults
					'max-results' : 50,
					'orderby': 'published'
					
				}, api.YouTube.DEFAULT_QUERY_OBJ, queryObj || {}),
				queryString,
				that = this;
			
			if (this.request) {
				this.request.abort(); //abort any queued request
			}
			
			this.request = $.ajax({
				url : this.userFeed + '/uploads',
				data : queryObj,
				dataType : 'jsonp',
				success : function (response) {
					if (that._processResponse.call(that, response)) {
						callback && callback.call(that, response);	
					}
				},
				error : this.onError,
				complete : function () {
					that.request = null; //reset the response property when AJAX call is done
				}
			});
			
		},
		
		embedTo : function (item, elementId, width, height) {
			var	flashParams = { allowScriptAccess: 'always' , wmode : 'opaque' },
    			flashAtts = { id: elementId };			
			
			if (!('swfobject' in win)) {
				return false;
			}
			
			if (!item.id) { 
				//not a item object, get it!
				item = this.getItem(item);
			}
			
			swfobject.embedSWF(
				'http://www.youtube.com/e/' + item.id + '?rel=0&showinfo=0',
				elementId, 
				width,
				height,
				'8', 
				null, 
				null, 
				flashParams, 
				flashAtts
			);
		},
		
		getItem : function (index) {
			
			var total = this.totalItems,
				items = [].concat(this.items),
				itemKey = 0,
				item = false;
				
			function randomNumber (min, max){
				return Math.floor(Math.random() * (max - min + 1) + min);
			} 
			
			if (index === 'random') {
				
				//more than one, get one 
				itemKey = randomNumber(0, (total-1));
				
				item = items[itemKey]; //get a reference of the item
				items.splice(itemKey, 1); //remove it from the array
				
				while(total && item.accessControl.embed !== 'allowed') {
					total--;
					itemKey = randomNumber(0, total);
					item = items.splice(itemKey, 1);
				}
				
			} else if (typeof index === 'number' && index < items.length ) {
				item = items[index];
			}
			
			if (item && item.accessControl.embed === 'allowed') {
				return item;
			}
			return false;		
		}
		
	};
	
	
	
	return api;
	
})(jQuery, window, document);


jQuery(function ($) {
	
	var $youTubePlayer = vivigas.query('#homepageVideoContainer'),
		vivitube;
	
	
	if ($youTubePlayer) {
		vivitube = new vivigas.YouTube('VIVIgasVideo');
		
		vivitube.get({}, function () {
			
			this.embedTo('random', 'homepageVideoContainer', '357', '229');
			
			
		});
	} 
	
});

