


(function( $ ){

	// Global Variable, 
	// Hoping to be able to move this out of this current position.
	// But Currently Don't know how
	var data;

	var methods = {	
    
		// dFav Basic Functionality --------------------------------------------------------------------
		init : function( options ) {
            
			// Setting My Variables ----------------------------------------------------------------
			var settings = {
	                	 resourceID : 'null',								// Resource ID
	                	 rating : 0,									// Rating
	                	 format : 'stars',
	                	 x : 0,
	                	 d : '',
	                	 ranking : -99,
	                	 favoritesID : '',
	                	 getFavoritesID : '',
	                	 getFavoritesCountID : '',
	                	 rankingsID : '',
	                	 ratingsID : '',
	                	 getRatingsCountID : '',
	                	 getRatingsID : '',
	                	 isFavorite : false,
	                	 action : '',
	                	 initialize : true,
	                	 favFormat : true
			};
			
			// ---------------------------------------------------------- END - Setting My
	            
			// Updating My Variables ---------------------------------------------------------------
			if ( options ) { 
				$.extend( settings, options );
			}
			// --------------------------------------------------------- END - Updating My Variables
			
			// Each --------------------------------------------------------------------------------
			return this.each(function() {
			
				// Cache this
				var $this = $(this);
				
				
				
				// Create This Data Object -----------------------------------------------------
				$this.data({
					resourceID : settings.resourceID,
		                	rating : settings.ratings,
		                	format : settings.format,
		                	x : settings.x,
		                	d : settings.d,
		                	ranking : settings.ranking,
		                	favoritesID : settings.favoritesID,
		                	getFavoritesID : settings.getFavoritesID,
		                	getFavoritesCountID : settings.getFavoritesCountID,
		                	rankingsID : settings.rankingsID,
		                	ratingsID : settings.ratingsID,
		                	getRatingsCountID : settings.getRatingsCountID,
		                	isFavorite : settings.isFavorite,
		                	action : settings.action,
		                	initialize : settings.initialize,
		                	favFormat : settings.favFormat 
				});
				
				// Save This Data object in Data Variable --------------------------------------
				data = $this.data();
				
				if ( data.ratingsID != '' ) {
				
					if ( data.format == 'stars' ) {
						$('#' + data.ratingsID ).html('<ul id="stars"><li><a href="#1" id="star-1" class="star"></a></li><li><a href="#2" id="star-2" class="star"></a></li><li><a href="#3" id="star-3" class="star"></a></li><li><a href="#4" id="star-4" class="star"></a></li><li><a href="#5" id="star-5" class="star"></a></li></ul>');
					}
					$this.dRatings('runAjax', data, 'isRated');
					
					// If you wanted to know how many people have Rated this
					if ( data.getRatingsCountID != '' ) {
						$this.dRatings('runAjax', data, 'getRatingsCount');
					}
				
					// Variables for Our Hover Functionality
					var hRating;	// Hover Rating
					var i;		// Incrementer
					
					// Star Hover Functionality
					$('#' + data.ratingsID + ' a').hover(function () {
						
						hRating = $(this).attr('id').split('-')[1];
						$('#' + data.ratingsID + ' li').each(function(){
							// Add 'hover' class to all li's less than the hRating	
							if ( i < hRating ) { $(this).addClass('hover');i++;}
							else {}
						});
					}, 
						function () {
							// Remove all 'hover' classes
							$('#' + data.ratingsID + ' li').removeClass('hover');
							// Reset both
							hRating = 0;
							i = 0;
						}
					);
					
					// Rate this File ---------------------------------------------------------------
					$('#' + data.ratingsID + ' a').click(function() {
						
						// Get which star you clicked on and convert it into a Integer
						data.rating = $(this).attr('id').split('-')[1];
						data.x = 0;
						$this.dRatings('addRating', data);
						
						// Keeps the Back button normal
						return false;
					});
				
				}
				
				if ( data.favoritesID != '' ) {
				
					$('#' + data.favoritesID ).html('<a href="#" class="add-fav"><span>Add to Favorites</span></a>');
					$this.dRatings('runAjax', data, 'isFavorite');
					
					// If you wanted to know how many people have favorited this file
					if ( data.getFavoritesCountID != '' ) {
						$this.dRatings('runAjax', data, 'getFavoritesCount');
					}
				
					// Favorites Hover Functionality ------------------------------------------------
					$('#' + data.favoritesID + ' a').hover(function() {
						$(this).addClass('hover');
					},
						function() {
							$(this).removeClass('hover');
					});
					
					// Add or Remove from Favorites--------------------------------------------------
					$('#' + data.favoritesID).click(function() {
					
						if ( data.isFavorite == false ) {
							$this.dRatings('runAjax', data, 'addFavorite');
						}
						if ( data.isFavorite == true ) {
							$this.dRatings('runAjax', data, 'deleteFavorite');
						}
						
						// Keeps the Back button normal
						return false;
					});
				}
				
				// getFavorites -----------------------------------------------------------------
				if ( data.getFavoritesID != '' ){
					// Run getFavorites AJAX call
					$this.dRatings('runAjax', data, 'getFavorites');
				}
				
				// getRatings -------------------------------------------------------------------
				if ( data.getRatingsID != '' ){
					// Run getFavorites AJAX call
					$this.dRatings('runAjax', data, 'getRatings');
				}
				
			});	// ------------------------------------------------------------------- END - Each
		
		},   // ------------------------------------------------------------------------------ END - init


		// runAjax Functionality ------------------------------------------------------------------------
		runAjax : function ( options, action ) {
	
			// Each ---------------------------------------------------------------------------------
			return this.each(function() {
			
				// Cache this
				var $this = $(this);
			
				// Base Ajax Call
				$.ajax({
					type: 'POST',
					url: '/content/system/modules/com.dispatch.favorites/rest/' + action + '/',
					data: {
						r : data.resourceID
					},
					dataType : 'json',
					jsonp: null,
		            		jsonpCallback: null,
					error : function(d, e) {
						
						if ( ( e == 'parsererror' ) && ( d.responseText == '{error: "Favorites List is empty or null" }' ) && ( action == 'deleteFavorite' ) ){
							$this.dRatings('runAjax', data, 'isFavorite');
						}
						
					},
					success: function(d) {
					
						if ( "error" in d ) {
							console.log(d);
						} else {
						
							data.d = d;
							
							if ( ( action == 'addFavorite' ) || ( action == 'deleteFavorite' ) ) {
								$this.dRatings('runAjax', data, 'isFavorite');
							}
							
							else { $this.dRatings( action, data ); }
						
						}
					
					}
					
				});	// ----------------------------------------------------------- END - Ajax
			
			});	// ------------------------------------------------------------------- END - Each
		
		},	// ------------------------------------------------------------------------ END - runAjax
		
		// updateFav Functionality ----------------------------------------------------------------------
		isFavorite : function ( data ) {
	
			// Each ---------------------------------------------------------------------------------
			return this.each(function() {
			
				// Cache this
				var $this = $(this);
				
				data.isFavorite = data.d.isFavorite;
				
				// If you did not change the favFormat
				if ( data.favFormat == true  ) {
					if ( data.isFavorite == true ) { 
						$('#' + data.favoritesID ).html('<a href="#" class="remove-fav" rel="poo"><span>Remove Favorite</span></a>');
					}
					
					if ( data.isFavorite == false ) { 
						$('#' + data.favoritesID ).html('<a href="#" class="add-fav"><span>Add to Favorites</span></a>'); 
						
					}
				}
				if ( data.favFormat != true ) {
					if ( data.isFavorite == true ) { 
						$('#' + data.favoritesID + ' a').removeClass('add-fav').addClass('remove-fav');
					}
					
					if ( data.isFavorite == false ) { 
						$('#' + data.favoritesID + ' a').removeClass('remove-fav').addClass('add-fav');
						
					}
				}
				
				
			});	// ------------------------------------------------------------------- END - Each
		
		},	// ---------------------------------------------------------------------- END - updateFav
		
		 
		
		// isRated Functionality ------------------------------------------------------------------------
		isRated : function ( data ) {
	
			// Each ---------------------------------------------------------------------------------
			return this.each(function() {
			
				// Cache this
				var $this = $(this);
				
				data.rating = data.d.rate;
				
				$('#' + data.ratingsID).find('li').removeClass('selected');
				$('#' + data.ratingsID).find('a').each(function() {
				
					if ( data.x < data.rating ) {
					
						$('#' + data.ratingsID + ' li:nth-child(' + ( data.x + 1 ) + ')').addClass('selected');
						data.x++;
						
					}
					else { }
					
				});
				
				// Get the Average Rating of this File -----------------------------------------
				if ( data.rankingsID != '' ) {
					$this.dRatings('runAjax', data, 'getRankings');
				}
				
			});	// ------------------------------------------------------------------- END - Each
		
		},	// ------------------------------------------------------------------------ END - isRated 
		
		// addRating Functionality ----------------------------------------------------------------------
		addRating : function ( data ) {
			
			// Each ---------------------------------------------------------------------------------
			return this.each(function() {
			
				// Cache this
				var $this = $(this);
				
				$.ajax({
					type: 'POST',
					url: '/content/system/modules/com.dispatch.favorites/rest/addRating',
					data: {
						r : data.resourceID,
						rating : data.rating
					},
					dataType : 'json',
					jsonp: null,
		            		jsonpCallback: null,
					success: function(d) {
					
						// Setting Some trickery here so we can re-use the isRated helper method
						data.d.rate = d.ratings[0].rating;
						
						if ( "error" in d ) { 
							console.log(d);
						} 
						else { $this.dRatings('isRated', data); }
					
					}	// ------------------------------------------------ END - Success
					
				}); 	// ----------------------------------------------------------- END - Ajax
				
			});	// ------------------------------------------------------------------- END - Each
		
		},	// ---------------------------------------------------------------------- END - addRating 
		
		// getRankings Functionality --------------------------------------------------------------------
		getRankings : function ( data ) {
			
			// Each ---------------------------------------------------------------------------------
			return this.each(function() {
			
				// Cache this
				var $this = $(this);
				
				$('#' + data.rankingsID ).html('<p class="average-rating">Average Rating: ' + data.d.rankings + ' stars');
				
				data.ranking = data.d.rankings;
				
			});	// ------------------------------------------------------------------- END - Each
		
		},	// -------------------------------------------------------------------- END - getRankings 
		
		// getFavorites Functionality -------------------------------------------------------------------
		getFavorites : function ( data ) {
			
			// Each ---------------------------------------------------------------------------------
			return this.each(function() {
			
				// Cache this
				var $this = $(this);
				
				if ( 'favorites' in data.d ) {
				
				var i = 0;
				
				var count = data.d.favorites.length;
				
				
					if ( ( count > 0 ) || ( count != 'null' ) ) {
					
						$('#' + data.getFavoritesID ).append('<ul id="fav-list"></ul>');
					
						for ( i = 0; i < count; i++ ) {
							
							// Make our JSON object into a smaller named variable
							var d = data.d.favorites[i];
						
							$('#fav-list').append('<li><a href="' + d.url + '" target="blank">' + d.title + '</a> <span class="fav-rating"> - ' + d.rating + ' stars</span></li>');
							
						};	
					}	
				}
				
			});	// ------------------------------------------------------------------- END - Each
		
		},	// ------------------------------------------------------------------- END - getFavorites 
		
		// getRatings Functionality ---------------------------------------------------------------------
		getRatings : function ( data ) {
			
			// Each ---------------------------------------------------------------------------------
			return this.each(function() {
			
				// Cache this
				var $this = $(this);
				
			});	// ------------------------------------------------------------------- END - Each
		
		},	// --------------------------------------------------------------------- END - getRatings 

		// getFavoritesCount Functionality --------------------------------------------------------------
		getFavoritesCount : function ( data ) {
			
			// Each ---------------------------------------------------------------------------------
			return this.each(function() {
			
				// Cache this
				var $this = $(this);
				
				// If Someone has Favorited this file, Display Total Favorites
				if ( data.d.favoritesCount > 0 ) {
					$('#' + data.getFavoritesCountID ).append(data.d.favoritesCount);
				}
				
			});	// ------------------------------------------------------------------- END - Each
		
		},	// -------------------------------------------------------------- END - getFavoritesCount 
		
		// getRatingsCount Functionality ----------------------------------------------------------------
		getRatingsCount : function ( data ) {
			
			// Each ---------------------------------------------------------------------------------
			return this.each(function() {
			
				// Cache this
				var $this = $(this);
				
				// If Someone has Rated this file, Display Total Ratings
				if ( data.d.ratingsCount > 0 ) {
					$('#' + data.getRatingsCountID ).append(data.d.ratingsCount);
				}
				
			});	// ------------------------------------------------------------------- END - Each
		
		}	// ---------------------------------------------------------------- END - getRatingsCount 
		
	};  // ------------------------------------------------------------------------------------ END - methods
		
$.fn.dRatings = function( method ) {

	if ( methods[method] ) {
		return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
	} else if ( typeof method === 'object' || ! method ) {
		return methods.init.apply( this, arguments );
	} else {
		$.error( 'Method ' +  method + ' does not exist on jQuery.dRatings' );
	}    

};

})( jQuery );
