

// On page load, this makes an AJAX call to the Boston Scientific app to get the items for the dropdown
// URL to directly link list all is eg http://localhost:8080/Microsite/DownloadCenter.htm?filterOne=-1&filterTwo=-1&downloadCenterName=DC1
function setup_download_center(){
	
	var request = createRequest();
	var downloadCenterName = document.getElementById("download_center_name").innerHTML;
	var currentUrl = location.pathname;
	request.open("GET", "/DownloadCenter.bsci?method=setup&downloadCenterName=" + encodeURIComponent(downloadCenterName) + "&url=" + currentUrl, true);	

	// if filter parameters were set, then the onreadystatechange should set the filters on the page and call search too.
	var filterOne = getURLParam("filterOne");
	var filterTwo = getURLParam("filterTwo");
	if (filterOne == "")
		filterOne = -1;
	if (filterTwo == "")
		filterTwo = -1;	
	request.onreadystatechange = function(){setup_download_center_2(request, filterOne, filterTwo);};
	request.send(null);
}

// On hitting search button, this makes an AJAX call to the Boston Scientific app to get the search results
function search_download_center(){
	var filterOne = document.getElementById('select_level_1');
	var filterOneParameter = filterOne.options[filterOne.selectedIndex].value;
	var filterTwo = document.getElementById('select_level_2');
	var filterTwoParameter = filterTwo.options[filterTwo.selectedIndex].value;
	var sortBy = document.getElementById('sort_by');
	var sortByParameter = sortBy.options[sortBy.selectedIndex].value;
	var downloadCenterName = document.getElementById("download_center_name").innerHTML;
	var currentUrl = location.pathname;
	search_download_center2(filterOneParameter, filterTwoParameter, sortByParameter, downloadCenterName, currentUrl);
}

// Back Button Support
// To ensure the state of a specific search is preserved, we need to have a search call with all parameters preserved
function search_download_center2(filterOneParameter, filterTwoParameter, sortByParameter, downloadCenterName)
{
	var currentUrl = location.pathname;

	// Back Button Support
	dhtmlHistory.add(encodeURI("search_download_center2("+filterOneParameter+","+filterTwoParameter+",'"+sortByParameter+"','"+downloadCenterName + "');").replace(/\(/g, "%28").replace(/\)/g, "%29").replace(/'/g, "%27"), 'Results [js]');

	// Make sure the selected values are displayed in the dropdown
	var filterOne = document.getElementById('select_level_1');
	var filterTwo = document.getElementById('select_level_2');
	var sortBy    = document.getElementById('sort_by');
	setSelected(filterOne, filterOneParameter);
	setSelected(filterTwo, filterTwoParameter);
	setSelected(sortBy, sortByParameter);
	
	
	var url = '/DownloadCenter.bsci?method=search&filterOne=' + filterOneParameter + '&filterTwo=' + filterTwoParameter + '&sortBy=' + sortByParameter + '&downloadCenterName=' + encodeURIComponent(downloadCenterName) + "&url=" + currentUrl;
	var searchButton = document.getElementById("search_button");
	searchButton.disabled = "true";
	searchButton.value = "Processing...";
	var request = createRequest();
	request.open("GET", url, true);
	request.onreadystatechange = function(){loadDownloadSearchResults(request);}
	request.send(null);

}

// On clicking on a search result, call Java to handle download
function download_document(downloadId){
	var request = createRequest();
	request.open("GET", "/DownloadCenter.bsci?method=check_security&downloadId=" + downloadId, true);
	request.onreadystatechange = function(){after_security_check_process(request, downloadId);}
	request.send(null);
}

function download_request_omniture_call(filePath){
	var pageName = "";
	if (s.pageName != null){
	  var currentPageName = s.pageName;
	  pageName = currentPageName.split(":")[0];
	  s.pageName = pageName + ":" + filePath;
	  void(s.t());
	}
}

// On clicking submit in the login screen, handle login, pt I
// Submit an AJAX request that checks if the login is valid, and prints an error message if not and nothing if it is.
function login_for_secure_download(name, password, downloadId){
	var request = createRequest();
	if (name == null || name == ''){
		alert('Username is null.');
	} else if (password == null || password == ''){
		alert('Password is null.');
	} else {
		//TODO: Change to https
		request.open("GET", "http://" + location.hostname + ":" + location.port + "/DownloadCenter.bsci?method=login&name=" + name + "&password=" + password, true);
		request.onreadystatechange = function(){login_secure_download_2(request, name, password, downloadId);};
		request.send(null);
	}
}

// On clicking submit in the login screen, handle login, pt II, which catches the response to part I
// If the result of the login1 method was success, call java again to revalidate and download
// If the result of the login2 method was failure, report the failure to the user
function login_secure_download_2(request, name, password, downloadId){
	if (request.readyState == 4){
		if (request.status == 200){
			if (request.responseText == 'success'){
				//TODO: Change to https
				document.location.href = "http://" + location.hostname + ":" + location.port + "/DownloadCenter.bsci?method=secure_download&downloadId=" + downloadId + "&name=" + name + "&password=" + password;
				setTimeout("if(opener) window.close();", 5000);
			} else {
				alert('Login failed.  Username and/or password is invalid');
			}
		}
	}
}
 
// After Boston Scientific returns the items for the dropdown, this will be called to dynamically load the page
function setup_download_center_2(request, filterOne, filterTwo){
	if (request.readyState == 4){
		if (request.status == 200){
			loadHeader(request);
			loadDropdowns(request);
			if (filterOne != -1 || filterTwo != -1){
				setTimeout("changeDropdownValues(" + filterOne + ", " + filterTwo + "); search_download_center();", 500);
			} else {
				loadDefaults(request);			
			}
		}
	}

}

function loadHeader(request){
	var xmlDoc = request.responseXML.documentElement;
	if (xmlDoc.getElementsByTagName("download-center-image").length > 0){
		document.getElementById("header_img").src = xmlDoc.getElementsByTagName("download-center-image")[0].firstChild.nodeValue;
		document.getElementById("header_img").style.display = "block";
	} else {
		document.getElementById("header_img").style.display = "none";	
	}
	if (xmlDoc.getElementsByTagName("download-center-description").length > 0)
		document.getElementById("download_description").innerHTML = xmlDoc.getElementsByTagName("download-center-description")[0].firstChild.nodeValue;
}

function loadDropdowns(request){
	var xmlDoc = request.responseXML.documentElement;
	// Set up the filter one dropdown
	removeAllOptions(document.getElementById('select_level_1'),1);
	var filterOneElement = xmlDoc.getElementsByTagName('filter-elements-1')[0];
	var filterOneList = filterOneElement.getElementsByTagName('filter-element');
	for (var i = 0; i < filterOneList.length; i++){
		var name = filterOneList[i].childNodes[0].firstChild.nodeValue;
		var categoryId = filterOneList[i].childNodes[1].firstChild.nodeValue;
		addItemToDropdown('select_level_1', name, categoryId, filterOneList[i].getAttribute('selected') == 'true');
	}
	// Set up the filter two dropdown
	removeAllOptions(document.getElementById('select_level_2'),1);
	var filterTwoElement = xmlDoc.getElementsByTagName('filter-elements-2')[0];
	var filterTwoList = filterTwoElement.getElementsByTagName('filter-element');
	for (var i = 0; i < filterTwoList.length; i++){
		var name = filterTwoList[i].childNodes[0].firstChild.nodeValue;
		var categoryId = filterTwoList[i].childNodes[1].firstChild.nodeValue;
		addItemToDropdown('select_level_2', name, categoryId, filterTwoList[i].getAttribute('selected') == 'true');
	}
}

function loadDefaults(request){

	var xmlDoc = request.responseXML.documentElement;
	
	// Clear old search results
	var resultsBox = document.getElementById("results_box");
	while (resultsBox.firstChild){
		resultsBox.removeChild(resultsBox.firstChild);
	}
	// Get date and total download label text
	var dateLabel = document.getElementById("date_label").value;
	var numDownloadsLabel = document.getElementById("download_number_label").value;

	// Add search results
	var resultsList = xmlDoc.getElementsByTagName('download')
	for (var i = 0; i < resultsList.length; i++){
		addSearchResultToPage(resultsList[i], dateLabel, numDownloadsLabel);
	}
			
}


// After Boston Scientific returns the search items, this will be called to dynamically load the page
function loadDownloadSearchResults(request){
	if (request.readyState == 4){
		if (request.status == 200){
			
			var xmlDoc = request.responseXML.documentElement;

			// Clear old search results
			var resultsBox = document.getElementById("results_box");
			while (resultsBox.firstChild){
				resultsBox.removeChild(resultsBox.firstChild);
			}
			// Get date and total download label text
			var dateLabel = document.getElementById("date_label").value;
			var numDownloadsLabel = document.getElementById("download_number_label").value;
			// Add search results
			var resultsList = xmlDoc.getElementsByTagName('download')
			for (var i = 0; i < resultsList.length; i++){
				addSearchResultToPage(resultsList[i], dateLabel, numDownloadsLabel);
			}
			
			if (resultsList.length <= 0){
				var noResultsMessage = document.createElement("div");
				noResultsMessage.className = "no_results_message";
				noResultsMessage.innerHTML = "No Results Found.";
				resultsBox.appendChild(noResultsMessage);
			}
			
		}
		var searchButton = document.getElementById("search_button");
		searchButton.disabled = false;
		searchButton.value = "Search";

	}
}

// After security check returns, if this is a nonsecure download, go ahead and download it.  if it is secure, then open a login window.
function after_security_check_process(request, downloadId){
	if (request.readyState == 4){
		if (request.status == 200){
		
			var xmlDoc = request.responseXML.documentElement;
			var fileStatus = xmlDoc.getElementsByTagName("security-type")[0].firstChild.nodeValue;
		
			if (fileStatus.toLowerCase() == 'file_not_found'){
				alert('That file is not currently available.');
			}
			if (fileStatus.toLowerCase() == 'nonsecured'){
				document.location.href = "/DownloadCenter.bsci?method=download&downloadId=" + downloadId;
			}
			if (fileStatus.toLowerCase() == 'login'){
				var loginStatus = xmlDoc.getElementsByTagName("security-type")[0].getAttribute("status");
				if (loginStatus == 'verified'){
					var name = xmlDoc.getElementsByTagName("name")[0].firstChild.nodeValue;
					var password = xmlDoc.getElementsByTagName("password")[0].firstChild.nodeValue;
					login_for_secure_download(name, password, downloadId);
				
				} else {	// otherwise loginStatus should be unverified, so login is required
					new_window = window.open('','popup','height=150,width=250');
					var tmp = new_window.document;
					tmp.write('<html><head><script type="text/javascript" src="JS/download_center.js"></script></head><body><form id="login">');
					tmp.write('Username: <input type="text" name="username"/><br/>');
					tmp.write('Password: <input type="password" name="password" onkeydown="if(event.keyCode == 13){login_for_secure_download(this.form.elements[0].value, this.form.elements[1].value,' + downloadId + ');}"/><br/>');
					tmp.write('<input id="login_submit" type="button" value="Submit" onclick="login_for_secure_download(this.form.elements[0].value, this.form.elements[1].value,' + downloadId + ');"/></body></html> ');
					tmp.close();
					new_window.focus();				
				}
				
			}
			if (fileStatus.toLowerCase() == 'disclaimer'){
				var loginStatus = xmlDoc.getElementsByTagName("security-type")[0].getAttribute("status");
				if (loginStatus == 'verified'){
					document.location.href = "/DownloadCenter.bsci?method=download&downloadId=" + downloadId;
				} else {	// otherwise loginStatus should be unverified, so disclaimer accepting is required
					var disclaimer_text = xmlDoc.getElementsByTagName("popup-text")[0].firstChild.nodeValue;
					new_window = window.open('','popup','height=150,width=250');
					var tmp = new_window.document;
					tmp.write('<html><head><script type="text/javascript" src="JS/download_center.js"></script></head><body><form id="disclaimer">');
					tmp.write(disclaimer_text + '<br/>');
					tmp.write('<input id="accept" type="button" value="Accept" onclick="document.location.href = \'/DownloadCenter.bsci?method=accept_disclaimer&downloadId=' + downloadId + '\'; setTimeout(\'if(opener) window.close();\', 5000)">');
					tmp.write('<input id="reject" type="button" value="Reject" onclick="if(opener) window.close();" />');
					tmp.write('</form></body></html>');
					tmp.close();
					new_window.focus();				
				}
			}
		}
	}
}


// Standard AJAX create request function
function createRequest(){
	var ajaxRequest; 
	try {
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		try {
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e)	{
			try {
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e)	{
				alert("Your browser does not support Ajax.  Please update your browser");
			}
		}
	}
	return ajaxRequest;
}

// Helper function for loading dropdowns, adds item
function addItemToDropdown(dropdownId, optionText, optionValue, selected){
	var selectElement = document.getElementById(dropdownId);
	var optionElement = document.createElement('option');
	optionElement.setAttribute('value', optionValue);
	if (selected)
		optionElement.setAttribute('selected', 'true');
	optionElement.innerHTML = optionText;
	selectElement.appendChild(optionElement);
}

//Resets dropdown value.  We have to do these serially else IE6 can have timing issues
function changeDropdownValues(optionOne, optionTwo){
	var selectElement = document.getElementById('select_level_1');
	var optionElements = selectElement.getElementsByTagName("option");
	for (var i = 0; i < optionElements.length; i++){
		if (optionElements[i].value == optionOne){
			optionElements[i].setAttribute('selected', 'true');
		} else {
			optionElements[i].removeAttribute('selected');
		}
	}
	selectElement = document.getElementById('select_level_2');
	optionElements = selectElement.getElementsByTagName("option");
	for (var i = 0; i < optionElements.length; i++){
		if (optionElements[i].value == optionTwo){
			optionElements[i].setAttribute('selected', 'true');
		} else {
			optionElements[i].removeAttribute('selected');
		}
	}
}

// Help function for loading search results, takes a download element from the results and returns
// a result class div, and add to resultsBox
function addSearchResultToPage(downloadElement, dateLabel, numDownloadsLabel){   //CHANGED

	// Extract result from XML

	var title = downloadElement.getElementsByTagName("title").item(0).firstChild.nodeValue;
	var downloadId = downloadElement.getElementsByTagName("download-id").item(0).firstChild.nodeValue;
	var filePath;
	var description;
	var attributes;
	var downloadDate;
	var thumbnailImage;
	var thumbnailImgAlt;
	var popularity;
	var filetypeIcon;
	var filetypeIconAlt;
	if (downloadElement.getElementsByTagName("file-path").length > 0){
		filePath = downloadElement.getElementsByTagName("file-path").item(0).firstChild.nodeValue;
	} else {
		filePath = '';
	}
	if (downloadElement.getElementsByTagName("description").length > 0){	
		description = downloadElement.getElementsByTagName("description").item(0).firstChild.nodeValue;
	} else {
		description = '';
	}
	if (downloadElement.getElementsByTagName("download-date").length > 0){
		downloadDate = downloadElement.getElementsByTagName("download-date").item(0).firstChild.nodeValue;	
	} else {
		downloadDate = '';
	}
	if (downloadElement.getElementsByTagName("download-attributes").length > 0){
		attributes = downloadElement.getElementsByTagName("download-attributes").item(0).firstChild.nodeValue;
	} else {
		attributes = '';
	}
	if (downloadElement.getElementsByTagName("thumbnail-img").length > 0){
		thumbnailImage = downloadElement.getElementsByTagName("thumbnail-img").item(0).firstChild.nodeValue;
	} else {
		thumbnailImage = ''
	}
	if (downloadElement.getElementsByTagName("thumbnail-alt-info").length > 0){
		thumbnailImgAlt = downloadElement.getElementsByTagName("thumbnail-alt-info").item(0).firstChild.nodeValue;
	} else {
		thumbnailImgAlt = '';
	}
	if (downloadElement.getElementsByTagName("popularity").length > 0){
		popularity = downloadElement.getElementsByTagName("popularity").item(0).firstChild.nodeValue;
	} else {
		popularity = '';
	}
	if (downloadElement.getElementsByTagName("filetype-image").length > 0){
		filetypeIcon = downloadElement.getElementsByTagName("filetype-image").item(0).firstChild.nodeValue;
	} else {
		filetypeIcon = '';
	}
	if (downloadElement.getElementsByTagName("filetype-image-alt").length > 0){
		filetypeIconAlt = downloadElement.getElementsByTagName("filetype-image-alt").item(0).firstChild.nodeValue;
	} else {
		filetypeIconAlt = '';
	}

	// Assign result to page
	var resultsBox = document.getElementById("results_box");
	var resultDiv = document.createElement("div");
	resultDiv.className = "result";
	resultsBox.appendChild(resultDiv);
	var downloadIdDiv = document.createElement("div");
	downloadIdDiv.className = "download_id";
	downloadIdDiv.innerHTML = downloadId;
	resultDiv.appendChild(downloadIdDiv);
	var resultsImage = document.createElement("img");
	resultsImage.className = "result_image";
	resultsImage.onclick = function(){download_document(downloadId);download_request_omniture_call(filePath);};
	resultsImage.onmouseover = function(){resultsImage.style.cursor='pointer'};
	if (thumbnailImage)
		resultsImage.setAttribute("src", thumbnailImage);
	if (thumbnailImgAlt)
		resultsImage.setAttribute("alt", thumbnailImgAlt);
	if (thumbnailImage)
		resultDiv.appendChild(resultsImage);
	var resultsRightDiv = document.createElement("div");
	resultsRightDiv.className = "result_right";
	resultDiv.appendChild(resultsRightDiv);
	var resultsTitleDiv = document.createElement("div");
	resultsTitleDiv.className = "results_title";
	resultsTitleDiv.onclick = function(){download_document(downloadId);download_request_omniture_call(filePath);};
	resultsTitleDiv.onmouseover = function(){resultsTitleDiv.style.cursor='pointer'};
	resultsTitleDiv.innerHTML = title;
	resultsRightDiv.appendChild(resultsTitleDiv);
	var resultsDescriptionDiv = document.createElement("div");
	resultsDescriptionDiv.className = "file_description";
	if (description)
		resultsDescriptionDiv.innerHTML = description;
	resultsRightDiv.appendChild(resultsDescriptionDiv);
	if (filetypeIcon != ''){
		var fileTypeImage = document.createElement("img");
		fileTypeImage.setAttribute("src", filetypeIcon);
		fileTypeImage.setAttribute("alt", filetypeIconAlt);
		fileTypeImage.className = "file_type_image";
		resultsRightDiv.appendChild(fileTypeImage);
	}
	var fileMetadataDiv = document.createElement("div");
	fileMetadataDiv.className = "file_metadata";
	if (attributes)
		fileMetadataDiv.innerHTML = attributes;
	resultsRightDiv.appendChild(fileMetadataDiv);
	var resultsDateDiv = document.createElement("div");
	resultsDateDiv.className = "file_description";
	if (downloadDate)
		resultsDateDiv.innerHTML = dateLabel + " " + downloadDate;
	resultsRightDiv.appendChild(resultsDateDiv);
	var resultsPopularityDiv = document.createElement("div");
	if (popularity)
		resultsPopularityDiv.innerHTML = numDownloadsLabel + " " + popularity;
	resultsPopularityDiv.className = "popularity";
	resultsRightDiv.appendChild(resultsPopularityDiv);
}

	
function setSelected(element, selected_value)
{
	for(var x=0; x < element.options.length; x++)
	{
		if(element.options[x].value == selected_value)
		{
			element.selectedIndex = x;
			break;
		}
	}
}


function removeAllOptions(selectbox, options_to_keep){
   while (selectbox.options.length > options_to_keep) {selectbox.removeChild(selectbox.lastChild);}
}
