/* Copyright IntuitSolutions 2008 */

$(function() {
	
	$('#dialog').dialog({
		modal: true,
		autoOpen: false,
		width: 300,
		height: 150,
		overlay: {
			opacity: 0.6,
			backgroundColor: '#222'
		},
		buttons: {
			"Get Back To Shopping!" : function() {
				$(this).dialog('close');
			}
		}
	});
	
	$('form[name=cartadd] :input[name^=attributevalue_]').change(function() {

		// Keep all the currently selected attributes in here...
		options = [];
		
		// Go through all the attribute values in the cartadd form and keep them in the options array...
		$('form[name=cartadd] :input[name^=attributevalue_]').each(function() {
			if( $(this).attr('type') == 'radio' ) {
				if( $(this).is(':checked') ) {
					options.push( $(this).val() );
				}
			} else {
				options.push( $(this).val() || 'All' );
			}
		});
		
		// Go through each attribute 	
		for ( var i in attributes ) {
			var update = false;
			for( var j in attributes[i].attributes ) {
				update = ( attributes[i].attributes[j] == "All" ) ? true : ( attributes[i].attributes[j] == options[j] ) ? true : false ;
				if ( !update ) { break; }
			}
			if ( update ) {
				if( attributes[i].quantity === 0 ) {
					$('#add-to-cart-button').attr( { src: $('#disabled-buyit').attr('value'), disabled: 'disabled' } );
					$('#dialog').data('title.dialog', 'Sorry, Out Of Stock!');
					$('#dialog').html("We're currently out of stock of this product with the selected options.");
					$('#dialog').dialog('open');
					break;
				} else {
					$('#add-to-cart-button').attr('src', $('#enabled-buyit').attr('value')).removeAttr('disabled');
					break;
				}
			}
		}
		
	});
	
	$('form[name=cartadd]').submit(function() {
		
		errors = [];

		$(this).find(":input[name^='attributevalue_']").each(function(){
			field = $(this).parents('tr').find('th').text();
			if( $(this).val().match(/^\s*$/) ) {
				errors.push($(this).attr('class'));
			}
		});
		
		if(errors.length > 0) {
			$('#dialog').data('title.dialog', 'Plese Choose All Your Options!');
			$('#dialog').html("Please select all of the product options in order to add it to the cart.");
			$('#dialog').dialog('open');
			return false
		}
		
	})
	
});

