// Javascript for Tozer Seeds Direct

// ------------------------
// 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();
    
    // ------------------------
    // Auto Complete Address Field
    // ------------------------
    
    var jsAutoComplete = document.getElementById("jsAutoComplete");
    
    // If it isn't there return
    if (!jsAutoComplete) 
    {
    	return;
    }
    
    // We've made it here so a link with with the id exists. Wait for onclick and do something
    jsAutoComplete.onclick = function()
    {
        autoCompleteAddress();
        return false;
    }
    
    // ------------------------
    // Convert First email address to lower case and check is valid
    // ------------------------
    
     var jsEmailLowerCase = document.getElementById("jsEmail1");
    
    // If it isn't there return
    if (!jsEmailLowerCase) 
    {
    	return;
    }
    
    jsEmailLowerCase.onchange = function()
    {
        // Get email address and convert to lowercase
        var email = document.getElementById("jsEmail1").value;
        
        // Check that email is valid
        checkValidEmail(email);
        
        // Update form
        document.getElementById("jsEmail1").value = email.toLowerCase();
        
        return false;
    }
    
    // ------------------------
    // Check email addresses are the same
    // ------------------------
    
     var jsEmailCheck = document.getElementById("jsEmail2");
    
    // If it isn't there return
    if (!jsEmailCheck) 
    {
    	return;
    }
    
    jsEmailCheck.onchange = function()
    {
    	// Get values
        var email1 = document.getElementById("jsEmail1").value;
        var email2 = document.getElementById("jsEmail2").value;
        
        // Convert email2 to lowercase
        document.getElementById("jsEmail2").value = email2.toLowerCase();
        
        if(email1.toLowerCase() != email2.toLowerCase())
        {
        	// The email addresses don't match
        	alert("Please check that you have correctly entered your email address into both boxes. Thanks");
        	return false;
        }
        else
        {
        	return false;
        }
    }
    
    // ------------------------
    // Check New customer form has been completed correctly
    // ------------------------
    
    var jsNewCustomerValidation = document.getElementById("jsNewCustomerValidation");
    
    // If it isn't there return
    if (!jsNewCustomerValidation) 
    {
    	return;
    }
    
    // We've made it here so a link with with the id exists. Wait for onclick and do something
    jsNewCustomerValidation.onclick = function()
    {
        validateNewCustomer();
        return false;
    }
    
    // ------------------------
    // Check Update Customer Form has been correctly entered
    // ------------------------
    
    var jsEditCustomerValidation = document.getElementById("jsEditCustomerValidation");
    
    // If it isn't there return
    if (!jsEditCustomerValidation) 
    {
    	return;
    }
    else
    {
    	alert("ok");
    }
    
    // We've made it here so a link with with the id exists. Wait for onclick and do something
    jsEditCustomerValidation.onclick = function()
    {
        alert("here");
        validateEditCustomer();
        return false;
    }
	
	// ------------------------
    // Validate Newsletter
    // ------------------------
    
    var jsValidateNewsletter = document.getElementById("jsValidateNewsletter");
    
    // If it isn't there return
    if (!jsValidateNewsletter) 
    {
    	return;
    }
    
    // We've made it here so a link with with the id exists. Wait for onclick and do something
    jsValidateNewsletter.onclick = function()
    {
        alert("here");
        jsValidateNewsletter();
        return false;
    }
	
	
	
} 

addLoadEvent(javascriptController); 


// Update postage cookie
function submitBasket()
{
	document.basket.submit();
}

// Remove code and submit the basket
function removeBasketPromo()
{
	document.basket.promoCode.value = "";
	document.basket.submit();
}

// Update postage details on order confirmation page
function submitPostageChange()
{
	document.postage.submit();
}



// ------------------------
// Function to check new customer details are correct
// ------------------------
function validateNewCustomer()
{
	// Assume we are okay unless otherwise
	var valid = true;
	var message = "";
	
	// Go through the required fields
	if(document.checkout.firstname.value == "")
	{
		valid = false;
		message = "Please enter your firstname";
		alert(message);
		return;
	}
	
	if(document.checkout.surname.value == "")
	{
		valid = false;
		message = "Please enter your surname";
		alert(message);
		return;
	}
	
	if(document.checkout.telephone.value == "")
	{
		valid = false;
		message = "Please enter your telephone number";
		alert(message);
		return;
	}
	
	if(document.checkout.email1.value == "")
	{
		valid = false;
		message = "Please enter your email address into both boxes";
		alert(message);
		return;
	}
	
	if(document.checkout.email2.value == "")
	{
		valid = false;
		message = "Please enter your email address into both boxes";
		alert(message);
		return;
	}
	
	/*
	// Is this a valid email address
	if(isUnusedEmail(document.checkout.email1.value))
	{
		valid = false;
		message = "This email address is already being used any another customer. Please enter a unique email address for this account.";
		alert(message);
		return false;
	} 
	*/
	
	if(document.checkout.password1.value == "")
	{
		valid = false;
		message = "Please enter a password into both boxes";
		alert(message);
		return;
	}
	
	if(document.checkout.password2.value == "")
	{
		valid = false;
		message = "Please enter a password into both boxes";
		alert(message);
		return;
	}
	
	if(document.checkout.password1.value.length < 6)
	{
		valid = false;
		message = "Please enter a password which is at least 6 characters long";
		alert(message);
		return;
	}
	
	if(document.checkout.password2.value.length < 6)
	{
		valid = false;
		message = "Please enter a password which is at least 6 characters long";
		alert(message);
		return;
	}
	
	if(document.checkout.password1.value != document.checkout.password2.value)
	{
		valid = false;
		message = "Please check that you have entered the same password into both boxes";
		alert(message);
		return;
	}
        		
	if(document.checkout.delivery1.value == "")
	{
		valid = false;
		message = "Please enter your delivery address";
		alert(message);
		return;
	}
	
	if(document.checkout.deliveryTown.value == "")
	{
		valid = false;
		message = "Please enter your delivery town";
		alert(message);
		return;
	}
	
	if(document.checkout.deliveryCounty.value == "")
	{
		valid = false;
		message = "Please enter your delivery county";
		alert(message);
		return;
	}
	
	if(document.checkout.deliveryPostcode.value == "")
	{
		valid = false;
		message = "Please enter your delivery postcode";
		alert(message);
		return;
	}
	
	if(document.checkout.billing1.value == "")
	{
		valid = false;
		message = "Please enter your billing address";
		alert(message);
		return;
	}
	
	if(document.checkout.billingTown.value == "")
	{
		valid = false;
		message = "Please enter your billing town";
		alert(message);
		return;
	}
	
	if(document.checkout.billingCounty.value == "")
	{
		valid = false;
		message = "Please enter your billing county";
		alert(message);
		return;
	}
	
	if(document.checkout.billingPostcode.value == "")
	{
		valid = false;
		message = "Please enter your billing postcode";
		alert(message);
		return;
	}
	
	if(valid == true)
	{
		document.checkout.submit();
	}
}

// ------------------------
// Function to check new customer details are correct
// ------------------------
function validateEditCustomer()
{
	// Assume we are okay unless otherwise
	var valid = true;
	var message = "";
	
	// Go through the required fields
	if(document.checkout.firstname.value == "")
	{
		valid = false;
		message = "Please enter your firstname";
		alert(message);
		return false;
	}
	
	if(document.checkout.surname.value == "")
	{
		valid = false;
		message = "Please enter your surname";
		alert(message);
		return false;
	}
	
	if(document.checkout.telephone.value == "")
	{
		valid = false;
		message = "Please enter your telephone number";
		alert(message);
		return false;
	}
	
	if(document.checkout.email.value == "")
	{
		valid = false;
		message = "Please enter your email address";
		alert(message);
		return false;
	}
	/*
	// Is this a valid email address
	if(validateEditEmail(document.checkout.email.value) == 1)
	{
		valid = false;
		message = "This email address is already being used any another customer. Please enter a unique email address for this account.";
		alert(message);
		return false;
	} 
	*/
	
	
	// Are we updating the password
	if(document.checkout.password1.value != "")
	{
		if(document.checkout.password2.value == "")
		{
			valid = false;
			message = "Please enter a password into both boxes";
			alert(message);
			return false;
		}
	
		if(document.checkout.password1.value.length < 6)
		{
			valid = false;
			message = "Please enter a password which is at least 6 characters long";
			alert(message);
			return false;
		}
	
		if(document.checkout.password2.value.length < 6)
		{
			valid = false;
			message = "Please enter a password which is at least 6 characters long";
			alert(message);
			return false;
		}
	
		if(document.checkout.password1.value != document.checkout.password2.value)
		{
			valid = false;
			message = "Please check that you have entered the same password into both boxes";
			alert(message);
			return false;
		}
	}
	
	if(document.checkout.delivery1.value == "")
	{
		valid = false;
		message = "Please enter your delivery address";
		alert(message);
		return false;
	}
	
	if(document.checkout.deliveryTown.value == "")
	{
		valid = false;
		message = "Please enter your delivery town";
		alert(message);
		return false;
	}
	
	if(document.checkout.deliveryCounty.value == "")
	{
		valid = false;
		message = "Please enter your delivery county";
		alert(message);
		return false;
	}
	
	if(document.checkout.deliveryPostcode.value == "")
	{
		valid = false;
		message = "Please enter your delivery postcode";
		alert(message);
		return false;
	}
	
	if(document.checkout.billing1.value == "")
	{
		valid = false;
		message = "Please enter your billing address";
		alert(message);
		return false;
	}
	
	if(document.checkout.billingTown.value == "")
	{
		valid = false;
		message = "Please enter your billing town";
		alert(message);
		return false;
	}
	
	if(document.checkout.billingCounty.value == "")
	{
		valid = false;
		message = "Please enter your billing county";
		alert(message);
		return false;
	}
	
	if(document.checkout.billingPostcode.value == "")
	{
		valid = false;
		message = "Please enter your billing postcode";
		alert(message);
		return false;
	}
	
	
	
	if(valid == true)
	{
		document.checkout.submit();
	}
}

// ------------------------
// Function to check that email is valid address
// ------------------------

function checkValidEmail(str) 
{
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	
	if (str.indexOf(at)==-1)
	{
		alert("Please check that you have correctly entered your email address");
		return false;
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr)
	{
		alert("Please check that you have correctly entered your email address");
		return false;
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr)
	{
		alert("Please check that you have correctly entered your email address");
		return false;
	}

	if (str.indexOf(at,(lat+1))!=-1)
	{
		alert("Please check that you have correctly entered your email address");
		return false;
	}

	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot)
	{
		alert("Please check that you have correctly entered your email address");
		return false;
	}

	if (str.indexOf(dot,(lat+2))==-1)
	{
		alert("Please check that you have correctly entered your email address");
		return false;
	}
		
	if (str.indexOf(" ")!=-1)
	{
		alert("Please check that you have correctly entered your email address");
		return false;
	}

 		return true;				
	}

// ------------------------
// Billing and Delivery Address are the same so lets auto complete
// ------------------------
function autoCompleteAddress() 
{	
	document.checkout.billing1.value = document.checkout.delivery1.value;
	document.checkout.billing2.value = document.checkout.delivery2.value;
	document.checkout.billing3.value = document.checkout.delivery3.value;
	document.checkout.billingTown.value = document.checkout.deliveryTown.value;
	document.checkout.billingCounty.value = document.checkout.deliveryCounty.value;
	document.checkout.billingPostcode.value = document.checkout.deliveryPostcode.value;
	
	// Country Menu
	document.getElementById("form-billingCountry").selectedIndex = document.getElementById("form-deliveryCountry").selectedIndex;
	
	return false;
}

// ------------------------
// Validates newsletter
// ------------------------
function validateNewsletter()
{
	var valid = true;
	
	if(document.newsletterForm.name.value == "")
	{
		valid = false;
		message = "Please enter your name and try again";
		alert(message);
		return false;
	}
	
	if(document.newsletterForm.email.value == "")
	{
		valid = false;
		message = "Please enter your email address and try again";
		alert(message);
		return false;
	}
	
	if(valid == true)
	{
		document.newsletterForm.submit();
	}
}

// ----------------------------------------------
// Validate un-used email address
// ----------------------------------------------

function isUnusedEmail(email)
{
	// Open Http Object
	request = getHttpObject();
	request.open("GET", "/php/ajax/validate-email.php?email=" + escape(email), true);
	
	alert("/php/ajax/validate-email.php?email=" + email);
	
	// On ready state change lets make a fuction
	request.onreadystatechange = function()
	{
		alert("ready state function called");
	
   		// Check if we are ready
		if(request.readyState != 4)
		{
			// Not ready
			alert("not ready");
		}
		else
		{
		
			alert(request.responseText);
			/*
			// Ready so what is the response?
			if(request.responseText == "0")
			{
				// No email in system with this address so okay
				alert("Email Okay");
				return false;
				
			}
			else
			{
				// Email already in the system so false
				alert("Email Already Used. Response = " + request.responseText);
				return true;
			}
			*/
		}
  	}
  	
  	return 1;
}


// ----------------------------------------------
// Validate un-used email address
// ----------------------------------------------

function validateEditEmail(email)
{
	// Open Http Object
	request = getHttpObject();
	request.open("GET", '/php/ajax/validate-edit-email.php?email=' + email, true);
	
	alert('/php/ajax/validate-edit-email.php?email=' + email);
	
	// On ready state change lets make a fuction
	request.onreadystatechange = function() 
	{
   		// Check if we are ready
		if(request.readyState != 4)
		{
			// Not ready
			return;
		}
		else
		{
			myVar = request.responseText;
			alert(myVar);
		
			// Ready so what is the response?
			if(request.responseText == "0")
			{
				// No email in system with this address so okay
				alert("Email Okay");
				return false;
				
			}
			else
			{
				// Email already in the system so false
				alert("Email Already Used. Response = " + request.responseText);
				return true;
			}
		}
  	};
  	
	request.send(null);
}

// ----------------------------------------------
// 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
function changeSeedTreatment(productRef, productCode)
{
	// Firstly lets send the form
	var http = getHttpObject();
	
	// Get the form value
  	var sel = document.getElementById("treatment-" + productRef);
  	var treatment = sel.options[sel.selectedIndex].value;
	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-seed-prices.php?productRef="+productRef+"&productCode="+productCode+"&treatment="+treatment+"&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 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 == "product-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/page/minus.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 == "product-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/page/add.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);
}

function jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}
