var Children, Parents, Pagination;

// --------------------------------------------------------------------------------------
// Page elements

// div in #parents 
$.fn.pageParent = function() {
	return this.orParent('.parent').extend({
		moveToTop: function(){
			var byAge = Parents.byAge();
			if (byAge.isNotEmpty()) {
					Parents.byAge().after(this);
				} else {                      
					Parents.prepend(this)
				}
		}
	});
};

// Either images or details child cell   
$.fn.child = function() {
	return this.extend({  
		init: function(){
			this.watchHover();
		}, 
		
		watchHover: function(){
			// select child on hover
			this.hover(function() {
				$(this).child().select();
	    }, function() {
				return false  
	    });
		},
		
		// returns url for child
		href: function(){
			return this.find('a:first').attr('href')
		},
		
		select: function(){				
			Children.deselectOthers(this);
			this.cells().addClass('selected');
			this.showGrandchildren();
		},
		
		deselect: function(){    
			this.find('.grandchildren').hide(); 
			this.removeClass('selected')            
		},                         
		
		grandchildren: function(){
			return this.cells().find('.grandchildren').grandchildren()
		},
		
		showGrandchildren: function(){
			var grandchildren = this.grandchildren();
			if (grandchildren.isNotEmpty() ) { grandchildren.init().show(); }
		},		
		
		// returns both image and details cells for child
		cells: function(){ 
			return $('a[href='+this.href()+']').parent('td')
		},
		
		// returns true if both cells are linking to same page
		// used to find image cell for details cell or vice versa
		isTwin: function(cell){
			return this.href() == cell.child().href()
		}
				
	})
}


// Grandchildren div
var pageGrandchildren = function(page,container) {
	container.parent().grandchildren().showPage(page) 
	return false
}


$.fn.grandchildren = function(){
	return this.extend({
		init: function(){                              
			if (this.find('.viewAll').isEmpty()) {
				this.setWidth().insertViewAll();
				if (this.paginationIsNeeded()) { this.initPagination(); } 
			}
			
			return this
		},
		
		setWidth: function(){
			var width = this.parent().width();
			if($.browser.msie) { width = width + 16}
			this.css({width: width })
			return this
		}, 
		
		parentChild: function(){
			return this.parent().child()
		},
		
		paginationIsNeeded: function(){
			// return false if pagination is already initialized
			if (this.find('.pagination').isNotEmpty()) { return false}
			// otherwise check if it's needed for number of items
			return this.size() > this.rowsPerPage()
		},		
		
		initPagination: function(){			      
			// add div and show first page of items
			this.prepend(this.pagination()).showPage(0)
		},
		
		// returns div for pagination controls
		pagination: function(){
			return $('<div class="pagination">').pagination(this.size(), {
				items_per_page: this.rowsPerPage(),
				callback:pageGrandchildren,
				num_display_entries: 10,
				next_text: 'next',
				prev_text: 'prev' })
		},
		
		// inserts pagination footer link
		insertViewAll: function(){                       
			$('<a class="viewAll">And More...</a>').attr('href',this.parentChild().href()).appendTo(this);
		},
		
		// returns number of subsections in list
		size: function(){
			return this.find('li').size()
		},
		
		// each "row" of items equals one row for image, details, and spacer (3 total)
		rowsPerPage: function() {
			return 5 
		},
		
		// displays given page number, first page = 0
		showPage: function(page,container){    
			var rows_per_page = this.rowsPerPage();
			var start = page * rows_per_page;
			var end = start + rows_per_page;                               
			this.find('li').hide().slice(start,end).show()
		}		
		
	})
}

// --------------------------------------------------------------------------------------
// Main sections

$(document).ready(function(){
	
	Parents = $('#parents');
	Children = $('#main .children'); // table of children 
	Pagination = $('<div id="pagination">'); // div added to contain pagination controls
	
	// --------------------------------------------------------------------------------------
	// Div containing parents                                                       
	
	Parents.extend({
		init: function(){
			if(this.all().size() > 1) { this.personalize(); }
		},     
		
		// returns all parent divs
		all: function(){
			return this.find('.parent')
		},
		
		// reorders parents depending on referrer
		personalize: function(){
			var referringParent = this.referringParent();			
			if (referringParent) { referringParent.moveToTop() } 
		},
		
		// returns .parent div of link that referred user
		referringParent: function(){
			var referringLink = this.find('h2').referringLink();
			if (referringLink.isNotEmpty()) { return referringLink.parent().parent().pageParent();} else { return false }
		},
		
		// returns by-age div if it exists
		byAge: function(){
			return this.find('.by-age');
		}
		
	});	
	
	// --------------------------------------------------------------------------------------
	// Table for children                                                        
	
	Children.extend({
		init: function(){
			// init children
			this.find('.child').each(function(){
				$(this).child().init();
			});
			
			if (Pagination.isNeeded()) { Pagination.init(); }			
		},		 
		
		// returns all rows in table
		rows: function(){
			return this.find('tr')
		},
		
		// returns currently selected cells
		selected: function(){
			return this.find('.selected')
		},
		
		deselectOthers: function(selected){
			this.selected().each(function(){
				var otherSelected = $(this).child();
				if (!(selected.isTwin(otherSelected))) { otherSelected.deselect(); }
			});
		}
		  
		
	});   
	
	// --------------------------------------------------------------------------------------
	// Pagination conrols for Children table                                                

	Pagination.extend({
		init: function(){
			// setup div using pagination plugin
			this.pagination(Children.rows().size(), {
				items_per_page:this.rowsPerPage(),
				callback:Pagination.showPage}).insertAfter(Children);  
			// show first page of items	
			this.showPage(0);
		},
		
		// each "row" of items equals one row for image, details, and spacer (3 total)
		rowsPerPage: function() {
			return 12 
		},
		
		// displays given page number, first page = 0
		showPage: function(page){    
			var rows_per_page = Pagination.rowsPerPage();
			var start = page * rows_per_page;
			var end = start + rows_per_page;
			                                  
			Children.rows().hide().slice(start,end).show()
		},
		
		isNeeded: function(){
			return Children.rows().size > this.rowsPerPage()
		}
		
	});
	
	// --------------------------------------------------------------------------------------
	// Init
	
	Parents.init();
	Children.init();
	
	
}); 


                   
                                 
	
