var baseUrl = null;
var ajaxUrl = null;
var proxyFilename = "form_confirmation_proxy.htm";
var help = "Please call the UNIT Help Desk at x97777 for assistance.";
var spinner = null;
var duration = 30 * 24 * 60 * 60 * 1000;
mappings = new Array(
		   {fieldName: "Email", label: "Email Address"},
		   {fieldName: "Gender", label: "Gender"},
		   {fieldName: "Status", label: "School Status"},
		   {fieldName: "Smoker", label: "Smoker?"},
		   {fieldName: "Location", label: "Property Location"},
		   {fieldName: "Type", label: "Housing Type"},
		   {fieldName: "Bedrooms", label: "Bedrooms"},
		   {fieldName: "Baths", label: "# Baths"},
		   {fieldName: "Rent_Share", label: "Prospective Roommate's Contribution to Rent"},
		   {fieldName: "Gender_Preference", label: "Gender Preference"},
		   {fieldName: "Status_Preference", label: "School Status Preference"},
		   {fieldName: "Smoking_Preference", label: "Prefer Smoker?"},
		   {fieldName: "Date", label: "Posting Date"}
		   );

Event.observe(window, 'load', initForm, false);

function initForm() {
  if($("vuForms")) {
    $("vuForms").reset();
    spinner = $("statusIndicator");
    spinner.style.visibility = "hidden";
    locateUrls();
    displayData();
  }
}

function getRadioGroupSelection(thisForm, radioGroup) {
  var checked = $(thisForm).getInputs('radio', radioGroup).find(
    function(input) {
    	return input.checked;
    }
  );
  return (checked) ? checked : null;
}

function validateForm(thisForm) {
  var field;
  var pattern;

  // Email Address Validation
  field = $F("Email").strip();
  if(field.length == 0) {
    alert("Please provide your email address.");
    $("Email").activate();
    return false;
  }
  pattern = /^.*@[\w\-\.]+\.\w+$/;
  if(!field.match(pattern)) {
    alert("Please enter a valid email address.");
    $("Email").activate();
    return false;
  }
  // Gender Validation
  field = getRadioGroupSelection(thisForm, "Gender");
  if(field == null) {
  	alert("Please select your gender");
  	$("Male").activate();
  	return false;
  }
  // School Status Validation
  field = getRadioGroupSelection(thisForm, "Status");
  if(field == null) {
  	alert("Please select your school status");
  	$("Ugrad").activate();
  	return false;
  }
  // Smoking Validation
  field = getRadioGroupSelection(thisForm, "Smoker");
  if(field == null) {
  	alert("Please indicate whether or not you smoke");
  	$("Smoker").activate();
  	return false;
  }
  // Location
  if($("Location").selectedIndex < 1) {
    alert("Please select one of the location options.");
    $("Location").activate()
    return false;
  }
  // Type
  if($("Type").selectedIndex < 1) {
    alert("Please select one the type of accomodation available.");
    $("Type").activate()
    return false;
  }
  // Bedroom Validation
  field = getRadioGroupSelection(thisForm, "Bedrooms");
  if(field == null) {
  	alert("Please select the bedroom arrangment");
  	$("Individual").activate();
  	return false;
  }
  // Bath Validation
  field = getRadioGroupSelection(thisForm, "Baths");
  if(field == null) {
  	alert("Please indicate the number of bathrooms");
  	$("B1").activate();
  	return false;
  }
  // Rent Share
  if($("Rent_Share").selectedIndex < 1) {
    alert("Please indicate the prospective roommate's expected contribution to the rent.");
    $("Rent_Share").activate()
    return false;
  }
  // Prefered Gender Validation
  field = getRadioGroupSelection(thisForm, "Gender_Preference");
  if(field == null) {
  	alert("Please indicate your gender preference for a roommate");
  	$("Male_Preference").activate();
  	return false;
  }
  // School Status Validation
  field = getRadioGroupSelection(thisForm, "Status_Preference");
  if(field == null) {
  	alert("Please indicate your school status preference for a roommate");
  	$("Ugrad_Preference").activate();
  	return false;
  }
  // Smoking Validation
  field = getRadioGroupSelection(thisForm, "Smoking_Preference");
  if(field == null) {
  	alert("Please indicate your smoking preference for a roommate");
  	$("Smoker_Preference").activate();
  	return false;
  }
  //alert("Would normally submit.");
  //return false;
  $("apply").disabled = true;
  spinner.style.visibility = "visible";
  return true;
}

function locateUrls() {
  baseUrl = location.pathname;
  if(baseUrl.substring(baseUrl.length-1) != "/") {
    baseUrl = baseUrl.substring(0, baseUrl.lastIndexOf("/")+1);
  }
  ajaxUrl = baseUrl + proxyFilename + "?template=no";
}

function displayData() {
  var success = function(transport){displayDataSuccess(transport);}
  var failure = function(){displayDataError();}
  var missing = function(){displayDataMissing();}
  var pars = "subcommand=Display&ufile=" + $("U-File").value + "&timestamp=" + $("timestamp").value;
  new Ajax.Request(ajaxUrl,
	  {
	    method: "post",
	    postBody: pars,
	    onSuccess: success,
	    onFailure: failure,
	    on404: missing
	  }
  );
}

function displayDataSuccess(transport) {
	var data = transport.responseText.strip();
	var content = "";
	var fields;
	var field;
	var rows = data.split("\n");
	if(rows.length > 0 && rows[0].length > 0) {
	  content += '<table class="curriculum">';
	  for(var i = 0; i < rows.length; i++) {
		fields = rows[i].split('","');
		if(i > 0 && !isRecent(fields[fields.length-3])) continue;
		content += '<tr>';
		for(var j = 0; j < fields.length-2; j++) {
		  field = fields[j];
	  	  field = j == 0 ? field.substring(1) : field;
	  	  field = j == fields.length-1 ? field.substring(0,field.length-1) : field;
	  	  if(i == 0) {
	  	    content += '<td class="header"><span class="vu___stylize_3">';
	  		//content += field;
			var label = field;
			$A(mappings).each(
              function(mapping) {
				if(mapping['fieldName'] == field) {
				  label = mapping['label'];
				}
			});
			content += label;
	  		content += '</span></td>';
	  	  }
	  	  else {
	  		content += '<td>';
	  		content += field;
	  		content += '</td>';
	  	  }
	    }
	    content += '</tr>';
	  }
	  content += '</table>';
	  $("formdata").innerHTML = content;
	  $("formdata").style.display = "block";
	  $("nodata").style.display = "none";
	}
	else {
	  content = "No entries available currently.";
	  $("nodata").innerHTML = content;
	  $("formdata").style.display = "none";
	  $("nodata").style.display = "block";
	}
	
}

function isRecent(entryDate) {
	var expirationDate = new Date().getTime() - duration;
	var subjectDate = new Date(entryDate).getTime();
	//alert("Expiration: " + expirationDate + ", Entry: " + subjectDate + ", is recent: " + (subjectDate >= expirationDate));
	return subjectDate >= expirationDate;
}

function displayDataError() {
	alert("Dispay data failed.\n" + help);
}

function displayDataMissing() {
	alert("Dispay data failed.\n" + help);
}

function hideData() {
	$("formdata").style.display = "none";
	$("nodata").style.display = "none";
}