// JavaScript Document

var sources;
var current;

function initImages()
{
   sources = new Array();
   current = -1;
   var arr = document.getElementsByName("addImg");
   for (var i = 0; i < arr.length; i++)
   {
	  sources[i] = arr[i].src;
   }
}

function lastImage()
{
   if (--current < 0) current = sources.length - 1;
   document.getElementById("mainImg").src = sources[current];
}

function nextImage()
{
   if (++current > sources.length - 1) current = 0;
   document.getElementById("mainImg").src = sources[current];
}

function checkReviewForm()
{
   var elem = document.getElementById("reviewForm");
   if (elem != null)
   {
	  var msg = "";
	  var kids = elem.childNodes;
      for (var i = 0; i < kids.length; i++)
	  {
		 if (kids[i].type == "text" || kids[i].type == "textarea")
		 {
	        if (kids[i].value == "") msg += "\n" + kids[i].name + " incorrectly filled out.";
			else if(kids[i].type == "text" && kids[i].name.indexOf("mail") != -1)
			{
			   if (!checkEmail(kids[i].value)) msg += "\n" + kids[i].name + " incorrectly filled out.";
			}
		 }
	  }
	  
	  if (msg == "") return true;

	  window.alert("The following must be fixed before the form can be submitted.\n" + msg);
   }
   return false;
}

function checkEmail(email)
{
  var foundAt = false;
  var foundDot = false;
  var atPos = 0;
  var dotPos = 0;
  for (var i = 0; i < email.length; i++)
  {
    if (email.charAt(i) == "@")
    {
      foundAt = true;
      atPos = i;
    }
    else if (email.charAt(i) == ".")
    {
      foundDot = true;
      dotPos = i;
    }
  }
  if (foundAt && foundDot && (atPos < dotPos) && (email.length > 6))
  {
    return true;
  }
  return false;			
}

function fixReviewLink(ref)
{
   var revLink = document.getElementById("reviewlink");
   if (revLink != null)
   {
	  revLink.href = "Submit_a_Review.php?ref=" + ref;
   }
}

function checkContactForm(theForm) {
  if (theForm.Name.value == "") {
	showError("Please supply your name.", theForm['Name']);
	return false;
  }
  if (theForm.Email.value == "") {
	showError("Please supply your email address.", theForm['Email']);
	return false;
  }
  if (!checkEmail(theForm.Email.value)) {
	showError("The email address you have entered is not valid. It must match name@domain.com.", theForm.Email);
	return false;
  }
  if (theForm.Phone.value == "") {
	showError("Please enter your telephone number.", theForm.Phone);
	return false;
  }
  if (theForm.Product.value == "") {
	showError("Please enter the product name.",theForm.Product );
	return false;
  }
  if (theForm.Price.value == "") {
	showError("Please enter the product price.", theForm.Price);
	return false;
  }
  if (theForm.Delivery_Price.value == "") {
	showError("Please enter the delivery price.", theForm.Delivery_Price);
	return false;
  }
  return true;
}

function showError(err, inp) {
  window.alert(err);
}