// Javascript for Tozer Seeds Direct New Buying Panel

// ------------------------
// Simon Willison Script for defining onLoadEvents
// ------------------------
function addLoadEvent(func) 
{
	var oldonload = window.onload;
  	if (typeof window.onload != 'function') 
  	{
    	window.onload = func;
  	}
  	else 
  	{
    	window.onload = function() 
    	{
      		if (oldonload) 
      		{
        		oldonload();
      		}
      		func();
    	}
  	}
}

// ------------------------
// Javascript Controller - ADDS ON CLICK EVENTS
// ------------------------
function javascriptController() {
    
    // Check the browser supports getElementById so we can find our link
    if(!document.getElementById) 
    {
    	return;
    }
	
	// ------------------------
    // Add Minus / Plus Quantity buttons
    // ------------------------
	
	addQuantityButtons();
    
} 

addLoadEvent(javascriptController); 


// ----------------------------------------------
// Get HTTP Request
// ----------------------------------------------

// Browser spedific XmlRequest Object
function getHttpObject() 
{
	if(window.ActiveXObject) 
	{
		var waystation = new ActiveXObject("Microsoft.XMLHTTP");
	} 
	else if (window.XMLHttpRequest) 
	{
		var waystation = new XMLHttpRequest();
	} 
	else 
	{
		var waystation = false;
	}
	
	return waystation;
}


// Toggles seed treatments (NOT FORMATS)
function changeTreatment(productRef, productCode)
{
	// Firstly lets send the form
	var http = getHttpObject();
	
	// Get the treatment value
  	var sel = document.getElementById("treatment-" + productRef);
  	var treatment = sel.options[sel.selectedIndex].value;
  	 	
  	// Get the format value
  	var sel = document.getElementById("format-" + productRef);
  	// Added a check for options, if none use the hidden value
  	if(sel.option)
  	{
  		var format = sel.options[sel.selectedIndex].value;
  	}
  	else
  	{
  		var format = sel.value;
  	}
  	// Create the nocache
	var nocache = Math.floor(Math.random()*1001);
  	
  	// window.open("/pages/ajax-seed-prices.php?productRef="+productRef+"&productCode="+productCode+"&treatment="+treatment);
	
  	// SEND the request
  	http.open("GET", "/pages/ajax-buying-panel.php?panel=full&productRef="+productRef+"&productCode="+productCode+"&treatment="+treatment+"-"+format+"&nocache="+nocache, true);
  	http.send(null);
  	
  	// Are we ready
	http.onreadystatechange = function() 
    {
      	if(http.readyState == 4)
		{
			// Update the page
			var node = document.getElementById("buying-" + productRef);
			node.innerHTML = http.responseText;
			
			// Add the quantity controls
			addQuantityButtons();
		}
    }
}

// Toggles seed formats (not treatments)
function changeFormat(productRef, productCode)
{
	// Firstly lets send the form
	var http = getHttpObject();
	
	// Get the treatment value
  	var sel = document.getElementById("treatment-" + productRef);
  	// Added a check for options, if none use the hidden value
  	if(sel.option)
  	{
  		var treatment = sel.options[sel.selectedIndex].value;
  	}
  	else
  	{
  		var treatment = sel.value;
  	}
  	
  	// Get the format value
  	var sel = document.getElementById("format-" + productRef);
  	var format = sel.options[sel.selectedIndex].value;
  	
  	// Create the nocache
	var nocache = Math.floor(Math.random()*1001);
  	
  	// window.open("/pages/ajax-seed-prices.php?productRef="+productRef+"&productCode="+productCode+"&treatment="+treatment);
	
  	// SEND the request
  	http.open("GET", "/pages/ajax-buying-panel.php?panel=full&productRef="+productRef+"&productCode="+productCode+"&treatment="+treatment+"-"+format+"&nocache="+nocache, true);
  	http.send(null);
  	
  	// Are we ready
	http.onreadystatechange = function() 
    {
      	if(http.readyState == 4)
		{
			// Update the page
			var node = document.getElementById("buying-" + productRef);
			node.innerHTML = http.responseText;
			
			// Add the quantity controls
			addQuantityButtons();
		}
    }
}

// Adds the hide functionality to the fullbuy panel (SCRAPPED)
function addHideShowButtons()
{
	var img_array = document.getElementsByTagName("img");
	
	// Do we have an object
	if(img_array)
	{
		for (i=0; i<img_array.length; i++)
		{
			// Loop around images
			// Hide Buttons
			if(img_array[i].className == "hide-options-button")
			{
				// We have found an appropriate img so get the rel tag
				var rel = img_array[i].getAttribute("rel");
				
				// Assign an on click to this
				img_array[1].onclick = function()
				{
					
				}
			}
		}
	}
}

// Adds quantity Buttons
function addQuantityButtons()
{
	var div_array = document.getElementsByTagName("div");
	
	// Do we have an object
	if(div_array)
		{
		for (i=0; i<div_array.length; i++)
		{
			// Loop around div
			// Product Minus
			if(div_array[i].className == "fullbuy-minus")
			{
				// We have found an appropriate div so get the rel tag
				var rel = div_array[i].getAttribute("rel");
				
				// Add the image
				div_array[i].innerHTML = "<img src='/images/buying-panel/minus-full-button.gif' alt='Decrease Quantity' rel='" +  rel + "'/>\n";
				
				// Get the image
				var node = div_array[i].firstChild;
				
				// Store the value of rel on the image
				
				// Add the on click behaviour
				node.onclick = function()
				{
					// Get the relevant qty node
					var qtyNode = document.getElementById("qty-" + this.getAttribute("rel"));
					
					// Get the current qty
					var qty = parseInt(qtyNode.value);
					
					// Work out new qty
					if(qty == 0)
					{
						var newQty = 0;
					}
					else
					{
						var newQty = qty -1;
					}
					
					// Change node value
					qtyNode.value = newQty;
					return false;
				}
			}
			
			// Product Plus
			if(div_array[i].className == "fullbuy-plus")
			{
				// We have found an appropriate div so get the rel tag
				var rel = div_array[i].getAttribute("rel");
				
				// Add the image
				div_array[i].innerHTML = "<img src='/images/buying-panel/plus-full-button.gif' alt='Increase Quantity' rel='" +  rel + "'/>\n";
				
				// Get the image
				var node = div_array[i].firstChild;
				
				// Store the value of rel on the image
				
				// Add the on click behaviour
				node.onclick = function()
				{
					// Get the relevant qty node
					var qtyNode = document.getElementById("qty-" + this.getAttribute("rel"));
					
					// Get the current qty
					var qty = parseInt(qtyNode.value);
					
					// Work out new qty
					var newQty = qty +1;
					
					// Change node value
					qtyNode.value = newQty;
					return false;
				}
			}
			
			// Loop around div
			// Product Minus
			if(div_array[i].className == "quickbuy-minus")
			{
				// We have found an appropriate div so get the rel tag
				var rel = div_array[i].getAttribute("rel");
				
				// Add the image
				div_array[i].innerHTML = "<img src='/images/buying-panel/minus-button.gif' alt='Decrease Quantity' rel='" +  rel + "'/>\n";
				
				// Get the image
				var node = div_array[i].firstChild;
				
				// Store the value of rel on the image
				
				// Add the on click behaviour
				node.onclick = function()
				{
					// Get the relevant qty node
					var qtyNode = document.getElementById("qty-" + this.getAttribute("rel"));
					
					// Get the current qty
					var qty = parseInt(qtyNode.value);
					
					// Work out new qty
					if(qty == 0)
					{
						var newQty = 0;
					}
					else
					{
						var newQty = qty -1;
					}
					
					// Change node value
					qtyNode.value = newQty;
					return false;
				}
			}
			
			// Product Plus
			if(div_array[i].className == "quickbuy-plus")
			{
				// We have found an appropriate div so get the rel tag
				var rel = div_array[i].getAttribute("rel");
				
				// Add the image
				div_array[i].innerHTML = "<img src='/images/buying-panel/plus-button.gif' alt='Increase Quantity' rel='" +  rel + "'/>\n";
				
				// Get the image
				var node = div_array[i].firstChild;
				
				// Store the value of rel on the image
				
				// Add the on click behaviour
				node.onclick = function()
				{
					// Get the relevant qty node
					var qtyNode = document.getElementById("qty-" + this.getAttribute("rel"));
					
					// Get the current qty
					var qty = parseInt(qtyNode.value);
					
					// Work out new qty
					var newQty = qty +1;
					
					// Change node value
					qtyNode.value = newQty;
					return false;
				}
			}
			
		}
	}
}

function popupWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

// Functions to show the full panel and quick panel

// Get the quickpanel for this product
function showQuick(productRef, productCode)
{
	// First setup the httpobject
	var http = getHttpObject();
	
	// Create the no cache
	var nocache = Math.floor(Math.random()*1001);
	
	// SEND the request
	http.open("GET", "/pages/ajax-buying-panel.php?panel=quick&productRef="+productRef+"&productCode="+productCode+"&nocache="+nocache, true);
	http.send(null);
	
	// Are we ready
	http.onreadystatechange = function() 
    {
      	if(http.readyState == 4)
		{
			// Update the page
			var node = document.getElementById("buying-" + productRef);
			node.innerHTML = http.responseText;
			
			// Add the quantity controls
			addQuantityButtons();
		}
    }
}


// Get the full panel for this product
function showFull(productRef, productCode)
{
	// First setup the httpobject
	var http = getHttpObject();
	
	// Create the no cache
	var nocache = Math.floor(Math.random()*1001);
	
	// SEND the request
	http.open("GET", "/pages/ajax-buying-panel.php?panel=full&productRef="+productRef+"&productCode="+productCode+"&nocache="+nocache, true);
	http.send(null);
	
	// Are we ready
	http.onreadystatechange = function() 
    {
      	if(http.readyState == 4)
		{
			// Update the page
			var node = document.getElementById("buying-" + productRef);
			node.innerHTML = http.responseText;
			
			// Add the quantity controls
			addQuantityButtons();
		}
    }
}


// Change the packet price on the quickbuy menu
function changePacketPrice(productRef)
{
	// Get the drop down element
  	var dropdown = document.getElementById("packsize-" + productRef);
  	
  	// Grab the price from the selected item in the drop down
  	var price = dropdown.options[dropdown.selectedIndex].getAttribute("rel");
  	
  	// We also need the article code for our ajax
  	var article = dropdown.options[dropdown.selectedIndex].getAttribute("value");
  	
  	// Get the node we have selected
	var node = document.getElementById("price-" + productRef);
	
	// Insert into innerHTML of the price P
	node.innerHTML = "&pound; "+price;
	
	// We need to pull in the values from the ajax request so we have the right values for this item
	
	// First setup the httpobject
	var http = getHttpObject();
	
	// Create the no cache
	var nocache = Math.floor(Math.random()*1001);
	
	// SEND the request
	http.open("GET", "/pages/ajax-quickbuy-info.php?articleRef="+article, true);
	http.send(null);
	
	// Are we ready
	http.onreadystatechange = function() 
    {
      	if(http.readyState == 4)
		{
			// Update the page
			var node = document.getElementById("price-holder-" + productRef);
			node.innerHTML = http.responseText;
			
			// Add the quantity controls
			addQuantityButtons();
		}
    }	
}

/**
 * Adds the starbuy hover panel
 * 
 */
$(document).ready(function()
{
	// Search for things with a class of .star-buy
	// Add a hover function to them
	$(".star-buy").hover(
	function()
	{
		// Find and animate the span inside what we find
		$(this).find("span").animate({opacity: "show", top: "-51"}, "normal");
	},
	function()
	{
		// On hover out animate the span back to it's previous position
		$(this).find("span").animate({opacity: "hide", top: "-45"}, "fast");
	});
});


/**
 * Need to loop through divs with class fullbuy-panel
 * Then add a function to prevent zero quantities from being added to basket
 * 
 */
$(document).ready(function()
{
	// Itterate through all divs		
	$("div").each(function(index)
	{
		// Check for fullbuy class
		if($(this).hasClass('fullbuy-panel'))
		{			
			// Define the form as the direct parent of this panel which is a form element
			var thisForm = $(this).parent('form');
			
			// Now we need to add a function to the click event of the buy button
			$(this).find('[name=buy]').click(function()
			{
				// Fetch all the quantities by traversing up the dom tree using parents with class of fullbuy-panel to find the quantity values
				var qty1 = $(this).parents('.fullbuy-panel').find('[name=qty1]').val();
				var qty2 = $(this).parents('.fullbuy-panel').find('[name=qty2]').val();
				var qty3 = $(this).parents('.fullbuy-panel').find('[name=qty3]').val();
				var qty4 = $(this).parents('.fullbuy-panel').find('[name=qty4]').val();
				
				// If any one of the quantities are greater than 0 we can submit the form
				if((qty1 > 0) || (qty2 > 0) || (qty3 > 0) || (qty4 > 0))
				{
					// Submit the form we defined earlier
					thisForm.submit();
				}
				else
				{
					// Alert a message
					alert("Please select at least 1 packet size to add to your basket");
					
					// And return false
					return false;
					
				} // << END OF QUANTITY CHECK IF STATEMENT
				
			}); // << END OF CLICK FUNCTION
			
		} // << END OF HAS CLASS IF STATEMENT
		
	}); // << END OF DIV ITTERATION STATEMENT
	
}); // << END OF DOCUMENT READY FUNCTION


