// JavaScript Document

var searchURL = 'http://www.medi-carefirst.com/meddinfo/drug/searchDrugs.json?year=2011&drugNamePattern=';
var categorySearchURL = 'http://www.medi-carefirst.com/meddinfo/drug/listCategories.json?year=2011';
var authorizedListSearchURL = 'http://www.medi-carefirst.com/meddinfo/drug/listPADrugs.json?year=2011';
var itemDetailsURL = 'http://www.medi-carefirst.com/meddinfo/drug/drugDetail.json?year=2011&key=';  
var QauntityLimitListSearchURL ='http://www.medi-carefirst.com/meddinfo/drug/listQLDrugs.json?year=2011';
var formularyChangesSearchURL = 'http://www.medi-carefirst.com/meddinfo/drug/findDrugChanges.json?year=2011';
var classesForCategory = 'http://www.medi-carefirst.com/meddinfo/drug/listClasses.json?year=2011&categoryName=';
var drugsInClass = 'http://www.medi-carefirst.com/meddinfo/drug/listClassDrugs.json?year=2011&className=';

// Used to initiate all different types of search.
// 1) Updates the UI to indicate the search is in progress.
// 2) Kicks off an Ajax/Json call to the specefied URL.
// 3) Hooks up the passed call back function so that it is called when the search completes.
function InitiateSearch(searchURL, searchCompletedCallBackFunction) 
{
	// Hide any products details that may be hanging around from the last search.
	$("#productDetailsSearchIndicator").hide();
	$("#itemDetailsContainer").hide();
	
	// Update the UI to indicate that the search is occuring.
	// 1a) Remove the previous search results table by fading it out, then deleting it.
	$("#searchResults").slideUp(100, function() {
	
		// 1b) Show the search indicator.
		$("#searchingIndicator").slideDown();
		
		// Make the Ajax call and hook up the specified function to handle the results.
		// 2) Kick of the search request.
		// 3) Hook up the callback.
		$.getJSON(searchURL, searchCompletedCallBackFunction);

	});
}

// Used to display the results of all different types of search.
function ShowSearchResults(searchResultsHtml)
{
	// Insert the new search results table back into the dom.
	$("#searchResults").html(searchResultsHtml);
	
	// Update the UI to indicate that the search has completed.
	// 1) Hide the search indicator.
	$("#searchingIndicator").slideUp(100, function() {

		// 2) Now show the results.
		$("#searchResults").slideDown("slow");
	});
}


// Carries out the a user initiated search.
function DoUserSearch() 
{
	// Get the search term entered by the user.
	var searchTerm = $("#searchquery").val();
	
	// need to do something here to make the blank search field show an error
	if (searchTerm == ''){
		alert("Please enter a search term");
		return;
	}
	// Construct the URL of the search using the search term.
	var searchURLWithTerm = searchURL + escape(searchTerm);
	
	// Execute the search.
	InitiateSearch(searchURLWithTerm, UserSearchCompleted);
	
}

// Handles the results of a user initiated search.
function UserSearchCompleted(data)
{
	// Check for no results.
	if(data.totalCount == 0)
	{
		var h = "<h3>Drug Search Results</h3><p>There are " + data.totalCount + " results for your term.</p>"
		ShowSearchResults(h);
	}
	
	var h = "<h3>Drug Search Results</h3><p>There are " + data.totalCount + " search results for your term.</p><table class='dataTable' width='500'><tr><th>Name</th><th>Drug Tier</th><th>Class</th><th>Generic Alternative</th></tr><tbody>";
	for (var i = 0; i < data.drugs.length; i++) {
		var dr = data.drugs[i];

		if ((i % 2) == 1) {
			h += '<tr class="odd">\n';
		}
		else {
			h += '<tr>\n';
		}
		
		h += '<td class="LB"><a href="#" onclick="return ViewItemDetails(\'' + dr.primaryKey + '\');">' + dr.brandName + ' ' + dr.dosage +' '+ dr.strength + '</a></td>';
		
		h += '<td align="center"><a href="../includes/incTierDrugPlan.htm" onclick="return OpenFileInNewWindow(this);">' + dr.tierCode + '</a></td>';
		h += '<td class="L"><a href="#" onclick="return ShowDrugsInClass(\'' + dr.cls + '\');">'+ dr.cls + '</td>';
		h += '<td class="L">' + dr.genericAlt + '</td>';
		h += '</tr>\n';
	}
	h += "</tbody></table><div id='productDetailsSearchIndicator' class='invisible'>Retrieving item details, please wait...</div><div id='itemDetailsContainer'></div>";

	// Now show the search results.
	ShowSearchResults(h);
}

// Carry out a category search.
function ShowCategories()
{
	// Execute the search using the category search url on top.
	InitiateSearch(categorySearchURL, CategorySearchCompleted);
}

function CategorySearchCompleted(data) 
{
	// Check for no results.
	if (data.categories.length == 0) {
		 var h = "<h3>Category Search Results</h3><p>There are " + data.totalCount + " categories.</p>"
		ShowSearchResults(h);
	}

	var h = "<h3>Category Search</h3><p>There are " + data.totalCount + " categories.  To see classes, click on the category link below.</p><table class='dataTable'><tr><th>Category Name</th></tr><tbody>";
	var dr = data.categories;
	for (var i = 0; i < dr.length; i++) {
		if ((i % 2) == 1) {
			h += '<tr class="odd">\n';
		}
		else {
			h += '<tr>\n';
		}
		// show classes for each category using this function call
		h += '<td class="LB"><a href="#" onclick="return ShowClassesForCategory(\'' + dr[i] + '\');">' + dr[i] + '</td>';
		h += '</tr>\n';
	}
	h += "</tbody></table>";

	// Now show the search results.
	ShowSearchResults(h);
}

// Carry out a prior authorization search.
function ShowAuthorizedList() 
{
	// Execute the search using the authorised list Json source at top
	InitiateSearch(authorizedListSearchURL, AuthorizedListSearchCompleted);
}

function AuthorizedListSearchCompleted(data) 
{
	// Check for no results.
	if (data.drugs.length == 0) {
		 var h = "<h3>Authorized List Search</h3><p>There are " + data.totalCount + " drugs requiring authorization.</p>"
		ShowSearchResults(h);
	}

	var h = "<h3>Prior Authorization List</h3><p>For more information about the requirements surrounding prior authorization, please see our <a href='http://www.medi-carefirst.com/mcf/attachments/CY2011PACriteria.pdf' target='_blank'>prior authorization criteria</a>.</p><table class='dataTable'><tr><th>Drug Name</th><th>Form Link</th></tr><tbody>";
	for (var i = 0; i < data.drugs.length; i++) {
		var dr = data.drugs[i];

		if ((i % 2) == 1) {
			h += '<tr class="odd">\n';
		}
		else {
			h += '<tr>\n';
		}

		// just show the data now - drug name ...
		h += '<td class="LB"><a href="#" onclick="return ViewItemDetails(\'' + dr.primaryKey + '\');">' + dr.brandName + ' ' + dr.dosage +' '+ dr.strength + '</a></td>';
		
		// show multiple prior authorization pdfs
		// split url into an array - typiclly returns one result, but if more then it become an array
		h += '<td class="L">';
	
		var PA_URLs=dr.priorAuthURL.split(';');
		
		if (PA_URLs.length==1){
			h += '<a href="' + PA_URLs[0] + '" target="_blank">PA Form</a> <img src="http://www.carefirst.com/images/acrobat_small.gif" alt="PDF" /> ';
		}
		else{
			// we are parsing the link URL for word between the _ and .pdf pieces
			for (link=0;link<PA_URLs.length;link++){
				 var linkName = PA_URLs[link].substring(PA_URLs[link].lastIndexOf('_')+1, PA_URLs[link].lastIndexOf('.'));
				 h += '<a href="' + PA_URLs[link] + '" target="_blank"> PA Form (' + linkName + ') </a> <img src="http://www.carefirst.com/images/acrobat_small.gif" alt="PDF" /> ';
			}
		}
		h +='</td></tr>';

	}
	h += "</tbody></table>";

	// Now show the search results.
	ShowSearchResults(h);
}

// Carry out a prior authorization search.
function ShowQauntityLimitList() 
{
	// Execute the search using the authorised list Json source on top.
	InitiateSearch(QauntityLimitListSearchURL, QauntityLimitListSearchCompleted);
}

function QauntityLimitListSearchCompleted(data) 
{
	// Check for no results.
	if (data.drugs.length == 0) {
		
		return;
	}

	var h = "<h3>Quantity Limits</h3><p>There are " + data.totalCount + " drugs with quantity limits.</p><table class='dataTable'><tr><th>Drug Name</th><th>Form Link</th></tr><tbody>";
	for (var i = 0; i < data.drugs.length; i++) {
		var dr = data.drugs[i];

		if ((i % 2) == 1) {
			h += '<tr class="odd">\n';
		}
		else {
			h += '<tr>\n';
		}

		// this pulls the data for each item
		h += '<td class="LB"><a href="#" onclick="return ViewItemDetails(\'' + dr.primaryKey + '\');">' + dr.brandName  + ' ' + dr.dosage + ' ' + dr.strength + '</a></td>';
		h += '<td class="L"> <img src="http://www.carefirst.com/images/acrobat_small.gif" alt="PDF" /> <a href="' + dr.quantityLimitURL + '" target="_blank">QL Exception Request Form </a></td>';
		h += '</tr>\n';
	}
	h += "</tbody></table>";

	// Now show the search results.
	ShowSearchResults(h);
}

// Provides a means to open a file related to a specific search result.
function OpenFileInNewWindow(source) 
{
	// Open the hyperlink's target in a new window.
	window.open(source.href, source.target, ',width=600,height=400,left=100,top=75,links=yes,status=yes,toolbar=yes,menubar=yes,resizable=yes,location=yes');

	// Prevent the hyperlink from re-directing the browser.
	return false;
}

// Gets the details of a specific item within the search results.
function ViewItemDetails(itemId) 
{
	// Define Search Key - - item key
	var itemIdKey = itemId;
	
	// putting together URL for search string
	var itemDetailsURLWithItemId = itemDetailsURL + escape(itemIdKey);
	
	// Execute the search using the authorised list Json source.
	InitiateSearch(itemDetailsURLWithItemId, ItemDetailsRequestCompleted);
}

// This is called when a request for details of a particular item completes.
function ItemDetailsRequestCompleted(data) 
{
	dr = data.drug;
	var h = "<h3>Drug Details</h3><table class='dataTable' width='500'><tr><th>Item Details</th><th></th></tr>";
		h += '<tr><td class="LB">Drug Name:</td><td class="L">' + dr.brandName  + ' ' + dr.dosage +' '+ dr.strength + '</td></tr>';
		h += '<tr><td class="LB">Generic Alternative Available:</td><td class="L">' + dr.genericAlt + '</td></tr>';
		h += '<tr><td class="LB">Drug Tier:</td><td class="L"><a href="../includes/incTierDrugPlan.htm" onclick="return OpenFileInNewWindow(this);">' + dr.tierCode + '</a></td></tr>';
		
		// displays generic tier code when value is 1
		if (dr.tierCodeGeneric == 1){
				h += '<tr><td class="LB">Generic Tier:</td><td class="L">' + dr.tierCodeGeneric + '</td></tr>';
		}
		
		h += '<tr><td class="LB">Category:</td><td class="L">' + dr.category + '</td></tr>';
		h += '<tr><td class="LB">Class:</td><td class="L">' + dr.cls + '</td></tr>';

		// show multiple prior authorization pdfs
		// split url into an array - typiclly returns one result, but if more then it become an array
		h += '<tr><td class="LB">Prior Authorization Required:</td><td class="L">';

		if (dr.priorAuthReq == "NO") {
			h +=  dr.priorAuthReq + '</td></tr>';
		}
		else {
			// split url into an array - typiclly returns one result, but if more then it become an array
			h +=  dr.priorAuthReq + '<br />';
			var PA_URLs=dr.priorAuthURL.split(';');			
			
			// display for one result
			if (PA_URLs.length==1){
				h += '<a href="' + PA_URLs[0] + '" target="_blank">PA Form</a> <img src="http://www.carefirst.com/images/acrobat_small.gif" alt="PDF" /> ';
			}
			else{
				// we are parsing the link URL for word between the _ and .pdf pieces
				for (link=0;link<PA_URLs.length;link++){
					var linkName = PA_URLs[link].substring(PA_URLs[link].lastIndexOf('_')+1, PA_URLs[link].lastIndexOf('.'));
					h += '<a href="' + PA_URLs[link] + '" target="_blank"> PA Form (' + linkName + ') </a> <img src="http://www.carefirst.com/images/acrobat_small.gif" alt="PDF" />&nbsp;';
				}
			}
			h +='&nbsp; &nbsp;<a href="http://www.medi-carefirst.com/mcf/attachments/CY2011PACriteria.pdf" target="_blank">Criteria</a>  <img src="http://www.carefirst.com/images/acrobat_small.gif" alt="PDF" /></td></tr>';					
			
		}


		
		// shows quantity limits are No or w/ URL
		if (dr.quantityLimitReq == "NO") {
			h += '<tr><td class="LB">Quantity Limit:</td><td class="L">' + dr.quantityLimitReq + '</td></tr>';
		}
		else {
			h += '<tr><td class="LB">Quantity Limit:</td><td class="L">YES<br /> <a href="' + dr.quantityLimitURL + '" target="_blank">QL Form</a> <img src="http://www.carefirst.com/images/acrobat_small.gif" alt="PDF" /> <br />' +  dr.quantityLimitDetail + '</td></tr>';
		}	
		
		
		if (dr.webComment1 != ''){
			h += '<tr><td class="LB">Comments:</td><td class="L">' + dr.webComment1 + ' ' + dr.webComment2 + ' '+ dr.webComment3 +  '</td></tr>'; 
		}
		h += '</table>';
		
		
		if (dr.nnocEffDate != ''){
			h += "<h3>" + dr.brandName + "</h3><table class='dataTable' width='500'><tbody>"; 
			h += '<tr><td class="LB">Effective Date:</td><td class="L">' + dr.nnocEffDate +'</td></tr>'; 
			h += '<tr><td class="LB">Description of Change:</td><td class="L">' + dr.nnocDescr +'</td></tr>'; 
			h += '<tr><td class="LB">Reasons for Change:</td><td class="L">' + dr.nnocReason +'</td></tr>'; 
			h += '<tr><td class="LB">Replacement Drug:</td><td class="L">' + dr.nnocAltDrug +'</td></tr>'; 
			h += '<tr><td class="LB">Replacement Drug\'s Tier:</td><td class="L">' + dr.nnocAltTier +'</td></tr>'; 
			h += '<tr><td class="LB">Replacement Drug\'s Cost:</td><td class="L"><a href="../includes/incTierDrugPlan_2009.htm" onclick="return OpenFileInNewWindow(this);"> See Table for Replacement Drug\'s Cost </td></tr></tbody></table>'; 			
		}		
		
	// Now show the search results.
	ShowSearchResults(h);
}		


// Gets the details of a specific drugs within a class.
function ShowDrugsInClass(classId) 
{
	// Define Search Key - class name
	var classIdKey = classId;
	
	// putting together the URL for search string.
	var drugsInClassWithClassId = drugsInClass + escape(classIdKey);
	
	// Execute the search with the define function.
	InitiateSearch(drugsInClassWithClassId, DrugsInClassRequestCompleted);
}

// This is called when a request for details of a particular item completes.
function DrugsInClassRequestCompleted(data) 
{
   // Check for no results.
	if(data.totalCount == 0)
	{
		return;
	}

	var h = "<h3>Drugs in Class</h3><table class='dataTable' width='500'><tr><th>Name</th><th>Drug Tier</th><th>Prior Authorization</th><th>Qauntity Limit</th><th>Change Notice</th></tr><tbody>";
	for (var i = 0; i < data.drugs.length; i++) {
		var dr = data.drugs[i];

		if ((i % 2) == 1) {
			h += '<tr class="odd">\n';
		}
		else {
			h += '<tr>\n';
		}
		
		h += '<td class="LB"><a href="#" onclick="return ViewItemDetails(\'' + dr.primaryKey + '\');">' + dr.brandName  + ' ' + dr.dosage +' '+ dr.strength + '</a></td>';
		
		h += '<td  align="center"><a href="../includes/incTierDrugPlan.htm" onclick="return OpenFileInNewWindow(this);">' + dr.tierCode + '</a></td>';
		
		if (dr.priorAuthReq == "NO") {
			h += '<td class="L">' + dr.priorAuthReq + '</td>';
		}
		else {
			// split url into an array - typiclly returns one result, but if more then it become an array
			h += '<td class="L">' + dr.priorAuthReq + '<br />';
			var PA_URLs=dr.priorAuthURL.split(';');			
			
			// display for one result
			if (PA_URLs.length==1){
				h += '<a href="' + PA_URLs[0] + '" target="_blank">PA Form</a> <img src="http://www.carefirst.com/images/acrobat_small.gif" alt="PDF" /> ';
			}
			else{
				// we are parsing the link URL for word between the _ and .pdf pieces
				for (link=0;link<PA_URLs.length;link++){
					var linkName = PA_URLs[link].substring(PA_URLs[link].lastIndexOf('_')+1, PA_URLs[link].lastIndexOf('.'));
					h += '<a href="' + PA_URLs[link] + '" target="_blank"> PA Form (' + linkName + ') </a> <img src="http://www.carefirst.com/images/acrobat_small.gif" alt="PDF" /> ';
				}
			}
			h +='</td>';		
			
		}			

		if (dr.quantityLimitReq == "NO") {
			h += '<td class="L">' + dr.quantityLimitReq + '</td>';
		}
		else {
			h += '<td class="L"><a href="' + dr.quantityLimitURL + '" target="_blank">'+ dr.quantityLimitReq + '</a> <img src="http://www.carefirst.com/images/acrobat_small.gif" alt="PDF" /></td>';
		}	
		
		h += '<td>' + dr.nnocEffDate + '</td>';			
		h += '</tr>\n';
	}
	h += "</tbody></table><div id='productDetailsSearchIndicator' class='invisible'>Retrieving item details, please wait...</div><div id='itemDetailsContainer'></div>";

	// Now show the search results.
	ShowSearchResults(h);
}

// Gets the details of a specific item within the search results.
function ShowClassesForCategory(categoryId) 
{
	// Define Search Key - category 
	var categoryIdKey = categoryId;
	
	// putting together the URL for search string.
	var ClassesForCategoryWithCategoryId = classesForCategory + escape(categoryIdKey);
	
	// Execute the search with the define function.
	InitiateSearch(ClassesForCategoryWithCategoryId, ClassesForCategoryRequestCompleted);
}

// This is called when a request for details of a particular item completes.
function ClassesForCategoryRequestCompleted(data) 
{
   // Check for no results.
	if(data.totalCount == 0)
	{
		return;
	}

	var h = "<h3>Classes in Category Search</h3><p>Click on the Class name to list the drugs for that class.</p><table class='dataTable'><tr><th>Classes for Category</th></tr><tbody>";
	var dr = data.classes;
	for (var i = 0; i < dr.length; i++) {
		if ((i % 2) == 1) {
			h += '<tr class="odd">\n';
		}
		else {
			h += '<tr>\n';
		}
		// this will show the classes and allow to do another search
		h += '<td class="LB"><a href="#" onclick="return ShowDrugsInClass(\'' + dr[i] + '\');">' + dr[i] + '</td>';
		h += '</tr>\n';
	}
	h += "</tbody></table>";

	// Now show the search results.
	ShowSearchResults(h);
}
