// URLs used in Javascript calls further in the code to retrieve information from a server...
// Reference the find_person_at_uva directory within your web site. 
var ldapSearchURL = "http://www2.lib.virginia.edu/purchaserequest/find_person_at_uva/ldap.php";
//var ldapSearchURL = "http://ammdev.lib.virginia.edu/purchaserequest/find_person_at_uva/ldap.php";

// Contact the purchase request form's site and have it contact the MOTS web service to get vendor
// data. Then when the PRF site gets the vendor information it will send it back to the client.
var vendorDataURL = "http://www2.lib.virginia.edu/purchaserequest/js/vendorXML.php";
//var vendorDataURL = "http://ammdev.lib.virginia.edu/purchaserequest/js/vendorXML.php";

var vendorsArray = new Array();	// used by the vendor autocomplete "widget"
var selectOption = new String(); 	// holds the state of the format selection list at any given time.

// JQUERY: Execute this when the page is loaded.
$(document).ready(function(){
	
	// Have the form be sure to validate when submitted
	$('#purchaseRequest').validate();
	
	// Set the focus to the first form field
	$('#computing_id')[0].focus();
	// If we are returning to the form field from the thank you page, 
	// then we want to prefill the user's information
	if ($('#computing_id').val() != '') {
		uvaComputingIdChanged();
	}
	
	// Load vendor information for auto-complete use if a video is requested.
	$.get(vendorDataURL, {}, function(xml) {
		var vendorCount = $('vendor_count',xml).text();
		if (vendorCount > 0) {
			$('vendor_name',xml).each(function() {
				vendorsArray.push($(this).text());
			});
		}
	});
	//YUI object for autocompletion of vendor
	var vendorData = new YAHOO.util.LocalDataSource(vendorsArray);
	var vendorAutoCompletion = new YAHOO.widget.AutoComplete("video_vendor","vendorAutoComplete",vendorData);
	vendorAutoCompletion.animVert = true;	// display vendors vertically
	vendorAutoCompletion.queryDelay = 0.1;	// key input events trigger ASAP response
	vendorAutoCompletion.useIFrame = true;	// work around for IE6 bug regarding selects and higher z-index
	vendorAutoCompletion.useShadow = true;
	vendorAutoCompletion.minQueryLength = 2; // minimum number of characters before displaying
	vendorAutoCompletion.maxResultsDisplayed = 5;	// maximum number of vendors displayed at any time
});

function hideAllFormatDetails() {
	$('#book').hide();
	$('#dissertation_or_thesis').hide();
	$('#journal_subscription').hide();
	$('#music_recording').hide();
	$('#music_score').hide();
	$('#other').hide();
	$('#spoken-word_recording').hide();
	$('#video').hide();
}

function showFormatDetails(format) {
	$('#biblSection').show();
	$('#instructions').show();
	$('#uniform_have_citation').show();
	if (format == "Book") {
		$('#book').show();
		$('#book_title')[0].focus();
	} else if (format == "Dissertation or Thesis") {
		$('#dissertation_or_thesis').show();
		$('#dissertation_or_thesis_title')[0].focus();
	} else if (format == "Journal Subscription") {
		$('#journal_subscription').show();
		$('#journal_subscription_title')[0].focus();
	} else if (format == "Music Recording") {
		$('#music_recording').show();
		$('#music_recording_title')[0].focus();
	} else if (format == "Music Score") {
		$('#music_score').show();
		$('#music_score_title')[0].focus();
	} else if (format == "Other") {
		$('#other').show();
		$('#other_title')[0].focus();
	} else if (format == "Spoken-word Recording") {
		$('#spoken-word_recording').show();
		$('#spoken-word_recording_title')[0].focus();
	} else if (format == "Video") {
		$('#video').show();
		$('#video_title')[0].focus();
	}
	$('#common_fields').show();
	$('#formatHelp').show();
	// Make sure the citation details are reset
	$('#have_citation').val('');
	$('#have_citation').attr('checked',false);
	$('#uniform_citation').show();
	$('#citation').val('');
	$('#uniform_citation').hide();
}

function chooseBibliographicInput(selectObj) {
	selectOption = selectObj.options[selectObj.selectedIndex].text;
	hideAllFormatDetails();
	if (selectOption == "Choose one") {
		$('#biblSection').hide();
		$('#formatHelp').hide();
	} else {
		showFormatDetails(selectOption);
	}
}

function isValidSSN(value) {
    var re = /^([0-6]\d{2}|7[0-6]\d|77[0-2])([ \-]?)(\d{2})\2(\d{4})$/;
    if (!re.test(value)) { return false; }
    var temp = value;
    if (value.indexOf("-") != -1) { temp = (value.split("-")).join(""); }
    if (value.indexOf(" ") != -1) { temp = (value.split(" ")).join(""); }
    if (temp.substring(0, 3) == "000") { return false; }
    if (temp.substring(3, 5) == "00") { return false; }
    if (temp.substring(5, 9) == "0000") { return false; }
    return true;
}

function noSSN(theField) { 
  var value = theField.value;
  if (isValidSSN(value)) {
    theField.value = "";
    alert("Please don't give us your Social Security Number");
    $('#computing_id')[0].focus();
  } else {
  	uvaComputingIdChanged();
  } 
  return true;
}

// Toggle citation display off or on. 
// NOTE: Since an onclick event is happening the box never gets its value assigned.
// So this must be done here to make sure when the form is submitted that we get a value
// indicating the box was checked.
function toggleCitationDisplay(chkBox) {
	if (chkBox.checked) {
		hideAllFormatDetails();
		$('#instructions').hide();
		$('#uniform_citation').show();
		$('#citation')[0].focus();
		$('#have_citation').val('yes');
	} else {
		$('#have_citation').val('');
		// selectOption is a global variable that is set when a format is specified.
		showFormatDetails(selectOption);
	}
}

// When the UVA computing id field is updated on your form, proceed to do what is
// found in this function. NOTE: Replace computing_id in the $.get line with the 
// name of your form field that contains the UVA computing id.
function uvaComputingIdChanged() {
	$.getJSON(ldapSearchURL, {user: $('#computing_id').val()}, function(jsonData) {
			// identify the user affiliation
			var affiliation = new String(jsonData.affiliation);
			// user was found so prefill the name and email form field values
			// choose the appropriate affiliation
			if (jsonData.nickname == '') {
				$('#name').attr('value',jsonData.firstName+' '+jsonData.lastName);
			} else {
				$('#name').attr('value',jsonData.nickname+' '+jsonData.lastName);
			}
			$('#email').attr('value',jsonData.email);
			// update the affiliation selection list to reflect the person's
			// first unselect all the options... then select based on affiliation
			$("#affiliation").selectOptions('0',true);
			$("#affiliation").selectOptions('1',true);
			$("#affiliation").selectOptions('2',true);
			$("#affiliation").selectOptions('3',true);
			$("#affiliation").selectOptions('4',true);
			if (affiliation.search(/faculty/i) >= 0) {
				$("#affiliation").selectOptions('1');
			} else if (affiliation.search(/undergraduate/i) >= 0) {
				$("#affiliation").selectOptions('3');
			} else if (affiliation.search(/graduate/i) >= 0) {
				$("#affiliation").selectOptions('2');
			} else if (affiliation.search(/staff/i) >= 0) {
				$("#affiliation").selectOptions('4');
			} else {
				$("#affiliation").selectOptions('0');
			}
	});
}
