/*
 * System76 main.js
 * Helper Classes & Whatnot
 * Created By: David Overcash - david@system76.com
 */

// Requires spin.js
$.fn.spin = function(opts) {
  this.each(function() {
    var $this = $(this),
        spinner = $this.data('spinner');

    if (spinner) spinner.stop();
    if (opts !== false) {
      opts = $.extend({color: $this.css('color')}, opts);
      spinner = new Spinner(opts).spin(this);
      $this.data('spinner', spinner);
    }
  });
  return this;
};

$(function() {
	
	// Subnavigation IE Fix
	$('div#subnavigation ul li:last-child').css('display','none');
	
	// Button
	$('a.green-button,a.blue-button,a.red-button').click(function() {
		
		$(this).blur();
		
	});
	
	// We update Current Mover to the active tab by default.
	if( $('div#subnavigation ul li.current') != undefined && $('div#subnavigation ul li.current').position() != undefined ) { 
		var currentMoverX = $('div#subnavigation ul li.current').position().left + parseInt( $('div#subnavigation ul li.current').width() / 2 );
		
		if( currentMoverX != undefined && currentMoverX > 0 ) {
			
			$('span#subnavigation-current-mover').css('left',currentMoverX+'px');
			
		}
	}
	
	// Listener for Ajax'd Subnavigation
	$('.subnavigation-ajax a').click(function() {
		
		// New Position Calculation
		
		var currentMoverX = $(this).parent().position().left + parseInt( $(this).parent().width() / 2 );
		
		if( $(this).css('display') == "block" ) {
			
			currentMoverX = $(this).position().left + parseInt( $(this).width() / 2 );
			
		}
		
		if( currentMoverX > 800 ) {
			
			currentMoverY = 4;
			
		} else {
			
			currentMoverY = 0;
			
		}
		
		// Re-Locate Current Mover
		if( $('span#subnavigation-current-mover').offset().left < 0 ) {
			
			// Just Show It
			$('span#subnavigation-current-mover').css('left',currentMoverX+'px').css('bottom',currentMoverY+'px');
			
		} else {
			
			// Animate
			$('span#subnavigation-current-mover').animate({
					'left':currentMoverX+'px',
					'bottom':currentMoverY+'px'
				},
				'fast'
				);
			
		}
		
		var nextBoxId = $(this).attr('rel');
		
		if( nextBoxId == undefined || nextBoxId.length == 0 ) {
			
			return true;
			
		}
		
		$('div.model-content-view:visible').slideUp(function() {
			
			$('div#model-content-'+nextBoxId).slideDown();
			
		});
		
		return false;
		
	});
	
	$('a.subnavigation-ajax').click(function() {
		
		// New Position Calculation
		var currentMoverX = $(this).parent().position().left + parseInt( $(this).parent().width() / 2 );
		
		if( $(this).css('display') == "block" ) {
			
			currentMoverX = $(this).position().left + parseInt( $(this).width() / 2 );
			
		}
		
		if( currentMoverX > 800 ) {
			
			currentMoverY = 4;
			
		} else {
			
			currentMoverY = 0;
			
		}
		
		// Re-Locate Current Mover
		if( $('span#subnavigation-current-mover').offset().left < 0 ) {
			
			// Just Show It
			$('span#subnavigation-current-mover').css('left',currentMoverX+'px').css('bottom',currentMoverY+'px');
			
		} else {
			
			// Animate
			$('span#subnavigation-current-mover').animate({
					'left':currentMoverX+'px',
					'bottom':currentMoverY+'px'
				},
				'fast'
				);
			
		}
		
		var nextBoxId = $(this).attr('rel');
		
		if( nextBoxId == undefined || nextBoxId.length == 0 ) {
			
			return true;
			
		}
		
		$('div.model-content-view:visible').slideUp(function() {
			
			$('div#model-content-'+nextBoxId).slideDown();
			
		});
		
		return false;
		
	});
	
	// Listener for Product Photo Images
	$('div.product-gallery-thumbnails a').click(function(e) {
		
		e.preventDefault();
		// console.log("Prevented");
		
		var imageId = $(this).attr('rel');
		
		if( ! $('div.product-gallery-image img#'+imageId).is(':visible') ) {
			
			$('div.product-gallery-thumbnails a').removeClass('current');
			
			$(this).addClass('current');
			
			$('div.product-gallery-image img:visible').fadeOut(150,function() {
				
				$('div.product-gallery-image img#'+imageId).fadeIn(250);
				
			});
			
		}
		
		return false;
		
	});
	
	// We update the price on the configuration page as soon as it loads.
	if( $('#configure-product-price-value') != undefined && $('#configure-product-price-value').html() != undefined ) {
		
		updateConfigurationPrice();
		
		// Price summary position listener.
		$(window).scroll(function() {
			
			var productPriceOffset = parseInt($('#configure-product-price').attr('rel'));
			var productPriceInitOffset = productPriceOffset + 40;
			
			if( $(this).scrollTop() >= productPriceInitOffset ) {
				
				$('#configure-product-price').css('top',($(this).scrollTop()-productPriceOffset)+'px');
				
			} else {
				
				$('#configure-product-price').css('top','40px');
				
			}
			
		});
		
	}
	
	// Listener for price on product config page.
	$('p.configure-product-option-set-option span.configure-product-option-set-option-name').click(function() {
		
		if( $(this).closest('p').hasClass('configure-product-option-disabled') ) {
			
			return;
			
		}
		
		var inputElement = $(this).parent().find('input');
		
		if( ! inputElement.is(':checked') ) {
			
			inputElement.attr('checked',true);
			
			var pTag = $(this).closest('p');
			pTag.animate({ backgroundColor: "#c8e4ff" }, 100,function() {
				pTag.animate({ backgroundColor: "#ffffff" }, 2000);
			});
			
			updateConfigurationPrice();
			
		} else {
			
			if( inputElement.is(':checkbox') ) {
				
				inputElement.attr('checked',false);
				
			}
			
			updateConfigurationPrice();
			
		}
		
	});
	
	$('p.configure-product-option-set-option input').click(function() {
		
		if( $(this).closest('p').hasClass('configure-product-option-disabled') ) {
			
			return;
			
		}
		
		var inputElement = $(this);
		
		if( inputElement.is(':checked') ) {
			
			var pTag = $(this).closest('p');
			pTag.animate({ backgroundColor: "#c8e4ff" }, 100,function() {
				pTag.animate({ backgroundColor: "#ffffff" }, 2000);
			});
			
			updateConfigurationPrice();
			
		}
		
	});
	
	// Listener for price on product config page.
	$('p.configure-product-option-set-option input').change(function() {
		
		updateConfigurationPrice();
		
	});
	
	// Add to cart listener
	$('a#add-product-to-cart-button').click(function() {
		
		// Check for all required fields ( i.e. all radio buttons ).
		var valid = true;
		
		$('.configure-product-option-set-options').each(function() {
			
			if( $(this).attr('rel') == "radio" ) {
				
				// Find selected option.
				if( $(this).find('input:checked') == undefined || $(this).find('input:checked').val() == undefined ) {
					
					valid = false;
					
				}
				
			} else {
				
				var product_option_component_ids = '';
				var product_option_id = 0;
				
				// Serialize values into hidden input.
				$(this).find('input:checked').each(function() {
					
					if( product_option_id == 0 ) {
						
						product_option_id = $(this).attr('rel');
						
					}
					
					product_option_component_ids = product_option_component_ids + $(this).val() + ',';
					
				});
				
				$('#product_option_'+product_option_id).val(product_option_component_ids);
				
			}
			
		});
		
		if( valid ) {
			
			// Submit
			$('form#add-product-to-cart-form').submit();
			
		} else {
			
			alert("Please select an option for all required fields.");
			
		}
		
	});
	
	// Support Page Helpers & Listeners
	$('div.support-links-column-item>a').click(function() {
		
		var item = $(this).closest('div');
		
		$('div.support-links-column-item-answer:visible').each(function() {
			
			if( item.find('div.support-links-column-item-answer').get(0) != $(this).get(0) ) {
				$(this).slideUp();
			}
			
		});
		
		item.find('div.support-links-column-item-answer').slideDown();
		
	});
	
	// My Account Accessories
	$('.myaccount-orders-accessories').each(function() {
		
		var order = $(this).attr('rel');
		
		updateAccessoriesPrice(order);
		
	});
	
	// Listener for My Account Accessories Options
	// Listener for price on product config page.
	$('p.myaccount-orders-accessories-set-option span.myaccount-orders-accessories-set-option-name').click(function() {
		
		var inputElement = $(this).parent().find('input');
		var pTag = $(this).closest('p');
		
		if( ! inputElement.is(':checked') ) {
			
			inputElement.attr('checked',true);
			
			pTag.animate({ backgroundColor: "#c8e4ff" }, 100,function() {
				pTag.animate({ backgroundColor: "#ffffff" }, 2000);
			});
			
			updateAccessoriesPrice(pTag.attr('rel'));
			
		} else {
			
			if( inputElement.is(':checkbox') ) {
				
				inputElement.attr('checked',false);
				
			}
			
			updateAccessoriesPrice(pTag.attr('rel'));
			
		}
		
	});
	
	$('p.myaccount-orders-accessories-set-option input').click(function() {
		
		var inputElement = $(this);
		var pTag = $(this).closest('p');
		
		if( inputElement.is(':checked') ) {
			
			pTag.animate({ backgroundColor: "#c8e4ff" }, 100,function() {
				pTag.animate({ backgroundColor: "#ffffff" }, 2000);
			});
			
			updateAccessoriesPrice(pTag.attr('rel'));
			
		} else {
			
			updateAccessoriesPrice(pTag.attr('rel'));
			
		}
		
	});
	
	// Listener for price on product config page.
	$('p.myaccount-orders-accessories-set-option input').change(function() {
		
		var inputElement = $(this);
		var pTag = $(this).closest('p');
		
		updateAccessoriesPrice(pTag.attr('rel'));
		
	});
	
	// Add Accessories Add to Cart Listener
	$('.myaccount-orders-accessories-addbutton').click(function(e) {
		
		e.preventDefault();
		
		// Check for all required fields ( i.e. all radio buttons ).
		var valid = true;
		
		$(this).closest('form').find('.myaccount-orders-accessories-set-options').each(function() {
			
			if( $(this).attr('rel') == "radio" ) {
				
				// Find selected option.
				if( $(this).find('input:checked') == undefined || $(this).find('input:checked').val() == undefined ) {
					
					valid = false;
					
				}
				
			} else {
				
				var product_option_component_ids = '';
				var product_option_id = 0;
				
				// Serialize values into hidden input.
				$(this).find('input:checked').each(function() {
					
					if( product_option_id == 0 ) {
						
						product_option_id = $(this).attr('rel');
						
					}
					
					product_option_component_ids = product_option_component_ids + $(this).val() + ',';
					
				});
				
				$('#product_option_'+product_option_id).val(product_option_component_ids);
				
			}
			
		});
		
		if( valid ) {
			
			// Submit
			$(this).closest('form').submit();
			
		} else {
			
			alert("Please select an option for all required fields.");
			
		}
		
	});
	
});

function updateConfigurationPrice() {
	
	var basePrice = parseFloat($('#configure-product-base-price').val());
	
	// Loop each option, update the basePrice, update all options.
	// Also disable/enable SKUs
	$('.configure-product-option-set-options').each(function() {
		
		if( $(this).attr('rel') == "radio" ) {
			
			// Find selected option.
			var selectedOption = $(this).find('input:checked');
			var priceChange = parseFloat(selectedOption.parent().find('span.configure-product-option-set-option-price').attr('rel'));
			
			basePrice += priceChange;
			
			// Update all options.
			$(this).find('.configure-product-option-set-option').each(function() {
				
				var optionPriceSpan = $(this).find('span.configure-product-option-set-option-price');
				var optionPriceChange = parseFloat(optionPriceSpan.attr('rel'));
				
				var optionPriceDifference = priceChange - optionPriceChange;
				var optionPriceSign = "-";
				if( optionPriceDifference < 0 ) {
					
					optionPriceSign = "+";
					
				}
				
				// Update Price Span
				if( optionPriceDifference == 0 ) {
					
					optionPriceSpan.html('');
					
				} else {
					
					optionPriceSpan.html('( '+optionPriceSign+' $'+Math.abs(optionPriceDifference).toFixed(2)+' )');
					
				}
				
			});
			
			// Disable incompatible SKUs
			var incompatible = $('#product_option_component-'+selectedOption.val()+'-incompatible_sku_list').val();
			
			var selectedDisabled = false;
			
			if( incompatible && incompatible.length > 0 ) {
				
				incompatibleSkus = incompatible.split(',');
				
				for( sku in incompatibleSkus ) {
					
					$('p.configure-product-option-sku-'+incompatibleSkus[sku]).each(function() {
						
						$(this).addClass('configure-product-option-disabled');
						$(this).find('input').attr('disabled','disabled');
						
						if( $(this).find('input').is(':checked') ) {
							
							$(this).find('input').attr('checked',false);
							
							// Enable a default option and alert user.
							selectedDisabled = true;
							
							var pTag = $(this);
							
							pTag.animate({ backgroundColor: "#ff4040" }, 100,function() {
								pTag.animate({ backgroundColor: "#ffffff" }, 5000);
							});
							
						}
						
					});
					
				}
				
			}
			
			// Enable compatible SKUs
			var compatible = $('#product_option_component-'+selectedOption.val()+'-compatible_sku_list').val();
			
			if( compatible && compatible.length > 0 ) {
				
				compatibleSkus = compatible.split(',');
				
				for( sku in compatibleSkus ) {
					
					$('p.configure-product-option-sku-'+compatibleSkus[sku]).each(function() {
						
						$(this).removeClass('configure-product-option-disabled');
						$(this).find('input').attr('disabled',false);
						
						if( selectedDisabled ) {
							
							$(this).find('input').attr('checked','checked');
							
							var componentTitle = $(this).find('span.configure-product-option-set-option-name').text();
							
							alert("One of your selections was made incompatible with the current configuration. To maintain compatibility, we've selected the following option:\n"+componentTitle);
							
							selectedDisabled = false;
							
						}
						
					});
					
				}
				
			}
				
		} else {
			
			$(this).find('.configure-product-option-set-option').each(function() {
				
				var inputElement = $(this).find('input');
				var priceSpan = $(this).find('span.configure-product-option-set-option-price');
				var priceChange = parseFloat(priceSpan.attr('rel'));
				
				if( inputElement.is(':checked') ) {
					
					basePrice += priceChange;
					priceSpan.html('');
					
				} else {
					
					var priceSign = "+";
					
					priceSpan.html('( '+priceSign+' $'+priceChange+' )');
					
				}
				
				// Disable incompatible SKUs
				var incompatible = $('#product_option_component-'+inputElement.val()+'-incompatible_sku_list').val();
				
				if( incompatible && incompatible.length > 0 ) {
					
					incompatibleSkus = incompatible.split(',');
					
					for( sku in incompatibleSkus ) {
						
						$('p.configure-product-option-sku-'+incompatibleSkus[sku]).each(function() {
							
							$(this).addClass('configure-product-option-disabled');
							$(this).find('input').attr('disabled','disabled');
							
							if( $(this).find('input').is(':checked') ) {
								
								$(this).find('input').attr('checked',false);
								
								var pTag = $(this);
								
								pTag.animate({ backgroundColor: "#ff4040" }, 100,function() {
									pTag.animate({ backgroundColor: "#ffffff" }, 5000);
								});
								
							}
							
						});
						
					}
					
				}
				
				// Enable compatible SKUs
				var compatible = $('#product_option_component-'+inputElement.val()+'-compatible_sku_list').val();
				
				if( compatible && compatible.length > 0 ) {
					
					compatibleSkus = compatible.split(',');
					
					for( sku in compatibleSkus ) {
						
						$('p.configure-product-option-sku-'+sku).each(function() {
							
							$(this).removeClass('configure-product-option-disabled');
							$(this).find('input').attr('disabled',false);
							
							var componentTitle = $(this).find('span.configure-product-option-set-option-name').text();
							
							alert("One of your selections was made incompatible with the current configuration. To maintain compatibility, we've selected the following option:\n"+componentTitle);
							
							selectedDisabled = false;
							
						});
						
					}
					
				}
				
			});
			
		}
		
	});
	
	$('#configure-product-price-value').html(basePrice.toFixed(2));
	
}

function updateAccessoriesPrice(order) {
	
	var basePrice = 0.00;
	
	$('p.accessories-order-'+order).each(function() {
		
		var inputElement = $(this).find('input');
		var priceSpan = $(this).find('span.myaccount-orders-accessories-set-option-price');
		var priceChange = parseFloat(priceSpan.attr('rel'));
		
		if( inputElement.is(':checked') ) {
			
			basePrice += priceChange;
			priceSpan.html('');
			
		} else {
			
			var priceSign = "+";
			
			priceSpan.html('( '+priceSign+' $'+priceChange+' )');
			
		}
		
	});
	
	$('#accessories-price-'+order).html(basePrice.toFixed(2));
	
}

