// JavaScript Document

//------------------------
// Global vars use for counts and limit
//------------------------
var count = 1;

// Use this limit to define how many products can be added to the form.
var productLimit = 10;

//------------------------
// Load event function
//------------------------
/**
 * Adds an onload event
 * 
 * @param func
 * @return
 */
function addLoadEvent(func) 
{
	var oldonload = window.onload;
  	if (typeof window.onload != 'function')
  	{
    	window.onload = func;
  	}
  	else 
  	{
    	window.onload = function() 
    	{
      		if (oldonload) 
      		{
        		oldonload();
      		}
      		func();
    	}
  	}
}

//------------------------
// Initialiser scripts
//------------------------

/**
 * Function to enable the form and buttons if Java is detected
 * 
 * 
 */
function loadForm()
{
	// Get the form by id
	var form = document.getElementById("theform");
	
	// Get the placeholder by id
	var placeholder = document.getElementById("placeholder");
	
	// Switch their display status
	form.style.display = 'inline';
	placeholder.style.display = 'none';
	
	// Activate the button click events
	addButtonActions();
}

/**
 * Function calls button enablers
 * 
 *
 */
function addButtonActions()
{ 
	activateSubmitButton();
	activateAddProductButton(count);
}

//------------------------
// End of Initialiser scripts
//------------------------


//------------------------
// Button activation scripts
//------------------------

/**
 * This activates the submit button action
 * 
 */
function activateSubmitButton()
{
	// Add the validation function firing for the submit button
	var node = document.getElementById("submit-button");
	if(!node)
	{
		return;
	}
	else
	{
		node.onclick = function()
		{
			// Disable the submit button
			disableSubmitButton();
			
			// Validate the form
			validateEstimateForm();
		}
	}
}

/**
 * Disables the submit button to prevent multiple submits
 * 
 */
function disableSubmitButton()
{
	// Switch out the button image to say please wait
	var button = document.getElementById("submit-button");
	button.setAttribute("src","/images/page/please-wait-button.gif");
	
	// Change the form button to disabled to prevent multiple clicks
	button.setAttribute("id","submit-button-off");
}

/**
 * re-enables the submit button
 * 
 */
function enableSubmitButton()
{
	// Switch out the button image to say please wait
	var button = document.getElementById("submit-button-off");
	button.setAttribute("src","/images/page/get-estimate-button.gif");
	
	// Change the form button to disabled to prevent multiple clicks
	button.setAttribute("id","submit-button");
	
	// Add the onclick once button id has returned
	activateSubmitButton()
}

/**
 * Enable the add product button depending on the product number
 * 
 */
function activateAddProductButton(buttonId)
{
	var buttonNumber = buttonId;
	// Add the action to create new elements in the form here
	var addItem = document.getElementById("add-product" + buttonNumber)
	if(!addItem)
	{
		return;
	}
	else
	{
		addItem.onclick = function()
		{
			addProduct();
		}
	}
}
/**
 * Enable the remove product button depending on the product number
 * 
 */
function activateRemoveProductButton(buttonId)
{
	var buttonNumber = buttonId;
	
	var removeItem = document.getElementById("remove-product" + buttonNumber)
	if(!removeItem)
	{
		return;
	}
	else
	{
		removeItem.onclick = function()
		{
			removeProduct();
		}
	}
}

//------------------------
// End of button scripts
//------------------------

//------------------------
// Regular functions
//------------------------

/**
 * Validate the customer form, ensuring all required fields are filled in.
 * 
 */
function validateEstimateForm()
{
	// Assume we are okay unless otherwise
	var valid = true;
	var message = "";
	// Go through the required fields
	if(document.theform.firstname.value == "")
	{	
		highlightOn("firstname");
		valid = false;
		message = "Please enter your firstname.";
		alert(message);
		enableSubmitButton();
		return;
	}
	else
	{
		highlightOff("firstname");
	}	
	
	if(document.theform.surname.value == "")
	{
		highlightOn("surname");
		valid = false;
		message = "Please enter your surname.";
		alert(message);
		enableSubmitButton();
		return;
	}
	else
	{
		highlightOff("surname");
	}
	
	if(validateEmail(document.theform.email.value) == false)
	{
		highlightOn("email");
		valid = false;
		message = "Please enter a valid email address.";
		alert(message);
		enableSubmitButton();
		return;
	}
	else
	{
		highlightOff("email");
	}
	
	if(document.theform.email.value == "")
	{
		highlightOn("email");
		valid = false;
		message = "Please enter your email address.";
		alert(message);
		enableSubmitButton();
		return;
	}
	else
	{
		highlightOff("email");
	}
	
	if(document.theform.telephone.value == "")
	{
		highlightOn("telephone");
		valid = false;
		message = "Please enter your telephone number.";
		alert(message);
		enableSubmitButton();
		return;
	}
	else
	{
		highlightOff("telephone");
	}
	
	if(document.theform.address1.value == "")
	{
		highlightOn("address1");
		valid = false;
		message = "Please enter your address.";
		alert(message);
		enableSubmitButton();
		return;
	}
	else
	{
		highlightOff("address1");
	}
	
	if(document.theform.town.value == "")
	{
		highlightOn("town");
		valid = false;
		message = "Please enter your town.";
		alert(message);
		enableSubmitButton();
		return;
	}
	else
	{
		highlightOff("town");
	}
	
	if(document.theform.county.value == "")
	{
		highlightOn("county");
		valid = false;
		message = "Please enter your county.";
		alert(message);
		enableSubmitButton();
		return;
	}
	else
	{
		highlightOff("county");
	}
	
	if(document.theform.postcode.value == "")
	{
		highlightOn("postcode");
		valid = false;
		message = "Please enter your postcode.";
		alert(message);
		enableSubmitButton();
		return;
	}
	else
	{
		highlightOff("postcode")
	}
	
	// Now check we have got a timber type in all the product fields
	var validCount = 1;
	
	do
	{
		var type = document.getElementById("type" + validCount);
		if(type.selectedIndex > 0)
		{
			// This passes validation and means an item is selected.
		}
		else
		{
			valid = false;
			message = "You have not chosen a timber type for product " + validCount + "\nPlease choose a timber type to continue.";
			alert(message);
			enableSubmitButton();
			return;
		}
		// Incremement the validCount
		validCount++;
	}while(validCount <= count)
		
	if(valid == true)
	{
		document.theform.submit();
	}
}

/**
 * This function creates the new product after add product has been clicked unless the productLimit has been reached.
 * 
 */
function addProduct()
{
	if(count >= productLimit)
	{
		alert("Sorry you have reached the maximum number of quotable items online.\n\nPlease get in touch via our contact page to get a personal quote from us.");
	}
	else
	{
		// Increment the Count
		count++;
		// Create the variable
		var html = "";
		// Create the html to into the form
		html = html + "<h2>Product " + count + "</h2>";
		html = html + "";
		html = html + "<div class=\"form-row form-required\">";
		html = html + "<label>Timber Type</label>";
		html = html + "<select id=\"type" + count + "\" name=\"type" + count + "\" class=\"form-dropdown\" onchange=\"toggleSizes(" + count + ", this.value); return false;\">";
		html = html + "<option selected=\"selected\">Please select</option>";
		html = html + "<option value=\"Western Red Cedar\">Western Red Cedar</option>";
		html = html + "<option value=\"Siberian Larch\">Siberian Larch</option>";
		html = html + "<option value=\"Thermowood\">Thermowood</option>";
		html = html + "<option value=\"Cumaru\">Cumaru</option>";
		html = html + "</select>";
		html = html + "</div>";
		html = html + "<div class=\"form-row form-required\" id=\"size" + count + "\">";
		html = html + "<label>Size</label>";
		html = html + "<select name=\"size" + count + "form\" class=\"form-dropdown\">";
		html = html + "<option selected=\"selected\">Please select</option>";
		html = html + "<option value=\"25 x 100\">25 x 100</option>";
		html = html + "<option value=\"25 x 125\">25 x 125</option>";
		html = html + "<option value=\"25 x 150\">25 x 150</option>";
		html = html + "</select>";
		html = html + "</div>";
		html = html + "<div class=\"form-row form-required\">";
		html = html + "<label>Lineal Metres</label>";
		html = html + "<input name=\"linealMetres" + count + "\" type=\"text\" class=\"form-input\" value=\"1\"/>";
		html = html + "</div>";
		html = html + "<div id=\"add-button-div" + count + "\">";
		html = html + "<img src=\"/images/page/add-product-button.gif\" alt=\"Add Another Product\" class=\"add-product\" id=\"add-product" + count + "\"/> ";
		html = html + "</div>";
		html = html + "<div class=\"remove-product\" id=\"remove-" + count +"\">";
		html = html + "<p>or <a href=\"#1\" id=\"remove-product" + count + "\">Remove this product</a></p>";
		html = html + "</div>";

		// Create the div element
		var newProduct = document.createElement("div");
		
		// Insert the html into the div element
		newProduct.innerHTML = html;
		
		// Set a new div id for the div element based on the count
		var newProductId = "product-" + count; 
		newProduct.setAttribute("id", newProductId);
		
		// Set the class of the div element
		newProduct.setAttribute("class","child-product");
		
		// Now add the div element as a child of the main enquiry form div
		var productHolder = document.getElementById("enquiry-form-products");
		productHolder.appendChild(newProduct);

		// Now clear the old add product button and remove button
		// Make an oldCount which is -1 of count to get the previous count.
		var oldCount = count - 1;
		
		// Get the old button's div
		var addButtonDiv = "add-button-div" + oldCount;
		var oldAddbuttonDiv = document.getElementById(addButtonDiv);
		
		// Clear the div
		oldAddbuttonDiv.innerHTML = "";
		
		// Get the old remove button's div
		var removeButtonDiv = "remove-" + oldCount;
		var oldRemoveButtonDiv = document.getElementById(removeButtonDiv);
		
		// Clear the div
		oldRemoveButtonDiv.innerHTML = "";

		// Activate the new add product button
		activateAddProductButton(count);
		
		// Activate the remove product button
		activateRemoveProductButton(count);
		
		// Update the product counter
		updateProductCount();
	}
}
/**
 * This function removes the last product on the list
 * 
 */
function removeProduct()
{
	// Get the enquiry form container and its child
	var container = document.getElementById("enquiry-form-products");
	var product = document.getElementById("product-" + count);
	
	// Remove the child from the container
	container.removeChild(product);
	
	// Decrease count since we have removed this.
	count --;
	
	// We now need to re-enable the add and remove product buttons
	
	// Get the new product button's div
	var newButtonDiv = "add-button-div" + count;
	var newAddbuttonDiv = document.getElementById(newButtonDiv);
	newAddbuttonDiv.innerHTML = "<img src=\"/images/page/add-product-button.gif\" alt=\"Add Another Product\" class=\"add-product\" id=\"add-product" + count + "\"/> ";
	
	// Now activate the new add product button
	activateAddProductButton(count);
	
	// We don't want a remove product button when we have only 1 product so only fire this if we have more than one
	if(count > 1)
	{
		// Get the new remove button's div
		var newRemoveButtonDiv = "remove-" + count;
		var newButtonDiv = document.getElementById(newRemoveButtonDiv);
		newButtonDiv.innerHTML = "<p>or <a href=\"#1\" id=\"remove-product" + count + "\">Remove this product</a></p>";
		
		// Now activate the remove product button
		activateRemoveProductButton(count);
	}
	// Update the product counter
	updateProductCount();
}


//Some products are only available in some sizes so this function filters
function toggleSizes(which, value)
{
	//alert("which = " + which + "value = " + value);
	var html = "<label>Size</label>";
	html = html + "<select name=\"size" + which + "\" id=\"size" + which + "form\" class=\"form-dropdown\" >";
	
	if(value == "Western Red Cedar")
	{
		// Change for Red Cedar
		
		// Make the new HTML
		html = html + "<option value=\"25 x 100\">25 x 100</option>";
		html = html + "<option value=\"25 x 150\">25 x 150</option>";
		
	
	}
	else if(value == "Cumaru")
	{
		// Change for Cumaru
		// Make the new HTML
		html = html + "<option value=\"25 x 150\">25 x 150</option>";
		
	}
	else
	{
		html = html + "<option value=\"25 x 100\">25 x 100</option>";
		html = html + "<option value=\"25 x 125\">25 x 125</option>";
		html = html + "<option value=\"25 x 150\">25 x 150</option>";
	}
	
	html = html + "</select>";
	
	// Update the page
	var node = document.getElementById("size" + which);
	node.innerHTML = html;
}

// This will change the product counter to count
function updateProductCount()
{
	// Update the counter to read how many items we have to send to the php
	var counter = document.getElementById("number-of-products");
	counter.setAttribute("value",count);
}

// Turn on the highlighted field
function highlightOn(inputId)
{
	var id = inputId
	var highlight = document.getElementById(id);
	highlight.setAttribute("class","form-input-highlight");
}

// Turn off the highlighted field
function highlightOff(inputId)
{
	var id = inputId
	var highlight = document.getElementById(id);
	highlight.setAttribute("class","form-input");
}


// Validate email
function validateEmail(str) 
{
		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1)
		{
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr)
		{
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr)
		{
		    return false
		}

		if (str.indexOf(at,(lat+1))!=-1)
		{
		    return false
		}

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot)
		 {
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1)
		 {
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1)
		 {
		    return false
		 }

 		 return true					
}

//------------------------
// End of functions
//------------------------


//------------------------
// Load Events here
//------------------------

addLoadEvent(loadForm);

//------------------------
// End of Load Events
//------------------------