$(document).ready(function() {

	setup_shop_sidebar();
	
	//AddToCart functionality for sites other than shop
	//Needs to be maintained, unintuitive attempt to wrap and redefine cart66 add to cart button	
	$('div.cart_redirect').each(function(){
		var redirect = $(this).find('input.cart_redirect_page');
		var text = $(this).find('input.cart_text_value');
		$(this).find('form.Cart66CartButton').each(function() {
			var loc = document.createElement('input');
			if(!redirect.val()) {
				redirect.val('store/view');
			}
			loc.type = redirect.attr('type');
			loc.value = redirect.val();
			loc.name = redirect.attr('name');
			this.appendChild(loc);
		});	
		if(text && text.val()) {
			$(this).find('form.Cart66CartButton input:[type=submit]').each(function() {
				$(this).val(text.val());
			});
		}
	});
	
	//Make cart form work as the checkout form
	(function() {
		var show_loading = function() {
			$('#cart_loading').fadeIn(200);
		};
		var hide_loading = function() {
			setTimeout(function(){ 
				$('#cart_loading').fadeOut(200);
			},200);
		};
		
		if(!$('#Cart66CartForm').length) { 
			$('#disabled_paypal').hide();
			$('#disabled_paypal_message').hide();
			hide_loading(); 
			return; 
		}
		
		var _first_load = true;
		var _changed_shipping = false;
		
		//Run our onload tweaks on the cart66 form.
		var attach_helpers = function() { 
			var frm = $('#Cart66CartForm');
			$('#Cart66CheckoutButton').hide();
			if(!frm.length) { 
				$('#paypal_checkout').hide();
				$('#disabled_paypal_message').hide();
				return false; 
			}
			//Add a select/blank option to the dropdown and detect if its a first run state or we can show paypal 
			frm.find('#shipping_method_id').each(function(){
				var opt = document.createElement('OPTION');
				opt.value = '';
				opt.innerHTML = 'Please Select Location';
				opt.style.color = '#990000';
				this.insertBefore(opt,this.firstChild);
				
				if(_first_load || !_changed_shipping) {
					this.selectedIndex = 0;
				}
				$(this).change(function(){ 
					if(this.selectedIndex != 0) {
						_changed_shipping = true;
					}
				});
				//If the user has made a selection then we can show the paypal button.
				if(this.selectedIndex != 0 && _changed_shipping) {
					$('#disabled_paypal').hide();
					$('#disabled_paypal_message').hide();
				} 
			});
			//remove clunky submit/update buttons
			frm.find('input[type=submit]').hide();
			
			//Capture events and relay through ajax
			var _tmOut = null;
			frm.find('a').click(function(){
				submit_link.call(this);
				return false;
			});
			frm.find('input[type=text]').keypress(function(){ 
				if(_tmOut) {
					clearTimeout(_tmOut);
				}
				_tmOut = setTimeout(function(){ submit_form.call(frm[0]);},500);
			});
			frm.find('#couponCode input').unbind('keypress');;
			frm.find('.Cart66ApplyCouponButton').show();
			
			var _tmOut = null;
			frm[0].onsubmit = function(){
				submit_form.call(this);
				return false;
			};
			
			_first_load = false;
		};	
		//Run on success of ajax
		var _refresh_form = function(ret_obj,callback) {
			 $('#cart_holder').fadeOut(100,function(){ 
				  $('#cart_holder').html(ret_obj);
				  attach_helpers();
				  $('#cart_holder').fadeIn(100,callback);
			  });
		};
		
		var submit_link = function() { 
			show_loading();
			$.ajax({url: $(this).attr('href'),
				   success: function(ret_obj,status){
					   _refresh_form(ret_obj,hide_loading); 
					}
			});
		};
		
		var submit_form = function() { 
			show_loading();
			$.ajax({
				  type: 'POST',	
				  data: $(this).serialize(),
				  success: function(ret_obj,status){
					  _refresh_form(ret_obj,hide_loading);
				  }
				});
		};
		
		attach_helpers();
		hide_loading();
	}());
	

	
	//product list display
	(function() { 
		var _more_increment = 3;
		var _display_amount = 0;
		var _min_display_amount = 0;
		var _max_display_amount = 0;
		
		var more_but = $('#more_products');
		var less_but = $('#less_products');
		
		//Use the inital hidden amount to define how many to show
		var set_product_amount = function() {
			$('#main-section article').each(function() {
				$(this).css('display','block');
				if(!$(this).hasClass('hide')) {
					_display_amount++;
				}
				_max_display_amount++;
			});
			_min_display_amount = _display_amount; 
		};
		set_product_amount();
		
		//Hide products beyond _display_amount use class hidden to avoid clash with the filter.
		var refresh_product_list = function() {
			var count = 0;
			
			//Only show more if we hide some
			more_but.css('display','none');
			$('#main-section article').each(function() {
				if($(this).css('display') == 'block') {
					count++;
				}
				if(count > _display_amount && count > _min_display_amount) {
					$(this).addClass('hide');
					more_but.css('display','inline-block');
				} else {
					$(this).removeClass('hide');
				}
			});
			//If we have displayed less than is possible update the display count
			_display_amount = (count < _display_amount) ? count : _display_amount;
			//Determine need for less button.
			if(_display_amount > _min_display_amount) {
				less_but.css('display','inline-block');
			} else {
				less_but.css('display','none');
			}
		};
		
		more_but.click(function() { 
			_display_amount += _more_increment;
			if(_display_amount >= _max_display_amount) {
				_display_amount = _max_display_amount;
			}
			refresh_product_list();
			return false;
		});
		
		less_but.click(function() { 
			_display_amount -= _more_increment;
			if(_display_amount < _min_display_amount) {
				_display_amount = _min_display_amount;
			}
			refresh_product_list();
			return false;
		});
		
		
		//sort/filter products based on class names of categories.
		var _product_list = [];
		$('#product-types li input').change(function() {
			var found_products = 0;
			if($(this).attr('checked')) {
				_product_list.push($(this).val());
			} else {
				for(var x in _product_list) {
					if(_product_list[x] == $(this).val()) {
						_product_list.splice(x,1);
					}
				}
			}
			if(_product_list.length == 0) {
				$('#main-section').find('article').fadeIn(150);
				found_products = _max_display_amount;
			} else {
				
				//Most recent click input should be at end of product list so appear at start of element.
				for(var i = 0; i < _product_list.length; i++) {
						$('#main-section').find('.'+_product_list[i]).each(function(){ 
							var el = this;
							var par_el = el.parentNode;
							var move_to_top = function() {
								par_el.removeChild(el);
								var first = $('#main-section').find('article');
								if(first.length > 0) {
									par_el.insertBefore(el,first[0]);
								} else {
									par_el.appendChild(el);
								}
							};
							if(!el.moved) {
								el.moved = true;
								found_products++;
							}
							move_to_top();
						});
				}
				$('#main-section').find('article').css('display','none');
			
				//Animate them all in at the same time if we can
				$('#main-section article:[moved=true]').fadeIn(150);
				//Remove the temporary tag we've added
				$('#main-section article:[moved=true]').each(function() {
					this.moved = false;
				});
			}//end if product list is empty
			
			//Update the count
			$('#count-types').fadeOut(150,function(){ 
				$('#count-types').html(found_products+'/'+_max_display_amount);
				$(this).fadeIn(150);
			});
			
			//hide all extra products
			refresh_product_list();
		});
	}()); // End product list display
	
	
	
	//Read More overlay
	$('a[rel^="#more"]').each(function() { 
			$(this).overlay({  
				mask : '#000000',	
				closeOnClick : true,
				closeOnEsc : true
			});
			//Custom modal as mask currently doesn't work
			var ol = $(this).overlay();
			ol.onBeforeLoad(function(){
				$('#modal').unbind('click');
				$('#modal').bind('click',function() { ol.close(); });
				$('#modal').fadeIn(200); 
			});
			ol.onClose(function(){ $('#modal').fadeOut(200); });
			
			ol.getOverlay().find('.close').click(function() {
					ol.close();
					return false;
			});
			ol.getOverlay().find('.Cart66CartButton input:[type=submit]').click(function() {
				var close = function(){ ol.close(); };
				setTimeout(close,500);
			}); 
		});
}); 

var setup_shop_sidebar = function(){

	var _inaction = false;
	//AddToCart functionality
	//Needs to be maintained, attempts to capture all addToCart button on the shop. Submit forms built by cart66
	$('body.page-template-shop-php .Cart66CartButton').unbind('submit');
	
	$('body.page-template-shop-php .Cart66CartButton').bind('submit',function() {
		if(_inaction) { return false; }
		_inaction = true;
		var frm = $(this);
		var action = frm.attr('action');
		var button = frm.find('input:[type=submit]');
		var but_orig_val = button.val();
		button.val('Adding...');
		//Submit form via ajax and get a new sidebar markup as return.
		$.ajax({
			url : action,
			type: frm.attr('method'),
			data: frm.serialize(),
			success : function(ret){
				if(ret) {
					//Replace the entire sidebar with this return.
					$('#dynamic_sidebar').html(ret);
				}
				var cart = $('#Cart66CartForm');
				var tm = 400;
				var flash = function(count) {
					count--;
					complete = count > 0 ? function(){ flash(count); } : function(){};  
					cart.fadeOut(tm,function(){ cart.fadeIn(tm,complete); });
				};
				flash(1);
				
				//if found propogate updated cart items count to where required
				var count = $('#cart_items').val();
				if(count) {
					//not ideal relise on pattern of ({item number}) within the text to work
					var str = $('.header-cart').html();
					var start = str.substr(0,str.indexOf('(') + 1);
					var end = str.substr(str.indexOf(')'));
					$('.header-cart').html(start+count+end);
				}
			},
			complete : function() {
				button.val('Added');
				button.addClass('green');
				var reset_but = function(){ 
					button.val(but_orig_val);
					button.removeClass('green');
				};
				setTimeout(reset_but,1250);
				_inaction = false;
				
				setup_shop_sidebar();
			}
		});
		return false;	
	});	

	//All add to cart buttons, Replace quantity with select
	$('.Cart66CartButton input:[name=item_quantity]').each(function() {
		if(this.type == 'hidden') { return; }
		
		var el = document.createElement('SELECT');
		var el_id = this.id;
		var el_name = this.name;
		for(var x = 1; x <= 25; x++) {
			var op = document.createElement('OPTION');
			op.value = x;
			op.innerHTML = x;
			if(x == this.value) {
				op.selected = 'selected';
			}
			el.appendChild(op);
		}
		//Remove label if we can find it.
		var holder = this.parentNode;
		var lbl = $(holder).find('label:[for='+this.id+']');
		if(lbl.length > 0) {
			holder.removeChild(lbl[0]);
		}
		holder.insertBefore(el,this);
		holder.removeChild(this);
		
		el.id = el_id;
		el.name = el_name;
	});

};
