jQuery(document).ready(function(){

	/* ------------------------------------------------- */
	/* BEGIN *** Append Stock Info to the last drop down */
	/* ------------------------------------------------- */
	/*
	 * this expects the html structure to be: selects are in DD tag, label are in DT - all in DL
	 */
	jQuery('.product-shop form').each( 
		function ()
		{
			var form = jQuery(this);
			// select the one before last drop down and on its 'change' event append the stock info
			var selects = jQuery("select.super-attribute-select", jQuery(this));			
			if (selects.length > 1)
			{
				selects.eq(selects.length-2).change(function(){
			    	appendStockInfo();
			    });	
			}
			
			 // check the last dropdown, if out of stock selected, disable Add to basket button			
		    jQuery("select.super-attribute-select:last", jQuery(this)).change(function(){
		    	appendStockInfo();
		    	updateQtyDropDown();
		    	if(jQuery(this).find(":selected").hasClass("outofstock")){		    		
		    		disableBuyButton(form);
		    	} 
		    	else if(jQuery(this).find(":selected").hasClass("backorder")){
		    		
		    		enableBackButton(form);
		    	}
		    	else {
		    		enableBuyButton(form);
		    	}    	
		    });
		    //var dropcolor = jQuery("select.attr_Color", jQuery(this));
		    //var dropsize = jQuery("select.super-attribute-select.attr_Size", jQuery(this));
			var dropsize = jQuery("select.super-attribute-select:last", jQuery(this));
		 // Select the QTY dropdown in each form
            jQuery("select.qty", form).change(
                        function()
                        {	
                            var select = jQuery(this);      
                           jQuery('p.back-order', form).remove();
                            // update change
                            appentuppent(form, select, dropsize);
                        });
  
		}
	);
});

function appentuppent(form, ss, dropsize)
{
	
	if((jQuery('input[name=simple_js]', form).val()<=0) || (jQuery('input[name=simple_js]', form).val()>0 && jQuery('input[name=simple_backOrder]', form).val()=="1"))
	{  
		if((jQuery('input[name=simple_buffer]', form).val()==0))
		{ 
			var manage_stock=jQuery('input[name=simple_ManStock]', form).val();
			if(manage_stock==1)
			{
			var stock_value= jQuery('input[name=simple_js]', form).val();
			var stock_status= jQuery('input[name=stock_in]', form).val();
			}
			else
			{
				var stock_value= '10';
				var stock_status= '1';
			}
			
		}
		else
		{	
			var manage_stock=jQuery('input[name=simple_ManStock]', form).val();
			if(manage_stock==1)
			{
			var buf=parseInt(jQuery('input[name=simple_buffer]', form).val());
			var stock_value= parseInt(jQuery('input[name=simple_js]', form).val())- buf;
			var stock_status= jQuery('input[name=stock_in]', form).val();
			}
			else
			{
				var stock_value= 10;
				var stock_status= '1';
				
			}
		}
		
	}
	else if(jQuery('input[name=simple_js]', form).val()>0 && jQuery('input[name=simple_backOrder]', form).val()=="0")
	{
		
		if((jQuery('input[name=simple_buffer]', form).val()==0))
		{ 
			var manage_stock=jQuery('input[name=simple_ManStock]', form).val();
			if(manage_stock==1)
			{
				var stock_value= parseInt(jQuery('input[name=simple_js]', form).val());
				var stock_status= jQuery('input[name=stock_in]', form).val();
				var manage_stock=jQuery('input[name=simple_ManStock]', form).val();
				if(ss.val() > stock_value)
				{						
					stock_status ='0';
				}
			}
			else
			{
				var stock_value= 10;
				var stock_status= '1';
			}
		
		}
		else
		{	
			var manage_stock=jQuery('input[name=simple_ManStock]', form).val();
			if(manage_stock==1)
			{
				var buf=parseInt(jQuery('input[name=simple_buffer]', form).val());
				var stock_value= parseInt(jQuery('input[name=simple_js]', form).val())- buf;
				var stock_status= jQuery('input[name=stock_in]', form).val();
				if(ss.val() > stock_value)
				{	
					
					stock_status ='0';
				}
			}
			else
			{
				var stock_value= 10;
				var stock_status= '1';
			}
			
			
		}
	}
	else
	{
		
		var selectors = [];
		var selector = '';
		// Build the correct selector from the drop downs
		var dropdowns = jQuery("select.super-attribute-select", form);
		//alert(dropdowns.size());
		if (dropdowns.size())
		{ 
			//jQuery('p.back-order').remove(); 
			dropdowns.each( 
					function ()
					{
						// Find the table data for the current value
				    	var attrID = jQuery(this).attr("id").replace(/attribute/, "");	    					    	
				    	var selected_val = jQuery(this).val();	    					    	
				    	if (selected_val)
				    	{
				    		selectors.push("#stockInfoData tr td."+attrID+":contains('"+selected_val+"')");
				    	}
					});
			
			// If all options were selected	    				
			if (selectors.size() == dropdowns.size())
			{	
				// only product where we are manageing stock
				selectors.push("#stockInfoData tr td.manageStock:contains('1')");
				// Push the final selector onto the stack
				selectors.push("#stockInfoData tr td.stockqty");
				
		    	// Use the selectors to find the stock value
				var current = jQuery(selectors.shift(), form);
		    	selectors.each(
		    			function (selector)
		    			{	
		    				current = current.siblings(selector);
		    				
		    			});
		    	var stock_status = current.siblings("#stockInfoData tr td.stockstatus").text();
		    	var buf = current.siblings("#stockInfoData tr td.minStockOut");
		    	var backorder = current.siblings("#stockInfoData tr td.backorder");
				var stock_value = parseInt(current.text()) - parseInt(buf.text());
				if(ss.val() > stock_value && backorder.text()== 0)
				{	//sorry, actually just assign 0 to stock_status in as text.
					stock_status =current.siblings("#stockInfoData tr td.backorder").text();
				}
				
			}
		}
	}	
	//if(stock_value < ss.val() )
	if(stock_value < ss.val() && stock_status=='1')
		{
		var backCount=ss.val() - stock_value;
		
		//var product_name = jQuery('.breadcrumbs li.product strong').text();
		jQuery('div.add-to-cart',form).append('<p class="back-order">Currently Out Of Stock. Add To Basket To Back Order.</p>');
		//jQuery('.product-options-bottom').add('<p id="new">new paragraph</p>').css('background-color', 'red');
		
		//exit;
	}
	else if(stock_status=='0')
	{
		jQuery('div.add-to-cart',form).append('<p class="back-order">Currently Out Of Stock.</p>');
		jQuery('button#btnAjaxAddToBasket', form).hide();
		
		
	}
	else if(jQuery("select.super-attribute-select:last", form).val()!="")
	{
		jQuery('button#btnAjaxAddToBasket', form).show();
	}
				
			
}



    /**
     * Looks at the remaining stock for the selected product and updates the quantity drop down accordingly
     */
    function updateQtyDropDown()
    {    	
    	jQuery('.product-shop form').each( 
			function ()
			{jQuery('p.back-order').remove();
			
					var selectors = [];
					var selector = '';
					// Build the correct selector from the drop downs
					var dropdowns = jQuery("select.super-attribute-select", jQuery(this));
					if (dropdowns.size())
					{
	    				dropdowns.each( 
	    						function (){
	    							// Find the table data for the current value
	    					    	var attrID = jQuery(this).attr("id").replace(/attribute/, "");	    					    	
	    					    	var selected_val = jQuery(this).val();	    					    	
	    					    	if (selected_val)
	    					    	{
	    					    		selectors.push("#stockInfoData tr td."+attrID+":contains('"+selected_val+"')");
	    					    	}
	    						}
	    					);
	    				// If all options were selected	    				
	    				if (selectors.size() == dropdowns.size())
	    				{
	    					// only product where we are manageing stock
	    					selectors.push("#stockInfoData tr td.manageStock:contains('1')");
	    					// Push the final selector onto the stack
	    					selectors.push("#stockInfoData tr td.stockqty");
					    	// Use the selectors to find the stock value
	    					var current = jQuery(selectors.shift(), jQuery(this));
					    	selectors.each(
					    			function (selector)
					    			{
					    				current = current.siblings(selector);
					    			}
					    		);					    	
					    	var back_order = current.siblings("#stockInfoData tr td.backorder");
					    	var qty_buffer = current.siblings("#stockInfoData tr td.minStockOut").text();
							var stock_value = parseInt(current.text());	
							
							if(back_order.text()== 0 && qty_buffer>=0 )
							{
								stock_value=stock_value-qty_buffer;
								
							}
							// If there are more than 10 in stock or not found due to manage stock being off, just use 10
							if (isNaN(stock_value) || stock_value > 10 || (jQuery('input[name=cf-managestock]', jQuery(this)).val()=='1') || back_order.text()== 1)
							{	
								stock_value = 10;
								
							}	
							
							// Remove the options apart from the first
							jQuery("select#qty option:not(:first-child)", jQuery(this)).each(
									function (opt)
									{						
										jQuery(this).remove();
									}
								);
							// Rebuild the drop down
							var options = jQuery("select#qty", jQuery(this)).attr('options');
							for (i=1; i<=stock_value; i++)
							{
								options[i] = new Option(i,i);
							}
	    				}
					}
				
			});
    }

    function appendStockInfo(){
    	// In each form
    	
    	jQuery('.product-shop form').each( 
    			function ()
    			{  
    				var form = jQuery(this);
    				//if (jQuery('input[name=cf-managestock]', form).val()=='0')
    				{
	    				// Loop over the options; in the last dropdown
	    				jQuery("select.super-attribute-select:last option[value!='']", form).each(
	    						function ()
	    						{
	    							var option = jQuery(this);
	    							// Fetch any selectors needed to match the value from other dropdowns
	    							var selectors = [];    		    				
	    		    				// Build the correct selector from the drop downs which are not the last
	    		    				var dropdowns = jQuery("select.super-attribute-select:not(:last)", form);
	    		    				if (dropdowns.size())
	    		    				{
	    			    				dropdowns.each( 
	    			    						function (){
	    			    							// Find the table data for the current value
	    			    					    	var attrID = jQuery(this).attr("id").replace(/attribute/, "");	    					    	
	    			    					    	var selected_val = jQuery(this).val();	    					    	
	    			    					    	if (selected_val)
	    			    					    	{
	    			    					    		selectors.push("#stockInfoData tr td."+attrID+":contains('"+selected_val+"')");
	    			    					    	}
	    			    						}
	    			    					);
	    		    				}    		    				
	    		    				// Now find the stock value for each of these options, using the selectors found above if needed
	    		    				// Push the selector for this option onto the stack
	    		    				var option_attrID = option.parent().attr("id").replace(/attribute/, "");
	    		    				var option_val = option.val();
	    		    				selectors.push("#stockInfoData tr td."+option_attrID+":contains('"+option_val+"')");  
	    		    				selectors.push("#stockInfoData tr td.manageStock:contains('1')");
	    		    				if (selectors.size())
				    				{    		    					
				    					// Use the selectors to find the stock values
				    					var current = jQuery(selectors.shift(), form);
				    					if (selectors.size())
					    				{
									    	selectors.each(
									    			function (selector)
									    			{
									    				current = current.siblings(selector);
									    			}
									    		);					
					    				}
										// Loop over the values
				    					
								    	var stock_values = current.siblings("#stockInfoData tr td.stockqty");
								    	var stock_status = current.siblings("#stockInfoData tr td.stockstatus");
								    	var back_order = current.siblings("#stockInfoData tr td.backorder");
								    	
								    	stock_values.each(
							    			function ()
							    			{	var buf = current.siblings("#stockInfoData tr td.minStockOut").text();
							    				///alert(buf);
							    				var stockMsg = 'out of stock';
							    				var stock_value = parseInt(jQuery(this).text())- parseInt(buf);	
												// If 0 in stock mark the option as out of stock
							    				if (stock_value == 0 && back_order.text() == 0)
							    				{			
													// If the option is not already marked as out of stock
							        				if (option.text().split(' - ').pop() != stockMsg)
							        				{
							        					option.text(option.text()+(stockMsg.length>0 ? ' - '+stockMsg : ''));
								        				if(jQuery.trim(stockMsg)=='out of stock'){
								            				// If the option is not already marked as out of stock
								        					if (!option.hasClass('outofstock')){
								        						option.addClass('outofstock');
								        					}
								        				}
							        				}
							    				}
							    				else if(stock_value <= 0 && back_order.text() == 1)
							    				{	
							    					// If the option is not already marked as out of stock
							        				if (option.text().split(' - ').pop() != stockMsg)
							        				{
							        					option.text(option.text()+(stockMsg.length>0 ? ' - '+stockMsg : ''));
								        				if(jQuery.trim(stockMsg)=='out of stock'){
								            				// If the option is not already marked as out of stock
								        					if (!option.hasClass('outofstock')){
								        						option.addClass('backorder');
								        					}
								        				}
							        				}
							    				}
							    				
							    			}					    	
							    		);
								    	stock_status.each(
								    			function ()
								    			{	
								    				var stockMsg = 'out of stock';
								    				var stock_value = parseInt(jQuery(this).text());							
													// If produt status is outof stock mark it as out of stock.
								    				
								    				if (stock_value == 0)
								    				{								
														// If the option is not already marked as out of stock
								        				if (option.text().split(' - ').pop() != stockMsg)
								        				{ 
								        					option.text(option.text()+(stockMsg.length>0 ? ' - '+stockMsg : ''));
									        				if(jQuery.trim(stockMsg)=='out of stock'){
									            				// If the option is not already marked as out of stock
									        					if (!option.hasClass('outofstock')){
									        						option.addClass('outofstock');
									        					}
									        				}
								        				}
								    				}
								    			}					    	
								    		);
				    				}
	    						}
	    					);
    					}
    				}			    
    			);    			
        return true;
    }  

    function disableBuyButton(form){
    	jQuery(".add-to-cart-outofstock", form).remove();
    	var sHtml = '<div class="add-to-cart-outofstock"><p class="back-order">Currently Out Of Stock.</p>';
    	//var simpleprodid = jQuery("#stockInfoData tr td.simpleproductid", form).text();
    	//sHtml = sHtml + jQuery.ajax({url: "/configproduct/stockurl?product_id=" + simpleprodid,async: false}).responseText + '</div>';
    	
    	jQuery(".add-to-cart-outofstock", form).show();
    	jQuery(".add-to-cart", form).after(sHtml).hide();
    	return true;
    }
   
    function enableBuyButton(form){
    	jQuery(".add-to-cart-outofstock", form).remove();
    	jQuery(".alert-stock", form).remove();
    	jQuery(".add-to-cart", form).show();
    	return true;
    }
    function enableBackButton(form){
    	jQuery(".add-to-cart-outofstock", form).remove();
    	jQuery(".alert-stock", form).remove();
    	jQuery(".add-to-cart", form).show();
    	jQuery("p.back-order", form).show();
    	return true;
    }
    
    /* END *** Append Stock Info to the last drop down */
	/* ----------------------------------------------- */

