/* Copyright IntuitSolutions 2008 */

$(function() {

	$('#attributes ul.options li').click(function() {
		
		// Get the attribute we're changing...
		attribute = $(this).parent('ul').attr('id');
		// Style the selected attribute...
		$(this).siblings().removeClass('selected');
		// Add the class "selected" to the proper <li>
		$(this).addClass('selected');
		
		$('#quantity-notice').hide();
		
		options = [];
		
		$('#attributes ul.options li.selected').each(function() { 
			options.push( $.trim($(this).text()) || 'All' ); 
		});

		// Go through each attribute in the array...
		for ( var i in attributes ) {
			// We'll need this outside of the inner for loop.
			var update = false;
			for( var j in attributes[i].attributes ) {
				// If the current attributes attributes match the current option or it's value is "All", we're good.. if not, break out of loop...
				update = ( attributes[i].attributes[j] == "All" ) ? true : ( attributes[i].attributes[j] == options[j] ) ? true : false ;
				if ( !update ) { break; }
			}
			// If update is true, log it and break out of current loop...
			if ( update ) {
				attribute = attributes[i];
				if(attribute.quantity == 0) {
				    $('#add-to-cart-button').attr('disabled', true);
					$('#quantity-notice').text('The options you\'ve selected are currently out of stock').fadeIn('slow');
				} else {
				    $('#add-to-cart-button').attr('disabled', false);
				    $('#add-to-cart-button').fadeIn('slow');
				}
			}
		}
	});	
	

	// When the form is submitted we get all the selected attributes and append them to the form...
	$('form[name=cartadd]').submit(function(e) {
		
		form = $(this);
		errors =[];
		$(this).find('p.errors').remove();
			
		$('#attributes ul.options').each(function() {
			
			$(this).parent('li').removeClass('error');
			
			if( $(this).find('li.selected').length === 0 ) {
				errors.push($(this).attr('id').replace('/^attr_/'));
				$(this).parent('li').addClass('error');
			}
			
		});
		
		if(errors.length > 0) {
			form.append('<p class="errors">Please be sure to choose all of your options!</p>');
			e.preventDefault();
		} else {	
			// Append all selected attributes to the form...
			$('#attributes ul.options li.selected').each(function(i) {
				form.append('<input class="attribute" type="hidden" value="' + $.trim($(this).text()) + '" name="attributevalue_' + ( i + 1 ) + '">');
			});
		}
		
	});

});


