/*
 *	Maria Andrade
 *	Javascript 1 Midterm
 *	April 24, 2016
 *	index.js
 *
 */

// Toggle control for table decor
var tableDecor = false;
// Email regular expression for validation
var regex = /(.+)@(.+){2,}\.(.+){2,}/;

// Question 
// Users 18 years or older view hidden content
// Others get an alert
var dobCheck = function()
{
	// Get value of selected DOB
	var m = document.getElementById("birthmonth");
	var month = m.options[m.selectedIndex].value;
	var d = document.getElementById("birthday");
	var day = d.options[d.selectedIndex].value;
	var y = document.getElementById("birthyear");
	var year = y.options[y.selectedIndex].value;
	
	// Get current date
	var today = new Date();
	var dd = today.getDate();
	var mm = today.getMonth()+1; //January is 0!
	var yyyy = today.getFullYear();
	
	// Check if user is of age
	// Start with comparing the birthyear
	// Over 18, clear to view hidden content
	if ( (yyyy - year) > 18 )
	{
		// This will redirect user to a new page to view hidden content
		// Alternate option would be to update the current page with the hidden content
		// next if statement demonstrates this behavior
		window.location = "hiddenContent.html";
	}
	// Check birthmonth if user turns 18 this year
	// If birth month passed, clear...
	else if ( (mm > month) && ((yyyy - year) === 18) )
	{
		// content appears on same page vs redirecting user above
		document.getElementById("content").innerHTML = "This is the hidden content, you are clearly of age.";
	}
	// Check day, if user turns 18 this month
	else if ( (dd >= day) && (mm >= month) && ((yyyy - year) === 18) )
	{
		document.getElementById("content").innerHTML = "This is the hidden content, you are clearly of age.";
	}
	else
	{
		// If user is not of age, user will recieve an alert message
		document.getElementById("content").innerHTML = " ";
		alert("You are not of age to view this page");
	}
}

// Question 2 and 3
// User enters city name and valid email,
// error messages include both fields required and valid email
// Content is then displayed and email link will open up user's mail client
var outputData = function () 
{
	// Get text entered
	var c = document.getElementById("city");
	var city = c.value;
	var e = document.getElementById("email");
	var email = e.value;
	
	// Form validation
	// Fields are not empty
	// Display error message
	if (( city !== "" ) && ( email !== "" ))
	{
		// Verify valid email
		if (regex.test(email))
		{
			// Clear out error message
			document.getElementById("error").innerHTML = " ";
			// Display content as requested 
			document.getElementById("dataOut").innerHTML = city + " is a great town! " + "<a class='email' title='Email' href='mailto:" + email +"subject=Javascript Midterm&body=This email was sent automatically '>" + email+"</a>";
		}
		else
		{
			document.getElementById("error").innerHTML = "Please enter a valid email.";
		}
	}
	else
	{
		document.getElementById("error").innerHTML = "Both fields are required";
	}
}

// Question 4 and 5
// Order form for a tShirt, user selects size and shipping method
// Both required to place order
// Tax calculator will 

// These are some helper functions, reuse code
// Returns the shipping cost
var getShipping = function()
{
	// Determine which shipping method selected
	var shipping;
    var radios = document.getElementsByName( "shipping" );
	var len=radios.length;
	
	// Radio selection required
	var selectionMade = false;
	
	// Check if shipping method selected and get value
	for ( var i=0, len; i<len; i++ ) {
		if ( radios[i].checked ) { 
			selectionMade = true;
			shipping = parseFloat(radios[i].value); 
		}
	}
	if ( !selectionMade )
	{
		return null;
	}
	return shipping;
}

// Returns the tax 
var calcTax = function (preTax)
{
	var tax = 0.00;
		if ( ( preTax ) < 10 )
		{
			tax = 10;	
		}
		else if ( preTax < 20 )
		{
			tax = 7.25;
		}
		else
		{
			tax = 5;
		}
		return tax;
}

// Calculate and display the tax and total cost
var calcTotal = function (form, price) 
{
	// Get shipping cost
	shipping = getShipping();
	// Calculate tax and total
	if ( shipping !== null )
	{
		// Clear previous error message
		document.getElementById("shipError").innerHTML = " ";
		
		// Calculations
		var cost = parseFloat(price);
		var preTax = shipping + cost;
		var tax = calcTax(preTax);
		var total = ((tax/100) * preTax) + preTax;
		
		// Display output
		document.getElementById("totalDisplay").innerHTML = "Total with shipping and " + tax + "% tax is: $" + (total).toFixed(2);
	}
	// Shipping not selected, display error message
	else
	{
		document.getElementById("shipError").innerHTML = "Shipping Method Required";
	}
}

// Gathers order information for order processing
var buyNow = function(form, price)
{
	// Get size selected
	var s = document.getElementById("size");
	var size = s.options[s.selectedIndex].value;
	
	// Get name, address and email entered
	var n = document.getElementById("name");
	var name = n.value;
	var a = document.getElementById("address");
	var address = a.value;
	var e = document.getElementById("email2");
	var email = e.value;
	
	// Form validation
	// Get shipping cost
	shipping = getShipping();
	// Fields are not empty
	// Display error message
	if (( name !== "" ) && ( email !== "" ) && address !== "" && size !== "" && shipping !== null)
	{
		// Validate email
		if (regex.test(email))
		{
			// Calculate total
			var preTax = Number(shipping) + Number(price);
			var tax = calcTax(preTax);
			var total = ((tax/100) * preTax) + preTax;
	
			// Clear error
			document.getElementById("contactError").innerHTML = " ";
			
			// Display output		
			document.getElementById("orderConfirmation").innerHTML = "Order has been placed.  You have ordered a "+ document.getElementById("shirtName").innerHTML+ ", in a " + size + " size.  Your order total is $" + (total).toFixed(2) + ".  A confirmation will be sent to the following email: " + email;
		}
		else
		{			
			// Display error
			document.getElementById("contactError").innerHTML = "Please enter a valid email.";
		}
	}
	else
	{
		// Compose a descriptive error message
		var message = " ";
		
		if ( name === "" )
		{
			message += "Please enter a valid name. <br />";	
		}
		if ( email === "" || !(regex.test(email)) )
		{
			message += "Please enter a valid email address. <br />";	
		}
		if (address === "" )
		{
			message += "Please enter an address. <br />";	
		}
		if ( size === "" )
		{
			message += "Please select a size. <br />";
		}
		if ( shipping === null )
		{
			message += "Please select a shipping option. <br />";
		}
	
		// Display error
		document.getElementById("contactError").innerHTML = message;
	}
}


// Question 6
// Displays all multiples of 7 from 1 to 1000
var multiples = function() 
{
	var output = " ";
  	for( var i = 1; i <= 1000; i++ )
  	{
		if ( i%7 === 0 )
	  	{
			output += i + "<br />"
	  	}
  	}
	document.getElementById("multiples").innerHTML = output; 
}

// Question 7
// Styles the table with colors
var decorTable = function()
{
	// Get the number of rows and iterate through the table
	var table = document.getElementById("zebraTable");
	var tableRows = table.rows.length;
	
	// Toggle decor
	tableDecor = !tableDecor;

	for (var i = 1; i < tableRows; i++)
	{
		if ( i%2 === 0 )
		{
			if ( tableDecor )
			{
				table.rows[i].style.backgroundColor = "#eee";
				
				// I decided to add a unique color to the header row for distinction
				table.rows[0].style.backgroundColor = "#c0c0c0";
			}
			else
			{
				table.rows[i].style.backgroundColor = "white";
				table.rows[0].style.backgroundColor = "white";
			}
		}
	}
}