var Modal, Images, Buy, BuyTogether, RelatedItems, Parents;

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

// Thumbnail link
$.fn.thumbnail = function() {
	return this.extend({
		enlarge: function(){  
			this.addClass('clicked');			
			Modal.showImages();				         			
			this.removeClass('clicked');
		}                        
	});
};  


// Option block
$.fn.option = function(){  
	
	var isIncompleteFunction;	
	if (this.is('.radio')) {
		isIncompleteFunction = function() {
			return this.find(':checked').isEmpty()
		}
	} else {
		isIncompleteFunction = function() {
			return this.find('select').val() == ''
		}
	}
	
	return this.extend({
		isIncomplete: isIncompleteFunction,
		record: function(choice){
			this.removeClass('highlight')
			
			if (this.is('.radio')) {
				this.find('.selected').removeClass('selected');
				
				choice.orParent('.choice').addClass('selected');
			}
		}
	})
};   

// Item in BuyTogether
$.fn.kitItem = function(){
	return this.extend({
		price: function(){
			return parseFloat(this.find('.price').text().slice(1))
		},
		
		toggleSelection: function(){
			this.toggleClass('selected');
			this.image().toggle(); 
			BuyTogether.update(); 
		},
		
		name: function(){
			return this.find('.name').text()
		},
		
		image: function(){
			return BuyTogether.find('img').eq(this.position())
		},
		
		position: function(){
			return $.inArray(this.name(),BuyTogether.itemNames())
		}
		
	})
};




$(document).ready(function(){
	
	// --------------------------------------------------------------------------
	// name elements
	// -------------------------------------------------------------------------- 
	
	Page = $('#page')
  Modal = $('<div id="modal">');
	Images = $('#images');                	
	Buy = $('#buy');                      	
	BuyTogether = $('#buy_together');
	RelatedItems = $('#relatedItems');
	Parents = $('#related-pages .parent');
	
	
	Page.extend({
		// ripped from Facebox
		amountScrolledDown: function(attribute){
			// sane browsers
		  if (self.pageYOffset) { return self.pageYOffset; }
		  // Explorer 6 Strict
			if (document.documentElement && document.documentElement.scrollTop) { return document.documentElement.scrollTop }
			// all other Explorers
		  if (document.body) { return document.body.scrollTop }
		},
		
		// ripped from Facebox
		height: function(attribute){  
			// sane browsers
			if (self.innerHeight) { return self.innerHeight }
			// Explorer 6 Strict Mode 
			if (document.documentElement && document.documentElement.clientHeight) { return document.documentElement.clientHeight }
			// other Explorers
			if (document.body) { return document.body.clientHeight}
		}               
	});
	
	
	// --------------------------------------------------------------------------
	// Modal Window
	
	Modal.extend({
		init: function(){   
			this.initNav();
			this.jqm({overlayClass: 'curtain', closeClass: 'close'});			  
			$('<div id="modalContent">').appendTo(this); 
			this.appendTo($('#page')); 
		}, 
		
		initNav: function(){
			var nav = $('<div id="modalNav">');
		  $('<a href="#" class="close"><img src="http://lib.brandson-sale.com/images/modal/close.gif"></a>').appendTo(nav);
			nav.appendTo(this);
		},  
    
		content: function(){
			return $('#modalContent'); 
		},		
		
		show: function(){
			this.jqmShow();
      this.center();
		}, 
		
		center: function(){
			this.css({  
        top:  Page.amountScrolledDown() + (Page.height() / 10),
        left:  (Page.width() - this.width()) / 2 - 30
      })
		}
		
	});  
	
	// --------------------------------------------------------------------------
	// Modal extension to show clicked images                                    
	
	Modal.showImages = function() {
	
		var content = this.content().extend({                 
		
			cloneImages: function(){
				var images = Images.clone();  
				images.find('.tip,.main').remove(); 
				return images
			},
		
		
			enlarge: function(){
				return $('<img>').attr('src',clicked.attr('href')).addClass('main')
			},
		
			watchClicks: function(){
				this.click(function(event){
					clicked = $(event.target);            
					if (clicked.is('img')) { clicked = clicked.parent(); } 
					images = clicked.parent();
					if (clicked.hasClass('thumbnail')) {
	        	images.find('.clicked').removeClass('clicked');
						images.find('.main').attr('src',clicked.attr('href'));
						clicked.addClass('clicked');                          
						Modal.center();
						return false
					}                          
				});
			}
		}); 
	
		content.empty();
		var images = content.cloneImages();  
		var clicked = images.find('.clicked');
		content.enlarge(clicked).prependTo(images);
		content.append(images);
		content.watchClicks();  
		this.show();
	
	} 
	
	// --------------------------------------------------------------------------
	// Images block
	
	Images.extend({
		init: function(attribute){
			this.click(function(event){
				clicked = $(event.target)
				if (clicked.is('img')) { clicked = clicked.parent(); }
				switch(clicked.attr('class'))	{
					case 'main' :
						Images.find('.thumbnail.enlarged').thumbnail().enlarge();
						return false
					case 'thumbnail' :
						clicked.thumbnail().enlarge();
						return false			
				}  
			});
		}
	});
	
	// --------------------------------------------------------------------------
	// Main add to cart area

	Buy.extend({ 
		
		init: function(){ 
			this.recordChoices(); // records choices saved by browser	
			this.watchClicks();
			this.watchSelectChanges();
			this.watchButton();  
			this.watchSubmit();
		},
		
		watchClicks: function(){
			this.click(function(event){
				clicked = $(event.target)
				// radio options
				if (clicked.is("input[type='radio']")) { 
					clicked.parent().parent().option().record(clicked); 
					return true
				} 
				
				if (clicked.is('.choice')) {                   
					var radio = clicked.find("input[type='radio']");
					radio.click().parent().parent().option().record(radio);
					return true
				}
				
			});
		},  
		
		// record changes to select boxes
		watchSelectChanges: function(){
			this.find(".select select").change(function(){
				var choice = $(this)
				choice.parent().option().record(choice)
			});
		},
		
		watchSubmit: function(){
			this.submit(function(){
				if (Buy.isIncomplete()) { Buy.highlightIncompleteOptions(); return false }
			});
		},
		
		watchButton: function(){
			this.button().hover(function() {
				if (Buy.isIncomplete()) { Buy.disableButton();}
	    }, function() {             
				Buy.enableButton()
				return false  
	    });
		},  
		
		isIncomplete: function(){
			var incomplete = false;		
			this.find('.choices').each(function(){
				if ($(this).option().isIncomplete()) { incomplete = true}
			});                                                
			return incomplete
		},  
		
		incompleteOptions: function(){
			return this.find('.choices').map(function(){
				var option = $(this).option();
				if (option.isIncomplete()) { return option}
			})
		},
		
		highlightIncompleteOptions: function(){
			this.incompleteOptions().each(function(){
				$(this).addClass('highlight')
			})
		},    
		
		button: function(){
			return this.find('.add_to_cart')
		},    
		
		disableButton: function(){     
			this.button().addClass('disabled').next('.error').show();
		},
		
		enableButton: function(){
			this.button().removeClass('disabled').next('.error').hide();
		},
		
		// finds all selected choices and accessories
		recordChoices: function() {
			this.find('.radio :checked').parent('.choice').addClass('selected');
		}
		           
	});
	
	// --------------------------------------------------------------------------
	// Buy Together
	
	BuyTogether.extend({
		init: function(){			
			this.selectAll();			
			this.updateTotal();	  
			this.watchButton();			
			this.watchClicks();
			this.watchSubmit();
		},  
		
		watchClicks: function(){
			this.click(function(event) {
				clicked = $(event.target); 
				// checkboxes
				if (clicked.is('input[type=checkbox]')) { clicked.parent('.item').kitItem().toggleSelection(); }
			});
		}, 
		
		watchButton: function(){
			this.button().hover(function() {                            
				if (BuyTogether.isIncomplete()) { BuyTogether.disableButton(); }
	    }, function() {             
				// on mouse out
				BuyTogether.enableButton();
				return false  
	    });
		}, 
		
		watchSubmit: function(){
			this.submit(function(){
				if (BuyTogether.isIncomplete()) { return false }
			});
		},   
		
		selectAll: function(){
			this.find('.item').addClass('selected').each(function() {
				$(this).find('input').not(':checked').click();
			});
		},
		        
		button: function(){
			return this.find('.addToCart')
		},
		
		disableButton: function(){
			this.button().addClass('disabled').next('.error').addClass('visible');
		},
		
		enableButton: function(){
			this.button().removeClass('disabled').next('.error').removeClass('visible');
		},
		
		isIncomplete: function(){ 
			var incomplete = false;
			this.find('.selected select').each(function(){
				if ($(this).val() == '') { incomplete = true }
			});                                                  
			return incomplete
		},              
		
		update: function(){
			this.updateTotal();
			this.insertPlusSigns();
		},		
		
		// updates all quanity specific pieces 
		updateTotal: function(){
			var quantity = this.selectedItems().size();
			// hide total line and stop processing if empty selection
			if (quantity == 0) {
				return this.find('.total').hide()
			} else {
				this.find('.total:hidden').show();
			}			
			// update message above button
      this.find('.total .quantity').text(this.messageFor(quantity));		
			// recalculate total	
			this.find('.total .price').text('$' + this.calculateTotal());
			// make button quantity specific
			this.button().attr('src',this.buttonFor(quantity));
		},
		
		// returns path to quantity specific button
		buttonFor: function(quantity){
			var filename;
			switch(quantity) {
				case 1: filename = 'one'; break;
				case 2: filename = 'both'; break;
				case 3: filename = 'three'; break;
				default: filename = 'all';
			}
			
			return this.button().attr('src').replace(/add-to-cart\/.*[^\.\/]\.gif/,'add-to-cart/' + filename + '.gif')
			 
		}, 
		
		// returns quantity specific text for message above button
		messageFor: function(quantity){
			var message;
			switch(quantity) {
				case 1: return 'this item '; 
				case 2: return 'both ';
				default: return 'all ' + quantity + ' ';
			}
		},
		
		// returns total price as float
		calculateTotal: function(){
			var total = 0.00;
			this.selectedItems().each(function(i){
				total += $(this).kitItem().price()
			});     
			
			return Math.round(total*100)/100
		},
		
		// inserts plus signs between items
		insertPlusSigns: function(){
			this.find('.plus').remove();
			this.find('img:visible').not(':first').each(function(){
				$('<span class="plus">+</span>').insertBefore($(this))
			});
		}, 
		
		selectedItems: function(){
			return this.find('.selected')
		},
		
		itemNames: function() {
			return this.find('.item').map(function(){
				return $(this).kitItem().name();
			});
		}
		
	});
	
	RelatedItems.extend({
		init: function(){
			this.find('.item .image img').hover(function(event) {
				$(event.target).parent().next('.name').addClass('active')
	    }, function(event) {             
				$(event.target).parent().next('.name').removeClass('active')
				return false  
	    });
		},
		
		items: function(){
			return this.find('.item')
		}
	});  
	
	
	
	
	// --------------------------------------------------------------------------
	// Init elements
	
	Modal.init();
	Images.init();
	Buy.init();
	BuyTogether.init();  
	RelatedItems.init();
	
}); 
