jQuery(document).ready(function() {
	bindChangeEventListener();
});

jQuery(document).ajaxComplete(function(e, xhr, settings) {
	bindChangeEventListener();
});

// Global variables
var g_SizeSelectText = "";

function bindChangeEventListener()
{
	// Initialisation
	jQuery('.product-shop form').each( 
		function (frm)
		{
			if (jQuery("#ajaxProductType", jQuery(this)).val() != "simple") {
				jQuery("select.super-attribute-select, select.bundle-option-select", jQuery(this)).each( 
						function () {
							// Add event listeners to the select dropdowns so that we can enable/disable the AddToBasket button
							jQuery(this).change(function() { changeEventListener(); });

							// Reset the select dropdowns
							//jQuery(this).val(0);		
							// make the first option as selected /and clear the others as well, just in case/
							jQuery(this).removeAttr('selected').find("option:first").attr('selected','selected');
						}
					);				
				//jQuery("select#qty", jQuery(this)).val(0);				
				jQuery("select#qty").removeAttr('selected').find("option:first").attr('selected','selected');
				// Correctly show or hide the disabled button
				changeEventListener();	
			}
		}			
	);
}

function changeEventListener() {
	// Find all (no matter how many there are) super attribute selects
	// and see if they are selected
	
	jQuery('.product-shop form').each( 
			function (frm)
			{	
				var blnAllAreSelected = true;
				var form = jQuery(this);				
//alert('form called??');

				jQuery("select.super-attribute-select, select.bundle-option-select", form).each( 
						function(sel){

//				jQuery("select.super-attribute-select").each(function(){
						
//alert('select present');										
							// If there is only one value in the dropdown, remove the choose option, and disable the dropdown
							// Note that there is also the choose option, so we are looking for 2 options.
							//var options = jQuery(this).attr('options'); 
							
							if( jQuery(this).find('option').length == 2 )
							{
								// remove the choose option
								jQuery(this).find('option:first').remove();

								// add a class so we can change the look of the select
								jQuery(this).addClass('single-option');
								
								// Trigger event handlers so that the out of stock code runs
								if(undefined !== window.spConfig){
									if (spConfig[form.attr('id')])
									{
										spConfig[form.attr('id')].configureElement(this);
									}
									else
									{
										spConfig.configureElement(this);
									}
								}
								jQuery(this).change();
							}
							// Now see if this box has an option selected		
							if(!(jQuery(this).val() > 0)){ 
								blnAllAreSelected = false;					
							}				
						}
					);
				
				// Enable/disable the AddToBasket button	
				if (blnAllAreSelected) {
				    jQuery("#btnAjaxAddToBasket", form).show();
				    jQuery("#btnAjaxAddingToBasket", form).hide();
				    jQuery("#btnAjaxDisabledAddToBasket", form).hide();
				} else {
				    jQuery("#btnAjaxAddToBasket", form).hide();
				    jQuery("#btnAjaxAddingToBasket", form).hide();
				    jQuery("#btnAjaxDisabledAddToBasket", form).show();
				}
			}
		);
}						    

function ajaxAddToBasket(formId, prodId)
{	
	var jQAForm = jQuery('#'+formId);
		
	// Switch to "adding" button
	jQuery("#btnAjaxAddToBasket", jQAForm).hide();
	jQuery("#btnAjaxDisabledAddToBasket", jQAForm).hide();
	jQuery("#btnAjaxAddingToBasket", jQAForm).show();

	if (jQAForm.children("input[name='bAjaxaddtobasket']").length==0)
	{
		var bAjaxElement='<input type="hidden" name="bAjaxaddtobasket" id="bAjaxaddtobasket" value="true"/>';
    	jQuery(bAjaxElement).appendTo(jQAForm);
	}
		
	jQAForm.ajaxSubmit({
		
		success: function(data){
		data=parseJSON(data);
			
    		if (data['message']=='addedtobasket')
    		{
    			// Get the number of items being added to the basket
    			var sQty;
    			if (jQuery("#qty", jQAForm).is("select")) {
    				sQty = jQuery("select#qty option:selected", jQAForm).attr('value');
    			} else {
    				sQty = jQuery("input#qty", jQAForm).attr('value');
    			}    			
    			var item_desc = sQty > 1 ? ' Items were' : ' Item was';
    			
    			jQuery("#messages_product_view .messages").hide(); //suppress error message (if any)
    			
    			// Set the popup message to show the number of items added to the basket    			
    			var sMsg = jQuery("#BasketConfirmationBox", jQAForm).attr("innerHTML");
    			jQuery("#BasketConfirmationBox", jQAForm).attr("innerHTML", sMsg.replace(/\$\$\$/g, sQty + item_desc));

    			// Get the total number of items in the basket and update the mini-basket
    			updateMiniBasket(data['item_total']);
    			
		    	jQuery('#BasketConfirmationBox', jQAForm).attr("style", "visibility:visible");		    	
	      		var timer = self.setTimeout(function() { switchButtonsBack(formId); }, 5000);
    		}
    		else
    		{
    			if (data['url'].length>0 && formId.indexOf('product')<0)
    			{
    				window.location.href=data['url'];
    			}
    			else
    			{
    				alert(data['message']);	
    			}
    		}		
		}
    });
}

function updateMiniBasket(sTotal) {
	// Update the number inside the brackets (i.e. the total number of items in the basket) in the mini-basket text string
	if (sTotal.length != 0) {
		var sStr = jQuery(".header .form-search a.top-link-cart").attr("innerHTML");
		jQuery(".header .form-search a.top-link-cart").attr("innerHTML", sStr.replace(/(\d+)/g, sTotal));
	}
}

function switchButtonsBack(formId) {
	
	var jQAForm = jQuery('#'+formId);
	jQuery('#BasketConfirmationBox', jQAForm).attr("style", "visibility:hidden");
	// Switch back to "add" button for a simple product, or "disabled" button for other products
	jQuery("#btnAjaxAddToBasket", jQAForm).hide();
	jQuery("#btnAjaxAddingToBasket", jQAForm).hide();
	jQuery("#btnAjaxDisabledAddToBasket", jQAForm).hide();
	if (jQuery("#ajaxProductType", jQAForm).val() == "simple") {
		jQuery("#btnAjaxAddToBasket", jQAForm).show();
	} else {
		jQuery("#btnAjaxDisabledAddToBasket", jQAForm).show();
		// Reset the select dropdowns as well
		jQuery("select.attr_Color").removeAttr('selected').find("option:first").attr('selected','selected');
		jQuery("select.attr_Size").removeAttr('selected').find("option:first").attr('selected','selected');
		jQuery("select#qty").removeAttr('selected').find("option:first").attr('selected','selected');
	}
}

function parseJSON(str){
	return  eval('('+str+')');
}

