var httpRequest = null;
var tabSelected = null;

function loadContent (tab, page, params, initialization) {
  defaultLoadContent(page, params, initialization);
}

function loadLoginForm () {
  var loginDiv = getElement("login");
  loginDiv.innerHTML = "<DIV><DIV id=\"login_error\"></DIV><DIV align=\"right\">Email:<BR><INPUT type='TEXT' id='email' class='input'></DIV><DIV align=\"right\">Password:<BR><INPUT type='password', id='password' class='input'></DIV><DIV><INPUT type='button' value='Submit' onClick='designerLogin()' class='button'></DIV><DIV>Click <A href='javascript: register()'>here</A> to register. <A href='javascript: whyRegister()'>Why Register?</A>&nbsp;&nbsp;&nbsp;<A href='javascript: forgotPassword()'>Forgot your password?</A></DIV></DIV>";

//<DIV id=\"login_error\"></DIV><SPAN style='padding: 5px;'>Email:<BR><INPUT type='TEXT' id='email' class='input'></SPAN><SPAN style='padding: 5px;'>Password:<BR><INPUT type='password', id='password' class='input'></SPAN><SPAN style='padding: 5px;'><BR><INPUT type='button' value='Submit' onClick='designerLogin()' class='button'></SPAN><DIV style='padding-left: 5px; clear: left;'>Click <A href='javascript: register()'>here</A> to register. <A href='javascript: whyRegister()'>Why Register?</A></DIV>";
}

function viewPrivacyPolicy () {
  openInnerWindow("privacy_policy", "privacy_policy.php5", 600, 400, "Arch Framing & Design: Privacy Policy");
}

function loggedIn () {
  var loginDiv = getElement("login");
  var login = getElement("login");
  var currentOrderLink = "";
  var viewDesignersLink = "";
  if (getCookie("af_administrator") != null)
    viewDesignersLink = "<DIV style=\"float: left; width: 100px\"><A href=\"javascript: loadContent('', 'view_designers.php');\">View Designers</A></DIV><DIV style=\"float: left; width: 100px\"><A href=\"javascript: loadContent('', 'view_orders.php');\">View Orders</A></DIV>";
  if (getCookie("af_order_id") != null)
    currentOrderLink = "<DIV style=\"float: left; width: 100px\"><A href=\"javascript: loadPrintSelector();\">Edit Current Order</A></DIV>";
  login.innerHTML = "<DIV>You are currently logged in.</DIV><DIV style=\"float: left; width: 100px\"><A href=\"javascript: loadContent('', 'designer_home.php')\">Designer Home</A></DIV><DIV style=\"float: left; width: 100px\"<A href=\"javascript: newOrder()\">New Order</DIV>" + currentOrderLink + "<DIV style=\"float: left; width: 100px;\"><A href=\"javascript: editUserInformation();\">Edit User Info</A></DIV>" + viewDesignersLink + "<DIV style=\"float: left; width: 100px\"<A href=\"javascript: logOut()\">Log Out</A></DIV>";
}

function loadDesignerOrders (designerID) {
  httpRequest = new HttpRequest("get_designer_orders.php", loadDesignerOrdersCallback);
  httpRequest.setParameter("designer_ID", designerID);
  var params = "designer_ID=" + designerID;
  httpRequest.post(params);
}

function loadDesignerOrdersCallback () {
  var response = /* httpRequest */ this.getResponse();
  var designerID = httpRequest.getParameter("designer_ID");
  var designerOrderDiv = getElement("designer_" + designerID + "_orders");
  designerOrderDiv.innerHTML = response;
}

function deleteOrder (orderID, caller) {
  var confirmation = confirm("Are you sure you want to delete this order? This operation cannot be undone.");
  if (!confirmation)
    return;

  httpRequest = new HttpRequest("delete_order.php", deleteOrderCallback);
  httpRequest.setParameter("caller", caller);
  var params = "order_ID=" + orderID;
  httpRequest.post(params);
}

function deleteOrderCallback () {
  var caller = httpRequest.getParameter("caller");
  loadContent("", caller);
}

function designerLogin () {
  var email = getElement("email");
  var password = getElement("password");
  if (isValidEmail(email.value) && password.value != "") {
    httpRequest = new HttpRequest("log_in.php", designerLoginCallback);
    var params = "email=" + email.value + "&password=" + password.value;
    httpRequest.post(params); 
  }
  else alert("Please enter a valid email and password.");
}

function editUserInformation () {
  openInnerWindow("user_info", "edit_user_info.php", 500, "", "Edit User Information");
}

function logOut () {
  var login = getElement("login");
  login.innerHTML = "<A href=\"javascript: loadLoginForm()\">Designer Login</A>";
  loadContent("", "log_out.php");
}

function designerLoginCallback () {
  var response = /* httpRequest */ this.getResponse();
  response = trim(response);
  if (response == "0") {
    var loginErrorDiv = getElement("login_error");
    var password = getElement("password");
    loginErrorDiv.innerHTML = "<DIV style='padding: 5px; background-color: #FFFFFF'><FONT color=\"#DD0000\"><B>The email and/or password you specified is incorrect.</B></FONT>";
    password.value = "";
  }
  else {
    loggedIn();
    loadContent("", "designer_home.php");
  }
}

function register () {
  openInnerWindow("register", "register.php", 400, "", "Register with Arch Framing");
}

function whyRegister () {
  openInnerWindow("why_register", "why_register.php", 400, "", "Why Register?");
}

function forgotPassword () {
  var email = getElement("email");
  if (!isValidEmail(email.value)) {
    alert("Please enter a valid email to send a new password to.");
    return;
  }
  httpRequest = new HttpRequest("password_reminder_email.php", resetPasswordCallback);
  httpRequest.setParameter("email", email.value);
  var params = "email=" + email.value;
  httpRequest.post(params);
}

function checkExistingRegistration (editExisting) {
  var email = getElement("register_email");
  httpRequest = new HttpRequest("check_existing_registration.php", checkExistingRegistrationCallback);
  httpRequest.setParameter("email", email.value);
  var params = "email=" + email.value;
  if (editExisting)
    params += "&edit=1";

  httpRequest.post(params);
}

function checkExistingRegistrationCallback () {
  var response = /* httpRequest */ this.getResponse();
  response = trim(response);
  if (response != "0") {
    var confirmation = confirm("A user with this email address is already registered with Arch Framing. Would you like a new password sent to you via email?");
    if (confirmation) {
      closeInnerWindow("register_window");
      var email = httpRequest.getParameter("email");
      httpRequest = new HttpRequest("password_reminder_email.php", resetPasswordCallback);
      httpRequest.setParameter("email", email);
      var params = "email=" + email;
      httpRequest.post(params);
    }
  }
}

function resetPasswordCallback () {
  var email = httpRequest.getParameter("email");
  alert("A new password has been sent to " + email);
}

function validateRegistration () {
  var registrationForm = getElement("register");
  var email = getElement("register_email");
  var firstName = getElement("first_name");
  var lastName = getElement("last_name");
  var password = getElement("register_password");
  var confirmPassword = getElement("confirm_password");
  var telephone = getElement("telephone");
  var company = getElement("company");

  var error = "";
  if (!isValidEmail(email.value)) {
    error += "<LI>The email you entered is not valid.";
  }
  if (firstName.value == "" || lastName.value == "")
    error += "<LI>Please enter a first and last name.";
  if (!isValidTelephone(telephone.value))
    error += "<LI>The telephone number you entered is not a valid telephone number with area code.";

  // console.log(password.value + ", " + confirmPassword.value);
  if ((password.value != confirmPassword.value) || password.value == "") {
    password.value = "";
    confirmPassword.value = "";
    error += "<LI>The passwords you entered were invalid or did not match.";
  }
  if (error != "") {
    var errorDiv = getElement("registration_error");
    errorDiv.innerHTML = "<FONT color=\"#CC0000\">The following errors occured with your registration:<P><UL>" + error + "</UL></FONT>";
    return false;
  }
  else return true;
}

function submitUserInformation (page, callback) {
  var designerID = getElement("designer_ID");
  var registrationForm = getElement("register");
  var email = getElement("register_email");
  var firstName = getElement("first_name");
  var lastName = getElement("last_name");
  var password = getElement("register_password");
  var confirmPassword = getElement("confirm_password");
  var telephone = getElement("telephone");
  var company = getElement("company");

  if (!validateRegistration())
    return;

  var params = "email=" + email.value + "&password=" + password.value + "&first_name=" + firstName.value + "&last_name=" + lastName.value + "&telephone=" + telephone.value + "&company=" + company.value;

  if (designerID)
    params += "&designer_ID=" + designerID.value;

  httpRequest = new HttpRequest(page, callback);
  httpRequest.post(params);
}

function saveUserInformation () {
  submitUserInformation("save_user_information.php", editUserInformationCallback);
}

function editUserInformationCallback () {
  var registrationWindow = windowManager.getWindow("user_info_window");
  registrationWindow.setContents("<DIV align=\"center\"><DIV style=\"padding: 15px;\">Your new information has been saved.</DIV><INPUT type=\"button\" value=\"Close\" onClick=\"closeInnerWindow('user_info_window')\"></DIV>");
  logOut();
}

function submitRegistration () {
  submitUserInformation("save_registration.php", submitRegistrationCallback);
}

function submitRegistrationCallback () {
  var response = /* httpRequest */ this.getResponse();
  response = trim(response);
  var registrationWindow = windowManager.getWindow("register_window");
  registrationWindow.setContents("<DIV align=\"center\"><DIV style=\"padding: 15px;\">Thank you for registering! Please log in to access your designer home page!</DIV><INPUT type=\"button\" value=\"Close\" onClick=\"closeInnerWindow('register_window')\"></DIV>");
}

function editOrder (orderID) {
  var orderIDInput = getElement("order_ID");
  if (orderIDInput)
    orderIDInput.value = orderID
  setCookie("af_order_id", orderID);
  loadPrintSelector();
}

function eraseAllOrders () {
  httpRequest = new HttpRequest("erase_all_orders.php", eraseAllOrdersCallback);
  var params = "";
  httpRequest.post(params);
}

function eraseAllOrdersCallback () {

}

function changeFrame (name, newFrame) {
  httpRequest = new HttpRequest("script/query_image_dimensions.php", changeFrameCallback);
  httpRequest.setParameter("name", name);
  httpRequest.setParameter("new_frame", newFrame);
  var params = "filename=" + newFrame + ".gif";
  httpRequest.post(params);
}

function openDebugWindow () {
  openInnerWindow("execute_sql", "execute_sql.php", 600, "", "Execute SQL");
}

function changeFrameCallback () {
  var name = httpRequest.getParameter("name");
  var response = /* httpRequest */ this.getResponse();
alert(response);
  response = response.split("x");
  var width = response[0];
  var height = response[1] + "px";

  var newFrame = httpRequest.getParameter("new_frame");
  var topLeft = getStyleObject(name + "_top_left");
  var topLeftFront = getStyleObject(name + "_top_left_front");
  var topCenter = getStyleObject(name + "_top_center");
  var topRight = getStyleObject(name + "_top_right");
  var topRightFront = getStyleObject(name + "_top_right_front");

  var left = getStyleObject(name + "_left");
  var right = getStyleObject(name + "_right");

  var bottomLeft = getStyleObject(name + "_bottom_left");
  var bottomLeftFront = getStyleObject(name + "_bottom_left_front");
  var bottomCenter = getStyleObject(name + "_bottom_center");
  var bottomRight = getStyleObject(name + "_bottom_right");
  var bottomRightFront = getStyleObject(name + "_bottom_right_front");

  topLeft.backgroundImage = "url(" + newFrame + "_left.gif)";
  topLeftFront.backgroundImage = "url(" + newFrame + "_ul.gif)";
  topCenter.backgroundImage = "url(" + newFrame + ".gif)";
  topRight.backgroundImage = "url(" + newFrame + "_right.gif)";
  topRightFront.backgroundImage = "url(" + newFrame + "_ur.gif)";
  left.backgroundImage = "url(" + newFrame + "_left.gif)";
  right.backgroundImage = "url(" + newFrame + "_right.gif)";
  bottomLeft.backgroundImage = "url(" + newFrame + "_left.gif)";
  bottomLeftFront.backgroundImage = "url(" + newFrame + "_ll.gif)";
  bottomCenter.backgroundImage = "url(" + newFrame + "_bottom.gif)";
  bottomRight.backgroundImage = "url(" + newFrame + "_right.gif)";
  bottomRightFront.backgroundImage = "url(" + newFrame + "_lr.gif)";

  topLeft.width = height;
  topLeftFront.width = height;
  topLeft.height = height;
  topLeftFront.height = height;
  topCenter.height = height;
  topRight.width = height;
  topRightFront.width = height;
  topRight.height = height;
  topRightFront.height = height;

  left.width = height;
  right.width = height;

  bottomLeft.width = height;
  bottomLeftFront.width = height;
  bottomLeft.height = height;
  bottomLeftFront.height = height;
  bottomCenter.height = height;
  bottomRight.width = height;
  bottomRightFront.width = height;
  bottomRight.height = height;
  bottomRightFront.height = height;
}

/*************/
/*           */
/*  Contact  */
/*           */
/*************/
function clearMessageForm () {
  var name = getElement("name");
  var email = getElement("email");
  var regarding = getElement("regarding");
  var message = getElement("message");
  name.value = "";
  email.value = "";
  regarding.value = "";
  message.value = "";
}

function sendMessage () {
  var name = getElement("name");
  var email = getElement("email");
  var telephone = getElement("telephone");
  var regarding = getElement("regarding");
  var message = getElement("message");

  if (name.value == "" || email.value == "" || message.value == "") {
    alert("Please fill out your name, email address, and a message.");
    return;
  }
  httpRequest = new HttpRequest("send_message.php", sendMessageCallback);
  var params = "name=" + name.value + "&email=" + email.value + "&telephone=" + telephone.value + "&regarding=" + regarding.options[regarding.selectedIndex].text + "&message=" + message.value;
  var message_div = getElement("contact_message");
  message_div.innerHTML = "<B>Sending...</B>";
  httpRequest.post(params);
}


function sendMessageCallback () {
  var response = httpRequest.getResponse();
  var message_div = getElement("contact_message");
  response = trim(response);
  // console.log(response);
  if (response) {
    message_div.innerHTML = "Your message has been sent successfully.";
    clearMessageForm();
  }
  else message_div.innerHTML = "<FONT color=\"#990000\">Message could not be sent. Please verify that you have filled out the form correctly and try again.</FONT>";
}

/*******************/
/*                 */
/*  Print Selector */
/*                 */
/*******************/

function newOrder () {
  var orderID = getElement("order_ID");
  setCookie("af_order_id", "");
  if (orderID)
    orderID.value = "";
  openInnerWindow("print_selector", "print_selector.php", 865, "", "Arch Framing Print Selector", "new_order=1");
}

function loadPrintSelector () {
  openInnerWindow("print_selector", "print_selector.php", 865, "", "Arch Framing Print Selector");
}

function previewPrint (printID) {  // , manufacturer, stockNum) {
  var printIDInput = getElement("print_ID");
  var quantity = getElement("quantity");

/* FOR INCLUSION OF MANUFACTURER INPUT - "Advanced Search"
  var stockNumInput = getElement("SKU");
  var manufacturerInput = getElement("manufacturer");
  manufacturerInput.value = manufacturer;
  stockNumInput.value = stockNum;
*/
  if (printIDInput) {
    printIDInput.value = printID;
    quantity.value = 1;

    var addToOrderButton = getElement("add_to_order_button");
    addToOrderButton.value = "Add to Order";
    addToOrderButton.setAttribute("onClick", "addToOrder()");
  }
  preview(printID);
}

function preview (printID) {
  var addToOrderButton = getElement("add_to_order_button");
  if (addToOrderButton) {
    addToOrderButton.setAttribute("disabled", false);
    addToOrderButton.disabled = false;
  }
  httpRequest = new HttpRequest("preview_print.php", previewCallback);
  var stockNum = getElement("SKU");
/*
  var manufacturer = getElement("manufacturer");
  if (manufacturer.value == "") {
    alert("Please select a manufacturer.");
    return;
  }
*/
  var params = "print_ID=" + printID;  // "SKU=" + stockNum.value + "&manufacturer=" + manufacturer.value;
  httpRequest.post(params);
}

function previewCallback () {
  var response = /* httpRequest */ this.getResponse();
  var preview = getElement("preview");
  preview.innerHTML = response;
}

function printTitleSearch () {
  var search = getElement("search");
  httpRequest = new HttpRequest("print_keyword_search.php", searchCallback);
  var params = "search=" + search.value;
  httpRequest.post(params);
}

function getArtistPrints () {
  httpRequest = new HttpRequest("get_artist_prints.php", searchCallback);
/*
  var manufacturer = getElement("manufacturer");
*/
  var subject = getElement("subject");
  subject.value = "";

  var artist = getElement("artist");
  var params = "artist=" + artist.value; // "manufacturer=" + manufacturer.value + "&artist=" + artist.value;
  httpRequest.post(params);
}

function searchCallback () {
  var searchResults = getElement("search_results");
  var response = /* httpRequest */ this.getResponse();
  searchResults.innerHTML = response;
}

function getManufacturerArtists () {
  var manufacturer = getElement("manufacturer");
  httpRequest = new HttpRequest("get_manufacturer_artists.php", getManufacturerArtistsCallback);
  var params = "manufacturer=" + manufacturer.value;
  httpRequest.post(params);
}

function getSubjectPrints () {
  httpRequest = new HttpRequest("print_search.php", searchCallback);
  var artist = getElement("artist");
  artist.value = "";

  var subject = getElement("subject");
  var subjectEncoded = subject.value.replace("&", "*amp;");
  var params = "where=WHERE subject = `" + subjectEncoded + "`&title=Prints in `" + subjectEncoded + "`";
  httpRequest.post(params);  
}

function getManufacturerArtistsCallback () {
  var response = /* httpRequest */ this.getResponse();
  // console.log(response); return;
  var artist = getElement("artist");
  for (var i=artist.options.length-1; i>=0; i--)
    artist.options[i] = null;

  responseParts = response.split("|");
  artist.options[0] = new Option("", "");
  for (var i=1; i<responseParts.length; i++) {
    artist.options[i] = new Option(responseParts[i], responseParts[i]);
  }
}

function loadPrints (query, table, where, title, page, readOnly) {
  httpRequest = new HttpRequest("print_search.php", searchCallback);
  var params = "query=" + query + "&count_table=" + table + "&where=" + where + "&title=" + title + "&page=" + page + "&read_only=" + readOnly;
  httpRequest.post(params);
}

function uploadThumb (manufacturer, SKU) {
  
}

function clearPrintSearchForm () {
  var manufacturer = getElement("manufacturer");
  var SKU = getElement("SKU");
  var artist = getElement("artist");
  var subject = getElement("subject");
  var quantity = getElement("quantity");

  manufacturer.value = "";
  SKU.value = "";
  artist.value = "";
  subject.value = "";
  quantity.value = "";
}

function orderLogin () {
  var email = getElement("order_login_email");
  var password = getElement("order_login_password");
  httpRequest = new HttpRequest("log_in.php", orderLoginCallback);
  var params = "email=" + email.value + "&password=" + password.value;
  httpRequest.post(params);
}

function orderLoginCallback () {
  var response = /* httpRequest */ this.getResponse();
  response = trim(response);
  closeInnerWindow("submit_order_window");
  submitOrderToArch();
  loggedIn();  
}

function addPrintComments (printID) {
  var orderID = getElement("order_ID");
  openInnerWindow("print_comment", "print_comment.php", 400, "", "Add a Comment", "order_ID=" + orderID.value + "&print_ID=" + printID)
}

function savePrintComments (printID) {
  var orderID = getElement("order_ID");
  var printComments = getElement("print_comments");
  httpRequest = new HttpRequest("save_print_comments.php", savePrintCommentsCallback);
  var params = "order_ID=" + orderID.value + "&print_ID=" + printID + "&comments=" + printComments.value;
  httpRequest.post(params);
  closeInnerWindow("print_comment_window");
}

function savePrintCommentsCallback () {
  
}

function addToOrder () {
  var orderID = getElement("order_ID");
  var printID = getElement("print_ID");
  var quantity = getElement("quantity");

/*
  var manufacturer = getElement("manufacturer");
  var SKU = getElement("SKU");
  if (manufacturer.value == "" || SKU.value == "") {
    alert("Please select a manufacturer, a quantity, and a SKU");
    return;
  }
  var params = "order_ID=" + orderID.value + "&print_ID=" + printID.value + "&manufacturer=" + manufacturer.value + "&quantity=" + quantity.value + "&SKU=" + SKU.value;
*/

  httpRequest = new HttpRequest("add_to_order.php", addToOrderCallback);
  var params = "order_ID=" + orderID.value + "&print_ID=" + printID.value + "&quantity=" + quantity.value;
  // console.log(params);
  httpRequest.post(params);
}

function addToOrderCallback () {
  var orderID = getElement("order_ID");
  var response = /* httpRequest */ this.getResponse();
  response = trim(response);
  if (response != "0")
    orderID.value = response;
}

function removeFromOrder (printID) {
  var confirmation = confirm("Are you sure you want to remove this item from your order?");
  if (!confirmation)
    return;

  var quantity = getElement("quantity");
  quantity.value = 0;
  reviseOrderQuantity(printID);
}

function reviseOrderQuantity (printID) {
  var orderID = getElement("order_ID");
  var quantity = getElement("quantity");
  httpRequest = new HttpRequest("revise_order.php", reviseOrderQuantityCallback);
  var params = "order_ID=" + orderID.value + "&print_ID=" + printID + "&quantity=" + quantity.value;
  httpRequest.post(params);
}

function reviseOrderQuantityCallback () {
  viewOrder();
}

function reviseOrder (printID, quantity, manufacturer, stockNum) {
  previewPrint(printID, manufacturer, stockNum);
  var quantityInput = getElement("quantity");
  var addToOrderButton = getElement("add_to_order_button");
  if (quantityInput) {
    quantityInput.value = quantity;
    addToOrderButton.value = "Revise Order";
    addToOrderButton.setAttribute("onClick", "reviseOrderQuantity(" + printID + ")");
  }
}

function viewOrder () {
  var orderID = getElement("order_ID");
  httpRequest = new HttpRequest("view_order.php", viewOrderCallback);
  var params = "order_ID=" + orderID.value;
  httpRequest.post(params);
}

function viewOrderCallback () {
  var resultsDiv = getElement("search_results");
  var response = /* httpRequest */ this.getResponse();
  resultsDiv.innerHTML = response;
}

function addClientEmail () {
  var emailContainer = getElement("additional_clients");
  var numClientEmails = getElement("num_client_emails");
  var newEmail = document.createElement("INPUT");
  var newEmailDiv = document.createElement("DIV");
  numClientEmails.value = Number(numClientEmails.value) +1;
  var newEmailID = "client_email_" + numClientEmails.value;
  newEmail.setAttribute("id", newEmailID);
  newEmail.setAttribute("name", newEmailID);
  newEmail.setAttribute("type", "text");
  newEmail.setAttribute("size", 30);
  newEmail.setAttribute("class", "input");
  newEmailDiv.setAttribute("style", "padding-top: 4px;");
  newEmailDiv.appendChild(newEmail);
  emailContainer.appendChild(newEmailDiv);
}

function cancelSubmitOrder () {
  closeInnerWindow("submit_order_window");
}

function submitOrderToArch () {
  var orderID = getElement("order_ID");
  openInnerWindow("submit_order", "submit_order_form.php", 630, "", "Submit Order", "order_ID=" + orderID.value);
  closeInnerWindow("print_selector_window");
}

function submitOrder () {
  var email = getElement("register_email");
  var validEmails = verifyClientEmails();
  if (!validEmails || (email && !validateRegistration()))
    return;

  var form = getElement("order_submission");
  var params = getFormContents(form);
  var orderID = getElement("order_ID");
  params += "order_ID=" + orderID.value;
  httpRequest = new HttpRequest("submit_order.php", submitOrderCallback);
  httpRequest.post(params);
}

function submitOrderCallback () {
  var window = windowManager.getWindow("submit_order_window");
  window.setContents("<DIV align=\"center\">Thank you for submitting your order to Arch Framing!<P>We will review your selections and contact you with a bid.<P><INPUT type=\"button\" onClick=\"closeInnerWindow('submit_order_window')\" value=\"Close\"></DIV>");
}

function verifyClientEmails () {
  var numEmails = getElement("num_client_emails");
  var notes = getElement("client_notes");
  var error = "";
  var allValid = true;
  var validEmails = 0;
  for (var i=1; i<=numEmails.value; i++) {
    var emailInput = getElement("client_email_" + i);
    var email = trim(emailInput.value);
    if (email == "")
      continue;

    if (isValidEmail(email))
      validEmails++;
    else {
      allValid = false;
      error += "<LI>The email '" + email + "' is invalid.";
    }
  }
  var clientNotes = trim(notes.value);
  if (validEmails == 0 && clientNotes != "") {
    error += "<LI>At least one valid email must be specified to deliver your message.";
    allValid = false;
  }
  if (error != "") {
    var errorDiv = getElement("client_email_error");
    errorDiv.innerHTML = "<FONT color=\"#CC0000\">The following errors occured when processing this form:<UL>" + error + "</UL></FONT>";
  }
  return allValid;
}

function previewClientEmail () {
  var clientNotes = getElement("client_notes");
  var orderID = getElement("order_ID");
  load("client_email_preview", "preview_client_email.php", "client_notes=" + clientNotes.value + "&order_ID=" + orderID.value);
}

function loadImages () {
  var numImages = getElement("num_images");
  numImages = Number(numImages.value);
  //  numImages = 1;
  for (var i=1; i<=numImages; i++) {
    setTimeout("loadImage(" + i + ")", i*4000);
  }
}

var loaded = Array();

function loadImage (imageNum) {
  // console.log("loading image " + imageNum);
  var divide = getElement("image_" + imageNum + "_container");
  var randomNum = 0;
  while (randomNum == 0) {
    var random = Math.random() * imagesAvailable;
    random = Math.floor(random);
    var found = false;
    for (var key in loaded) {
      if (loaded[key] == random) {
        found = true;
        break;
      }
    }
    if (!found)
      randomNum = random;
  }

  loaded[imageNum] = randomNum;
  var imageName = images[randomNum].src;
  var width = widths[randomNum];
  var height = heights[randomNum];

  var adjustedHeight = height * (175/width);
  var margin = (200 - adjustedHeight)/4;
  margin = Math.floor(margin);

  var css = "{ width: 175px; margin-top: " + margin + "px; }";

  $("#image_" + imageNum).attr("src", imageName);
  $("#image_" + imageNum).css("margin-top", margin);

  $("#image_" + imageNum).fadeIn(3000, function () { changeImage(imageNum); });
}

function changeImage (imageNum) {
  var changeTime = Math.random() * 30000; // Max of 30 second stay-time.
  changeTime = Math.ceil(changeTime);

  if (changeTime < 15000)
    changeTime = 15000;

  setTimeout("changeImageSlave(" + imageNum + ")", changeTime);
}

function changeImageSlave (imageNum) {
  $("#image_" + imageNum).fadeOut(1000, function () { reloadImage(imageNum) });
}

function reloadImage (imageNum) {
  loaded[imageNum] = null;
  loadImage(imageNum);
}


function frameImage (imageNum) {
  var timeout = 500;
  setTimeout("showFrameTop(" + imageNum + ")", timeout);
  setTimeout("showFrameRight(" + imageNum + ")", 2*timeout);
  setTimeout("showFrameBottom(" + imageNum + ")", 3*timeout);
  setTimeout("showFrameLeft(" + imageNum + ")", 4*timeout);
}

function showFrameTop (imageNum) {
  var image = getStyleObject("image_" + imageNum);
  image.borderTop = "solid #FFFFFF 2px;";
}

function showFrameRight (imageNum) {
  var image = getStyleObject("image_" + imageNum);
  image.borderRight = "solid #FFFFFF 2px;";
}

function showFrameBottom (imageNum) {
  var image = getStyleObject("image_" + imageNum);
  image.borderBottom = "solid #FFFFFF 2px;";
}

function showFrameLeft (imageNum) {
  var image = getStyleObject("image_" + imageNum);
  image.borderLeft = "solid #FFFFFF 2px;";
}





