

function initRotateProjects () {
	setTimeout(rotateProjects, 7000);
}

function rotateProjects () {
	$("#projects").children(":first").fadeOut("slow", function () {
		var removed = $("#projects").children(":first").remove();
		removed.appendTo("#projects");
		$("#projects").children(":first").fadeIn("slow");
	});
	initRotateProjects();
}

/***************/
/*  Promotion  */
/***************/

function promotionSubscribe () {
	var firstName = $("#first_name").val();
	var lastName = $("#last_name").val();
	var email = $("#email").val();
	var verifyEmail = $("#verify_email").val();
	var address = $("#address_1").val();
	var city = $("#city").val();
	var state = $("#state").val();
	var zipcode = $("#zipcode").val();

	var errors = "";
	if (trim(firstName) == "") {
		$("#first_name").addClass("error");
		errors += "<LI>Please enter your first name.";
	}
	else $("#first_name").removeClass("error");

	if (trim(lastName) == "") {
		$("#last_name").addClass("error");
		errors += "<LI>Please enter your first name.";

	}
	else $("#last_name").removeClass("error");

	if (!isValidEmail(email) || !isValidEmail(verifyEmail) || (email != verifyEmail)) {
		$("#email").addClass("error");
		$("#verify_email").addClass("error");
		errors += "<LI>Please enter a valid email and matching verification email.";
	}
	else {
		$("#email").removeClass("error");
		$("#verify_email").removeClass("error");
	}

	if (trim(address) == "") {
		$("#address_1").addClass("error");
		errors += "<LI>Please enter an address.";
	}
	else $("#address_1").removeClass("error");

	if (trim(city) == "") {
		$("#city").addClass("error");
		errors += "<LI>Please enter a city.";
	}
	else $("#city").removeClass("error");

	if (trim(state) == "") {
		$("#state").addClass("error");
		errors += "<LI>Please enter a state / province.";
	}
	else $("#state").removeClass("error");

	if (trim(zipcode) == "") {
		$("#zipcode").addClass("error");
		errors += "<LI>Please enter a valid zipcode.";
	}
	else $("#zipcode").removeClass("error");

	if (errors != "") {
		$("#error").html("<UL>" + errors + "</UL>").slideDown("slow");
	}
	else {
		$("#promotional").submit();
	}
	
}

/*  /Promotion. */

function classicServiceInfo () {
	$("#service_info").html("Click to learn more about Classic Car Service");
}

function europeanServiceInfo () {
	$("#service_info").html("Click to learn more about European Car Service");
}

function clearServiceInfo () {
	$("#service_info").html("");
}

/***********/
/* General */
/***********/

var httpRequest = null;

function doNothing () {}

function loadContent (page, params, initialization) {
  defaultLoadContent(page, params, initialization);
}

function loadPrivacyPolicy () {
  openCenteredWindow("privacy_policy.php", 400, 800);
}

/************/
/*  Splash  */
/************/
var splashTimeout = null;

function initRotateSplash (timeout) {
	splashTimeout = setTimeout(function () { rotateSplash(timeout) }, timeout);
}

function rotateSplash (timeout) {
	$(".splash:first").animate({ width: 0 }, 1500, function () { shuffleSplash(); });
	initRotateSplash(timeout);
}

function loadSplash (index) {
	clearTimeout(splashTimeout);
	$(".splash_control").css("background-color", "#FFFFFF");
	$(".splash").css("display", "none");	// fadeOut("fast", function () {
		$("#splash_" + index).fadeIn("fast");
		$("#splash_control_" + index).css("background-color", "#DDDDDD");
	// });
}

function shuffleSplash () {
	$(".splash:first").remove().css("width", 600).appendTo("#splash_carrier");
}

/******************/
/*  Monthly Deal  */
/******************/

var monthlyDealPrice = 0;
var monthlyDealReductionIncrement = 0;

function reduceMonthlyDealPrice () {
	var monthlyDealPriceDisplay = getElement("monthly_deal_price");
	if (!monthlyDealPriceDisplay)
		return;

	monthlyDealPrice -= monthlyDealReductionIncrement;
	var displayPrice = monthlyDealPrice + "";
	displayPrice = displayPrice.substring(0, 10);
	monthlyDealPriceDisplay.innerHTML = "Price: $ " + prettyNumber(displayPrice);
	setTimeout("reduceMonthlyDealPrice()", 1000);
}

function startMonthlyDealReduction (startPrice, reductionIncrement) {
	var monthlyDealStyle = getStyleObject("monthly_deal");
	var left = getWindowWidth()/2 + 275;
	monthlyDealStyle.left = left + "px";
	monthlyDealStyle.top = "100px";
	monthlyDealPrice = startPrice;
	monthlyDealReductionIncrement = reductionIncrement;
	reduceMonthlyDealPrice();
}

function loadMonthlyDealExplanation (event) {
	var content = "The price of this vehicle will drop <B><I>every second</I></B> until it sells!<P>Call us at (314) 567-4200 to secure our monthly special before it disappears!";
	openTooltip(event, "monthly_deal_explanation", content);
}

function closeMonthlyDealExplanation () {
  closeTooltip("monthly_deal_explanation");
}

function showCurrencyConversions (event, AUD, CAD, EUR, GBP) {
	var content = "$ " + AUD + " AUD<BR>$ " + CAD + " CAD<BR>&euro; " + EUR + "<BR>&pound; " + GBP;
	openTooltip(event, "currency_conversions", content);
	return;
}

function openTooltip (event, tooltipID, content) {
  if (!event) var event = window.event;
  var tooltip = document.createElement("DIV");
  tooltip.setAttribute("id", tooltipID);

  tooltip.innerHTML = content;
  var x = event.clientX;
  var y = event.clientY + 15;
  tooltip.setAttribute("class", "note");
  tooltip.setAttribute("className", "note");
  document.body.appendChild(tooltip);
  absoluteMove(tooltipID, x, y);
}

function closeTooltip (tooltipID) {
  var tooltip = getElement(tooltipID);
  document.body.removeChild(tooltip);
}

function hideCurrencyConversions () {
	closeTooltip("currency_conversions");
}

/****************/
/*  Newsletter  */
/****************/

function unsubscribe (subscriptionID, email) {
	var reason = -1;
	var unsubscribeReasons = getElement("unsubscribe_reasons");
	for (var i=0; i<unsubscribeReasons.reason.length; i++) {
		if (unsubscribeReasons.reason[i].checked) {
			reason = i;
			break;
		}
	}
	if (reason < 0) {
		alert("Please specify a reason.");
		return;
	}

	var other = getElement("other");
	window.location = "unsubscribe_script.php?sid=" + subscriptionID + "&addr=" + email + "&reason=" + reason + "&exp=" + other.value;
}

/**********************/
/*  Vehicle Overview  */
/**********************/

function expandInventoryGallery () {
  var imageStyle = getStyleObject("inventory_gallery");
  imageStyle.position = "relative";
//  imageStyle.left = "-105px";
  if (IE)
    imageStyle.left = "-305px";
  else imageStyle.left = "-205px";
  imageStyle.width = "800px";
}

function contractInventoryGallery () {
  var imageStyle = getStyleObject("inventory_gallery");
  imageStyle.position = "";
  imageStyle.width = "590px";
}

/*************/
/* Inventory */
/*************/

function select (stockNum) {
  var divStyle = getStyleObject("vehicle_" + stockNum);
  divStyle.backgroundColor = "#CCCCCC";
  divStyle.cursor = "hand";
}

function deselect (stockNum) {
  var divStyle = getStyleObject("vehicle_" + stockNum);
  divStyle.backgroundColor = "#DDDDDD";
}

function delayedPreview (vehicleID, stockNum) {
  setTimeout("delayedPreviewCallback('" + vehicleID + "', '" + stockNum + "')", 1200);
}

function delayedPreviewCallback (vehicleID, stockNum) {
  openInnerWindow("vehicle_preview", "vehicle_overview.php?titlebar=0&vehicle_ID=" + vehicleID + "&stock_num=" + stockNum, 810, "", "", "vehicle_ID=" + vehicleID + "&stock_num=" + stockNum, "", "", 1, 1);
}

function preview (vehicleID) {
  window.location = "vehicle_overview.php?vehicle_ID=" + vehicleID;
  // openInnerWindow("vehicle_preview", "vehicle_overview.php?titlebar=0&vehicle_ID=" + vehicleID, 820, "", "Vehicle Details", "", "", "", 1, 1);

  /* Load window without bookmarking. */
/*
  var preview = new InnerWindow("vehicle_preview", "vehicle_overview.php?titlebar=0&vehicle_ID=" + vehicleID, 810, 0);
  preview.open();
*/

  /* Refresh page, then load window. */
  // window.location = "main.php?vehicle_ID=" + vehicleID;
}

function viewSimilar (model) {
  searchKeywords(model);
  // window.location = "main.php?search=" + model;
}

function loadEmailAFriendForm (vehicleID) {
  load("email_a_friend", "email_a_friend_form.php", "vehicle_ID=" + vehicleID);
}

function addFriendEmail () {
  var additionalEmails = getElement("additional_emails");
  var numEmails = getElement("num_emails");
  var newEmailDiv = document.createElement("DIV");
  numEmails.value = Number(numEmails.value) + 1;
  var id = "friend_email_" + numEmails.value;
  newEmailDiv.innerHTML = "<INPUT style=\"margin-top: 3px;\" type=\"text\" size=20 id=\"" + id + "\" name=\"" + id + "\">";
  additionalEmails.appendChild(newEmailDiv);
}

function emailAFriend (vehicleID) {
  var email = getElement("friend_email_1");
  var yourName = getElement("your_name");
  if (email.value == "" || yourName.value == "") {
    alert("Please enter your name and at least one email.");
    return;
  }
  var emailAFriendButton = getElement("email_a_friend_button");
  emailAFriendButton.disabled = true;
  var form = getElement("email_a_friend_form");
  httpRequest = new HttpRequest("../email_a_friend.php", emailAFriendCallback);
  httpRequest.setParameter("vehicle_ID", vehicleID);
  var params = getFormContents(form);
  httpRequest.post(params);
}

function emailAFriendCallback () {
  var emailAFriendDiv = getElement("email_a_friend");
  var vehicleID = httpRequest.getParameter("vehicle_ID");
  emailAFriendDiv.innerHTML = "Your email has been sent.<BR><A href=\"javascript: loadEmailAFriendForm(" + vehicleID + ")\">Send Another Email</A>";
}

/******************/
/*  View Similar  */
/******************/

function prevSimilar () {
  rotateSimilar(-1);
}

function nextSimilar () {
  rotateSimilar(1);
}

function rotateSimilar (delta) {
  var currentSimilar = getElement("current_similar");
  var numSimilar = getElement("num_similar");

  var newSimilarNum = Number(currentSimilar.value) + Number(delta);
  if (newSimilarNum == 0)
    newSimilarNum = numSimilar.value;
  else if (newSimilarNum > numSimilar.value)
    newSimilarNum = 1;

  var oldSimilar = getStyleObject("similar_" + currentSimilar.value);
  var newSimilar = getStyleObject("similar_" + newSimilarNum);
  oldSimilar.display = "none";
  newSimilar.display = "block";
  currentSimilar.value = newSimilarNum;
}

function closeSimilar () {
  var similarDiv = getStyleObject("similar_vehicles");
  similarDiv.visibility = "hidden";
}

/**************/
/*  Bookmark  */
/**************/

function bookmark (URL, pageName) {
  if (window.sidebar) { // Mozilla Firefox Bookmark
    window.sidebar.addPanel(pageName, URL,"");
  }
  else if( window.external ) { // IE Favorite
    window.external.AddFavorite(URL, pageName);
  }
//  else if(window.opera && window.print) { // Opera Hotlist
//    return true;
//  }
  else { 
   alert("Sorry! Your browser doesn't support this function.");
  }
}

function addSiteToFavorites () {
  bookmark("http://www.classiccarstudio.com/main.php", "Classic Car Studio - Classic and Exotic Cars");
}

function addVehicleToFavorites (description, vehicleID) {
  bookmark("http://www.classiccarstudio.com/main.php?vehicle_ID=" + vehicleID, description + " at Classic Car Studio");
}

/*************/
/*  GT350 R  */
/*************/

var currentStripeColor = null;
var currentBodyColor = null;

function viewStripeColor (stripeID, colorName) {
  if (currentStripeColor) {
    var prevStripeStyle = getStyleObject(currentStripeColor);
    prevStripeStyle.display = "none";
  }
  var stripeStyle = getStyleObject(stripeID);
  var stripeColor = getElement("stripe_color");
  stripeColor.innerHTML = colorName;
  stripeStyle.display = "block";
  currentStripeColor = stripeID;
}

function viewBodyColor (bodyID, colorName) {
  if (currentBodyColor) {
    var prevBodyStyle = getStyleObject(currentBodyColor);
    prevBodyStyle.display = "none";
  }
  var componentStyle = getStyleObject("components");
  var bodyStyle = getStyleObject(bodyID);
  var bodyColor = getElement("body_color");
  bodyColor.innerHTML = colorName;
  componentStyle.display = "block";
  bodyStyle.display = "block";
  currentBodyColor = bodyID;
}

function reviewEngineSelection (value) {
  reviewComponentSelection("engine", value);
}

function reviewBrakeSelection (value) {
  reviewComponentSelection("brakes", value);
}

function reviewFrontSuspensionSelection (value) {
  reviewComponentSelection("front_suspension", value);
}

function reviewRearSuspensionSelection (value) {
  reviewComponentSelection("rear_suspension", value);
}

function reviewSteeringSelection (value) {
  reviewComponentSelection("steering", value);
}

function reviewComponentSelection (componentName, selected) {
  var currentlySelected = getElement("current_" + componentName);
  var currentlySelectedStyle = getStyleObject(currentlySelected.value);
  var newlySelectedStyle = getStyleObject(selected);
  var currentTotal = getElement("current_total");
  var totalDisplay = getElement("configuration_total");
  var previousCost = getElement(currentlySelected.value + "_cost");
  var newCost = getElement(selected + "_cost")
  currentlySelectedStyle.display = "none";
  newlySelectedStyle.display = "block";
  currentlySelected.value = selected;
  var newTotal = (Number(currentTotal.value) + Number(newCost.value)) - Number(previousCost.value);
  currentTotal.value = newTotal;
  totalDisplay.innerHTML = "$ " + prettyNumber(newTotal);
}

/**********/
/*  News  */
/**********/

var maxNewsHeight = 220;
var newsHeight = maxNewsHeight;
var newsDelta = 10;
var newsDeltaTime = 50;
var initialNewsPause = 2000;
var newsExposure = 10000;
var newsReloadPause = 2000;

function cycleNews () {
  setTimeout("raiseNews()", initialNewsPause);
}

function raiseNews () {
  if (newsHeight > 0) {
    var newsDiv = getStyleObject("news_carrier");
    newsHeight -= newsDelta;
    newsDiv.top = newsHeight + "px";
    setTimeout("raiseNews()", newsDeltaTime);
  }
  else setTimeout("lowerNews()", newsExposure);
}

function lowerNews () {
  if (newsHeight < maxNewsHeight) {
    var newsDiv = getStyleObject("news_carrier");
    newsHeight += newsDelta;
    newsDiv.top = newsHeight + "px";
    setTimeout("lowerNews()", newsDeltaTime);
  }
  else { 
    switchNews(1);
    setTimeout("raiseNews()", newsReloadPause);
  }
}

function switchNews (direction) {
  var currentHeadline = getElement("current_headline");
  var numHeadlines = getElement("num_headlines");

  var oldHeadlineNum = currentHeadline.value;
  var newHeadlineNum = Number(oldHeadlineNum) + direction;
  if (newHeadlineNum > Number(numHeadlines.value))
    newHeadlineNum = 1;
  else if (newHeadlineNum == 0)
    newHeadlineNum = numHeadlines.value;

  var oldHeadlineStyle = getStyleObject("headline_" + oldHeadlineNum);
  var newHeadlineStyle = getStyleObject("headline_" + newHeadlineNum);
  oldHeadlineStyle.display = "none";

  var splash = getElement("splash");
  if (splash)
    newHeadlineStyle.display = "block";

  currentHeadline.value = newHeadlineNum;
}

/******************/
/*  Testimonials  */
/******************/

function flipTestimonials () {
  var testimonial = getElement("testimonial");

  /* If content has changed from testimonials... */
  if (!testimonial)
    return;

  var testimonialDiv = getElement("testimonial_" + testimonial.value);
  var numTestimonials = getElement("num_testimonials");

  var oldTestimonialNum = testimonial.value;
  var newTestimonialNum = Number(testimonial.value)+1;
  if (Number(testimonial.value) >= Number(numTestimonials.value))
    newTestimonialNum = 1;

  testimonial.value = newTestimonialNum;
  var pause = 5000;
  setTimeout("flipTestimonialSlave(" + oldTestimonialNum + ", " + newTestimonialNum + ")", pause)
}

function flipTestimonialSlave (oldTestimonialNum, newTestimonialNum) {
  var testimonial = getElement("testimonial");
  if (!testimonial)
    return;

  var oldTestimonial = getStyleObject("testimonial_" + oldTestimonialNum);
  var newTestimonial = getStyleObject("testimonial_" + newTestimonialNum);
  oldTestimonial.display = "none";
  newTestimonial.display = "block";
  flipTestimonials();
}

/***************/
/*  Insurance  */
/***************/

function submitInsuranceQuote () {
  var form = getElement("insurance_application");
  form.action = "submit_insurance_application.php";
  form.submit();
}

var shift = 0;
var descriptionShift = 0;
var playing = 0;

function setControlMessage (message) {
  var controlMessage = getElement("control_message");
  controlMessage.innerHTML = message;
}

function play () {
  playing = 1;
  playLoop();
}

function playLoop () {
  if (playing == 0)
    return;
  nextPicture();
  setTimeout("playLoop()", 2000);
}

function stop () {
  playing = 0;
}

function nextPicture () {
  scrollInventoryPicture(1);
}

function prevPicture () {
  scrollInventoryPicture(-1);
}

function scrollInventoryPicture (direction) {
  var numPhotos = getElement("num_images");
  var currentPhoto = getElement("current_image");
  var picture = Number(currentPhoto.value) + Number(direction);

  if (Number(picture) == 0 || picture == "0")
    picture = numPhotos.value;
  else if (picture > numPhotos.value)
    picture = 1;

  setInventoryPicture(picture);
}

function flashLoading (time, message) {
  if (typeof(time) == "undefined")
    time = 5000;

  if (typeof(message) == "undefined")
    message = "Loading...";

  var flashTime = 1000;
  var loadingDiv = getElement("loading");
/*
  if (!loadingDiv) {
    var width = 200;
    var height = 100;
    var screenWidth = getWindowWidth();
    var screenHeight = getWindowHeight();
    var left = screenWidth/2 - width/2;
    var top = screenHeight/2 - height/2;
    loadingDiv = document.createElement("DIV");
    loadingDiv.setAttribute("style", "position: absolute; left: " + left + "px; top: " + top + "px; background-color: #FFFFFF; border: solid #333333 1px; width: " + width + "px; height: " + height + "px");
    document.body.appendChild(loadingDiv);
  }
*/
  var newTime = Number(time) - Number(flashTime);
  if (true || (newTime/1000)%2 == 0) {
    loadingDiv.innerHTML = "<FONT size=+1><B>" + message + "</B></FONT>";
  }
  else loadingDiv.innerHTML = "<FONT size=+1 color=\"#FFFFFF\"><B>" + message + "</B></FONT>";
  if (newTime > 0)
    setTimeout("flashLoading(" + newTime + ")", flashTime);
  else loadingDiv.innerHTML = "&nbsp;"; // document.body.removeChild(loadingDiv);
}

function setInventoryPicture (picture) {
  flashLoading(3000);
  var stockNumber = getElement("stock_num");
  var currentPhoto = getElement("current_image");
  var baseURL = "http://www.classiccarstudio.com/images/auction/" + stockNumber.value + "/";
  var photo = getElement("inventory_gallery");

  var source = baseURL + picture + ".jpg";
  currentPhoto.value = picture;
  photo.src = source;
}

function loadVehicle (stockNum) {
  httpRequest = new HttpRequest("/get_vehicle_overview.php", loadVehicleCallback);
  var params = "stock_num=" + stockNum;
  httpRequest.post(params);
}

function scrollPhotoFrame () {
  var magnitudeAdjustment = 60;
  var frameStyle = getStyleObject("photo_frame");
  var width = stripTrailing(frameStyle.width, 2);
  var bias = (width/2 - this.x)/magnitudeAdjustment;
  if (Math.abs(bias) < 3.5) {
    setShift(0);
    return;
  }
  if (bias > 6)
    bias = 6;
  else if (bias < -6)
    bias = -6;

  var carrierStyle = getStyleObject("photo_carrier");
  var leftStop = stripTrailing(carrierStyle.width, 2);
  leftStop = -1*(Number(leftStop) - Number(width));

  if (shift == 0)
    startShift(bias, leftStop, 0);
  else setShift(bias);
}

function loadVehicleCallback () {
  var overviewDiv = getElement("vehicle_overview_frame");
  var response = httpRequest.getResponse();
  // alert(response);
  overviewDiv.innerHTML = response;
}

function setShift (newShift) {
  shift = newShift;
}

function setDescriptionShift (shift) {
  descriptionShift = shift;
}

function startShift (deltaX, leftStop, rightStop) {
  setShift(deltaX);
  shiftInventory(deltaX, leftStop, rightStop);
}

function shiftInventory (deltaX, leftStop, rightStop) {
  var shifted = shiftHorizontal("photo_carrier", deltaX, leftStop, rightStop);
  if (!shifted) {
    setShift(0);
    return;
  }
  if (shift != 0 /* && shift == deltaX */)
    setTimeout("shiftInventory(" + deltaX + ", " + leftStop + ", " + rightStop + ")", 20);
}

function startDescriptionShift (deltaY, topStop, bottomStop) {
  setDescriptionShift(deltaY);
  shiftDescription(deltaY, topStop, bottomStop);
}

function shiftDescription (deltaY, topStop, bottomStop) {
  var shifted = shiftVertical("description", deltaY, topStop, bottomStop);
  if (!shifted) {
    setDescriptionShift(0);
    return;
  }
  if (descriptionShift != 0) {
    setTimeout("shiftDescription(" + deltaY + ", '" + topStop + "', '" + bottomStop + "')", 20);
  }
}

function shiftHorizontal (divName, deltaX, leftStop, rightStop) {
  return moveDivide(divName, deltaX, 0, leftStop, rightStop, 0, 0);
}

function shiftVertical (divName, deltaY, topStop, bottomStop) {
  return moveDivide(divName, 0, deltaY, 0, 0, topStop, bottomStop);
}

function moveDivide (divName, deltaX, deltaY, leftStop, rightStop, topStop, bottomStop) {
  return shiftDivide(divName, deltaX, deltaY, leftStop, rightStop, topStop, bottomStop);
}

function shiftDivide (divName, deltaX, deltaY, leftStop, rightStop, topStop, bottomStop) {
  var divideStyle = getStyleObject(divName);
  leftStop = (typeof(leftStop) != "undefined") ? leftStop : -1 * stripTrailing(divideStyle.width);
  rightStop = (typeof(rightStop) != "undefined") ? rightStop : 0;
  topStop = (typeof(topStop) != "undefined") ? topStop : 9999999999;
  bottomStop = (typeof(bottomStop) != "undefined") ? bottomStop : -9999999999;

  if (!divideStyle)
    return;

  var left = divideStyle.left;
  var top = divideStyle.top;
  if (bottomStop == "HEIGHT") {
    var obj = getElement(divName);
    var height;
    if (document.all) {
      var object = getElement(divName);
      height = document.all[divName].offsetHeight;
      height = 700;
    }
    else  {
      height = document.defaultView.getComputedStyle(obj, "").getPropertyValue("height");
      height = height.substring(0, height.length-2);  // Remove trailing "px"
    }
    bottomStop = -1 * (height-200); // 200: Leave some text in the display box when completely scrolled up
  }
  var leftPrime = Number(left.substring(0, left.length-2)) + Number(deltaX);
  var topPrime = Number(top.substring(0, top.length-2)) + Number(deltaY);
  divideStyle.position = "relative";
  
  var shifting = false;
  if (deltaX) {
    if (((deltaX < 0) && (leftPrime > leftStop)) || ((deltaX > 0) && (leftPrime < rightStop))) {
      // alert(leftPrime); return;
      divideStyle.left = leftPrime + "px";
      shifting = true;
    }
  }
  if (deltaY) {
    if ((topPrime <= topStop) && (topPrime >= bottomStop)) {
      divideStyle.top = topPrime + "px";
      shifting = true;
    }
  }
  return shifting;
}

function moveDivideTo (divName, x, y) {
  var divideStyle = getStyleObject(divName);
  if (!divideStyle)
    return;
  divideStyle.position = "relative";
  divideStyle.left = x + "px";
  divideStyle.top = y + "px";
}

/*************/
/* Subscribe */
/*************/

function addInterest () {
  httpRequest = new HttpRequest("/add_interest.php", addInterestCallback);
  var interestNum = getElement("num_interests");
  interestNum.value++;
  var params = "interest_num=" + interestNum.value;
  httpRequest.post(params);
}

function addInterestCallback () {
  var response = httpRequest.getResponse();
  var interestsDiv = getElement("interests");
  var newInterestDiv = document.createElement("DIV");
  newInterestDiv.innerHTML = response;
  interestsDiv.appendChild(newInterestDiv);
}

function submitSubscription () {
  var form = getElement("subscribe_form");
  var params = getFormContents(form);
  httpRequest = new HttpRequest("/subscribe_email.php", submitSubscriptionCallback);
  httpRequest.post(params);
}

function submitSubscriptionCallback () {
  var response = httpRequest.getResponse();
  loadContent("subscription_thanks.php", "");
}

/***********/
/* CONTACT */
/***********/

function clearMessage () {
  var confirmation = confirm("Are you sure you want to clear this form? This operation cannot be undone.");
  if (!confirmation)
    return;
  clearMessageForm();
}

function clearMessageForm () {
  var email = getElement("email");
  var vehicle = getElement("vehicle");
  var message = getElement("message");
  email.value = "";
  vehicle.value = "";
  message.value = "";
}

function sendMessage () {
  var email = getElement("email");
  var telephone = getElement("telephone");
  var vehicle = getElement("vehicle");
  var message = getElement("message");
  var testMessage = message.value.toLowerCase();

  if (email.value == "" || message.value == "") {
    alert("Please fill out your email address and a message.");
    return;
  }
  else if (testMessage.indexOf(" seo ") != -1 || (testMessage.indexOf("traffic") != -1 && testMessage.indexOf("website") != -1))  {
    alert("We are not interested in solicitations for web or SEO services.");
    return;
  }

  httpRequest = new HttpRequest("/send_message.php", sendMessageCallback);
  var params = "email=" + email.value + "&telephone=" + telephone.value + "&vehicle=" + vehicle.value + "&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);
  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>";
}

/**********/
/* F.A.Q. */
/**********/

function setFAQAnswer (answer) {
  var answerDiv = getElement("faq_answer");
  answerDiv.innerHTML = answer;
}

/****************/
/* Listing Prep */
/****************/

function moveGallery (deltaX, deltaY) {
  var galleryLeft = getElement("gallery_left");
  var galleryTop = getElement("gallery_top");
  galleryLeft.value = Number(galleryLeft.value) + Number(deltaX);
  galleryTop.value = Number(galleryTop.value) + Number(deltaY);
  shiftDivide("gallery_container", deltaX, deltaY);
}

function submitPictureReview () {
  var photoForm = getElement("photo_form");
  photoForm.submit();
}

function deletePicture (pictureNum) {
  var deleted = getElement("delete_" + pictureNum);
  var deletedPicture = getElement("photo_" + pictureNum);
  var deletedPictureStyle = getStyleObject("photo_" + pictureNum);
  var height = 100;
  var opacity = 0.4;
  if (!deleted.checked) {
    height = 450;
    opacity = 1.0;
  }
  deletedPicture.setAttribute("height", height);
  deletedPictureStyle.opacity = opacity;
}

function checkDeleted (pictureNum) {
  var targetDeleted = getElement("delete_" + pictureNum);
  if (targetDeleted.checked) {
    alert("You cannot alter a deleted photo.");
    return true;
  }
  return false;
}

function useAsGallery (pictureNum, galleryFile) {
  var useAsGallery = getElement("use_" + pictureNum + "_gallery");
  if (!useAsGallery.checked) {
    useAsGallery.checked = true;
    return;
  }
  if (checkDeleted(pictureNum)) {
    useAsGallery.checked = false;
    return;
  }
  var numPhotosHidden = getElement("num_photos");
  var numPhotos = Number(numPhotosHidden.value);
  var galleryPhoto = getElement("gallery_photo");
  galleryPhoto.setAttribute("src", galleryFile);
  for (i=1; i<=numPhotos; i++) {
    var useAsGallery = getElement("use_" + i + "_gallery");
    if (i != pictureNum)
      useAsGallery.checked = false;
  }
}

function movePicture (pictureNum, direction) {
  if (checkDeleted(pictureNum)) return;   
  var targetPicture = getElement("photo_" + pictureNum);
  var destinationNum = Number(pictureNum) + Number(direction);
  var deleted = getElement("delete_" + destinationNum);
  while (deleted && deleted.checked) {
    destinationNum = Number(destinationNum) + Number(direction);
    deleted = getElement("delete_" + destinationNum);
  }
  var destinationPicture = getElement("photo_" + destinationNum);

  if (!destinationPicture)
    return;

  var targetSrc = targetPicture.getAttribute("src");
  var destinationSrc = destinationPicture.getAttribute("src");
  targetPicture.setAttribute("src", destinationSrc);
  destinationPicture.setAttribute("src", targetSrc);
  httpRequest = new HttpRequest("/reorder_template_photo.php", reorderPhotoCallback);
  var params = "one=" + targetSrc + "&two=" + destinationSrc;
  httpRequest.post(params);
}

function reorderPhotoCallback () {
/*
  var response = httpRequest.getResponse();
  alert(response);
*/
}

function search () {
  var keywords = getElement("keyword_search");
  searchKeywords(keywords.value);
}

function searchKeywords (keywords) {
  window.location = "search.php?search=" + keywords;
  // httpRequest = new HttpRequest("/results.php", loadCallback);

  // var params = "where=WHERE visible = '1' AND (make LIKE '" + keywords + "%' OR model LIKE '" + keywords + "%' OR submodel LIKE '" + keywords + "%')"; // OR description LIKE '%" + keywords.value + "%')";
  // alert(params);
  // httpRequest.post(params);
  // loadContent("results.php", params);
}

function expandCategory (category) {
  window.location = "make.php?make=" + category;
  /*
  httpRequest = new HttpRequest("/script/get_inventory_models.php", expandCategoryCallback);
  httpRequest.setParameter("category", category);
  var params = "make=" + category;
  httpRequest.post(params);
  */
}

function expandCategoryCallback () {
  var category = httpRequest.getParameter("category");
  var response = httpRequest.getResponse();
  var categoryDiv = getElement(category + "_category");
  categoryDiv.innerHTML = response;
  loadMake(category);
}

function collapseCategory (category) {
  var categoryDiv = getElement(category + "_category");
  categoryDiv.innerHTML = "<A href='javascript: expandCategory(\"" + category + "\")'>" + category + "</A>";
}

function loadMake (make) {
  // httpRequest = new HttpRequest("/results.php", loadCallback);
  var params = "where=WHERE visible = '1' AND make = '" + make + "'";
  // httpRequest.post(params);
  loadContent("results.php", params);
}

function loadModel (make, model) {
  // httpRequest = new HttpRequest("/results.php", loadCallback);
  var params = "where=WHERE visible = '1' AND make = '" + make + "' AND model = '" + model + "'";
  // httpRequest.post(params);
  loadContent("results.php", params);
}

function loadResultsPage (where, title, page) {
  var params = "where=" + where + "&title=" + title + "&page=" + page;
  loadContent("results.php", params);
  // httpRequest = new HttpRequest("/results.php", loadCallback);
  // httpRequest.post(params);
}

function resizeFrame () {
  var frameStyle = getStyleObject("frame");
  var windowHeight = getWindowHeight();
 alert(windowHeight);
  frameStyle.height = windowHeight + "px";
}

/*************/
/*           */
/*  Project  */
/*           */
/*************/

function expandProjectGallery () {
	var gallery = getElement("gallery");
	var imageID = getElement("gallery_ID");
	window.open("/view_image.php?image_ID=" + imageID.value);
}

function loadProjectGallery (url, imageID) {
	var gallery = getElement("gallery");
	var imageIDInput = getElement("gallery_ID");
	imageIDInput.value = imageID;
	gallery.setAttribute("src", url);
}
