FavoritesWidget = {
	
	// setup object params
	params: {
	
		// setup authentication data
		isLoggedIn:		false,
		authChecked:	false,
		
		// setup various settings
		currFavType:	'video',
		mediaUrl:		'http://media.booeep.com',
		panelExpanded:	false,
		pagination: {
			recPerPage:		3,
			pageScope:		5,
			currPage:		1
		},
		
		// setup fav data
		favoriteTypes:	{
			video:	{
				label:	'Videos',
				url:	'/videos/'
			},
			image:	{
				label:	'Photos',
				url:	'/photos/'
			}
		},
		favData: []
	},
	
	// holder for dropmenu clone
	typesDrop: false,
	
	// init function gets the ball rollin!
	init: function( params )
	{
		var me = this;
		
		// check login
		me.initAuth();
		
		// extend params with user-defined params
		if ( params ) {
			$.extend( me.params, params );
		}
		
		// check for logged in functionality
		if ( me.params.isLoggedIn ) {
		
			// process fav data
			me.procFavData();
			
			// build types drop down
			me.buildTypesNav();
		}
		
		// attach mouseclick handler
		$('#widget_header').click( function() {
			if ( me.params.panelExpanded ) {
				me.hidePanel();
			}
			else {
				me.showPanel();
			}
		} );
		
		// attach mousemove handler
		$('#widget_content').mousemove( function() {
			me.showPanel();
		} );
	},
	
	initAuth: function()
	{
		var me = this;
		
		if ( !me.params.authChecked ) {
			if ( getCookie('AUTH') ) {
				me.params.isLoggedIn = true;
			}
			me.params.authChecked = true;
		}
	},

	// load data and setup pagination
	procFavData: function()
	{
		var me = this;
		
		// empty the favs element
		$('#fav_content').empty();
		
		// init vars and build pagination
		var pagData = me.buildPagination(),
			data = me.params.favData,
			params = me.params.pagination;
		
		// loop through data and build each item
		if ( data.length > 0 ) {
		
			// show favs pane
			$('#fav_content').show();
			
			// hide empty pane
			$('#fav_empty').hide();
		
			for( var i=pagData.startItem; i<=pagData.endItem; i++ )
			{
				me.buildFavItem( data[i] );
			}
		}
		// empty dataSet - build 'no favorites' message
		else {
		
			// hide favs pane
			$('#fav_content').hide();
			
			// show empty pane
			$('#fav_empty').show();
		}
	},
	
	loadFavType: function( type )
	{
		var me = this;
		
		var data = {
			favorite_type: type
		};
		if ( me.params.currSiteEntity ) {
			data.content_entity_id = me.params.currSiteEntity;
		}
		
		// load the favData
		$.ajax( {
			type:		'POST',
			url:		'/global/ajax/favorites/getData',
			data:		data,
			dataType:	'json',
			success:	function(response)
						{
							if ( response.status == 'ok' ) {
								
								// set the current
								me.params.currFavType = response.favorite_type;
								
								// load the favData
								me.params.favData = response.data;
								
								// reset pagination to page 1 and re-render
								me.params.pagination.currPage = 1;
								me.procFavData();
							}
							else {
								alert( response.message || 'error' );
							}
						}
		} );
	},
	
	buildFavItem: function( data )
	{
		var me = this;
		
		// create new node
		var node = $('<li></li>').appendTo('#fav_content');
		node.tplAppend( data, me.favItemTpl );
		
		// bind click handlers
		/*
		$(node).find('.fav_share')
			.click( function() {
				var elem = this;
				me.removeFromFavorites( elem );
				return false; // cancel the href
			} );
		*/
		$(node).find('.fav_subtract')
			.click( function() {
				var elem = this;
				me.removeFromFavorites( $(elem).parents('a')[0] );
				return false; // cancel the href
			} );
	},
	
	favItemTpl: function()
	{
		var FW = FavoritesWidget;
		
		// normalize the object data
		if ( this.favorite_type == 'image' || this.favorite_type == 'video' ) {
		
			var obj = {
				item_img:	FW.params.mediaUrl + '/' + this.content_id + '_landscape_thumb',
				item_name:	this.content_name,
				item_link:	'/'
							+ ( this.favorite_type == 'image' ? 'photo' : this.favorite_type )
							+ 's/view/?mid=' + this.content_id
			};
		}
		else if ( this.favorite_type == 'news' ) {
		
			var obj = {
				item_img:	'/images/fav_video_thumb.png',
				item_name:	this.content_name,
				item_link:	'/news/view/?nid=' + this.content_id
			};
		}
		
		var tpl = [
			'a', { href: obj.item_link, content_id: this.content_id }, [
				'span', { className: 'fav_img' }, [
					'img', { src: obj.item_img, border: '0', width: '90', height: '51' },
					'span', { className: 'fav_overlay' }, [
						'span', { className: 'fav_play' },
						//'span', { className: 'fav_share' },
						'span', { className: 'fav_subtract' }
					]
				],
				'span', { className: 'fav_info' }, [
					'span', { className: 'title' }, [ obj.item_name ],
					/*'span', { className: 'meta' }, [
						'span', { className: 'add_date' }, [
							'Added: ' + this.favorite_created_stamp
						]
					],*/
					'span', { className: 'btn view_' +this.favorite_type }, [],
				]
			]
		];
		
		return tpl;
	},
	
	buildPagination: function()
	{
		var me = this;
		
		// get pagination data
		data = me.getPaginationData();
		$.extend( data, {
			favoriteData:	me.params.favoriteTypes[me.params.currFavType]
		} );
		
		// update pagination container
		var node = $('#footer_fav');
		node.empty().tplAppend( data, me.paginationTpl );
 	
		// bind click handlers
		node.find('#footer_fav_pagination a').click( function() {
			var elem = this;
			me.params.pagination.currPage = parseInt( elem.getAttribute('page_num') );
			me.procFavData();
		} );
		
		return data;
	},
	
	paginationTpl: function()
	{
		// check for empty dataSet
		if ( !this.total ) {
			return [];
		}
		
		// build template
		else {
			
			// calculate pages
			var pageList = new Array();
			
			if ( this.total > 3 ) {
				if ( this.prevPage ) {
					pageList.push(
						'li', { className: 'prev' }, [
							'a', { href: 'javascript:void(0)', page_num: this.prevPage }, [
								'span', {}, ['prev']
							]
						]
					);
				}
				for( i=scopeStart; i<=scopeEnd; i++ )
				{
					if ( i != this. currPage ) {
						pageList.push(
							'li', {}, [
								'a', { href: 'javascript:void(0)', page_num: i }, [ i ]
							]
						);
					}
					else {
						pageList.push(
							'li', {}, [ i ]
						);
					}
				}
				if ( this.nextPage ) {
					pageList.push(
						'li', { className: 'next' }, [
							'a', { href: 'javascript:void(0)', page_num: this.nextPage }, [
								'span', {}, ['next']
							]
						]
					);
				} 
			}
		
			var tpl = [
				'div', { id: 'footer_fav_type' }, [
					'a', { href: this.favoriteData.url }, [
						'span', {}, [ 'More ' + this.favoriteData.label ]
					]
				],
				'div', { id: 'footer_fav_pagination' }, [
					'ul', { className: 'rx-pagination' }, pageList
				]
			];
			
			return tpl;
		}
	},
	
	getPaginationData: function()
	{
		var me = this;
		
		// clone pagination params
		data = $.extend({}, me.params.pagination);
		
		var totalRecords	= me.params.favData.length,
			currentPage		= data.currPage,
			scope			= data.pageScope,
			recPerPage		= data.recPerPage;
		
		var numPages = ( totalRecords > 0 ) ?
			Math.ceil( totalRecords / recPerPage ) :
			1 ;
		var firstPage = ( totalRecords > 0 ) ?
			1 :
			0 ;
		var lastPage = ( totalRecords > 0 ) ?
			numPages :
			0 ;
		var prevPage = ( firstPage < currentPage ) ?
			currentPage -1 :
			0 ;
		var nextPage = ( lastPage > currentPage ) ?
			currentPage +1 :
			0 ;
		
		// calculate a tighter scope of pages to list
		if ( scope ) {
			if ( scope <= numPages ) {
				scopeBuffer = Math.ceil( scope / 2 ) -1;
				scopeStart = currentPage - scopeBuffer;
				scopeEnd = currentPage + ( scope % 2 ? scopeBuffer : scopeBuffer +1 );
				if ( scopeStart < 1 ) {
					scopeStart = 1;
					scopeEnd = scope;
				} else if ( scopeEnd > lastPage ) {
					scopeEnd = lastPage;
					scopeStart = lastPage - scope +1;
				}
			} else {
				scopeStart = firstPage;
				scopeEnd = lastPage;
			}
		}
		
		// calculate start / end items
		var startItem = ( currentPage -1 ) * recPerPage,
			endItem = startItem + ( recPerPage -1 );
			
		if ( ( endItem +1 ) > totalRecords )
			endItem = totalRecords -1;
		
		// extend clone
		$.extend( data, {
			total:			totalRecords,
			numPages:		numPages,
			recPerPage:		recPerPage,
			firstPage:		firstPage,
		 	lastPage:		lastPage,
			prevPage:		prevPage,
			nextPage:		nextPage,
			scopeStart:		scopeStart,
			scopeEnd:		scopeEnd,
			startItem:		startItem,
			endItem:		endItem
		} );
		
		return data;
	},
	
	buildTypesNav: function()
	{
		var me = this;
		
		// compile data for dropdown
		var data = {
			currFavType:	me.params.currFavType,
			favTypes:		me.params.favoriteTypes
		};
		
		// update nav container
		var node = $('#fav_nav_container');
		node.empty().tplAppend( data, me.typesNavTpl );
		
		// attach click handlers
		$('#fav_nav').find('a')
			.click( function() {
				var item = this;
				
				// load the favorite type
				me.loadFavType( item.getAttribute('favorite_type') );
				
				// unmark previous active
				$(item.parentNode).find('a.active').removeClass('active');
				
				// mark new active
				$(item).addClass('active');
			} );
	},
	
	typesNavTpl: function()
	{
		// calculate available types
		var availTypes = new Array();
		for( var i in this.favTypes )
		{
			availTypes.push(
				'a', { id: 'fav_nav_' + i + '_btn', favorite_type: i , className: ( (i == this.currFavType) ? 'active' : '' ), href: 'javascript:void(0)' }, [
					'span', { }, [ this.favTypes[i] ]
				]
			);
		}
		
        var tpl = [
        	'div', { id: 'fav_nav' }, [
        		'span', { id: 'folder_nav_label'}, [ 'MY FAVORITES' ],
        		'div', { id: 'fav_nav_btn'}, availTypes
        	]
        ];
        
		return tpl;
	},
	
	addToFavorites: function( elem )
	{
		var me = this;
		
		// check for login
		if ( !me.enforceLogin() )
			return false;
	
		// prepare data
		var data = {
			favorite_type:	elem.getAttribute('media_type'),
			content_id:		elem.getAttribute('entity_id') + '_'
							+ elem.getAttribute('media_type') + '_'
							+ elem.getAttribute('media_id')
		};
		
		// send request
		$.ajax( {
			type:		'POST',
			url:		'/global/ajax/favorites/add',
			data:		data,
			dataType:	'json',
			success:	function(response)
						{
							if ( response.status == 'ok' ) {
							
								var favItem = response.favItem;
								
								me.showPanel();
							
								if ( me.params.currFavType == favItem.favorite_type ) {
									// add favItem to dataSet
									me.params.favData.unshift( favItem );
									
									// reset pagination to page 1 and re-render
									me.params.pagination.currPage = 1;
									me.procFavData();
								}
								else {
									// load the favorite type
									me.loadFavType( favItem.favorite_type );
								}
							}
							else {
								alert( response.message || 'error' );
							}
						}
		} );
		
		return false;
	},
	
	removeFromFavorites: function( elem )
	{
		// check for confirmation to remove
		var msg = 'Are you sure you wish to remove this favorite?';
		if ( !confirm( msg ) )
			return false;

		var me = this;
		
		// check for login
		if ( !me.enforceLogin() )
			return false;
			
		// send request
		$.ajax( {
			type:		'POST',
			url:		'/global/ajax/favorites/remove',
			data:		{
							favorite_type:	me.params.currFavType,
							content_id:		elem.getAttribute('content_id')
						},
			dataType:	'json',
			success:	function(response)
						{
							if ( response.status == 'ok' ) {
							
								// grab favItem
								var favItem = response.favItem;
								
								// remove favItem from dataSet
								var index = 0;
								for( index=0; index<me.params.favData.length; index++)
								{
									if ( me.params.favData[index].content_id == favItem.content_id )
										break;
								}
								me.params.favData.splice( index, 1 );
								
								// rebuild data
								me.procFavData();
							}
							else {
								alert( response.message || 'error' );
							}
						}
		} );
		
		return false;
	},
	
	togglePanel: function()
	{
		var me = this;
		
		if ( me.params.panelExpanded ) {
			me.hidePanel();
		}
		else {
			me.showPanel();
		}
	},
	
	showPanel: function()
	{
		var me = this;
	
		if ( !me.params.panelExpanded ) {
			me.params.panelExpanded = true;
			$('#widget_content').show();
		}
		
		// continue only if logged in
		if ( !me.params.isLoggedIn )
			return;
		
		// reset the timeout
		if ( me.params.panelTimeout )
			clearTimeout( me.params.panelTimeout );
			
		me.params.panelTimeout = setTimeout( function() {
			me.hidePanel();
		}, 5000);
	},
	
	hidePanel: function()
	{
		var me = this;
	
		me.params.panelExpanded = false;
		$('#widget_content').hide();
		
		if ( me.params.panelTimeout ) {
			clearTimeout( me.params.panelTimeout );
			me.params.panelTimeout = 0;
		}		
	},
	
	enforceLogin: function()
	{
		var me = this;
		
		// init auth
		me.initAuth();
		
		if ( me.params.isLoggedIn ) {
			return true;
		}
		else {
			alert('You must be logged in to do that');
			
			// show panel
			me.showPanel();
			
			// scroll to top!
			document.location.href = '#';
			
			// focus on email field
			$('#widget_content').find('#email').focus().css('background-color', 'pink');
			
			return false;
		}
	}
};

