// ch = e.which || e.keyCode;

// JavaScript Document
// Mental Health Connections, Inc. 2004-5
// Written by Robert Patterson
/* ----------------------------------ADDRESSES ----------------------------------------------------------------------------------------


	ADD .EXE TO NAME ON WINDOWS SERVERS !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	
*/

// GLOBAL VARS
	var serverAddress = '/ddi53/';
	var prologEngine = 'http://mhc.daytondcs.com:8080/cgi-bin/ddiD4';
	var noteShowing = '';
	var password;
	//09-01-01 v50 var ver1RecordName = '';
	var object;	
	var xmlHttp;
	var showNames = false;
	var serverLocation = 'web';
	var currentNoteVis = "startPop";
	var newName = '';
	var guestUser = false;
	var dnaTest = false;
	var showDNATestPt = false;
	var algoWin;
	var skipMinors = 'show';
		
function visTable(tableName) {
  document.getElementById(tableName).className="table1vis";
  var expanderSpan = expand.concat('_expander');
  var cdHexpander = document.getElementById(expanderSpan);
  var txt = "<img src='close.jpg' width='15' height='20'>";
  cdHexpander.innerHTML = txt;  // changes to minus sign button
}
/*
function noVisTable(tableName) {
  var x = document.getElementById(tableName).className="table1none";
}
*/
function locateServer()
{
	if(window.location.hostname == 'localhost')
	{
		serverLocation = 'local';
//		prologAddress = '../cgi-bin/ddiD5.exe?';
		prologEngine = '../cgi-bin/ddiD53.exe';
	}
}
	
function setUp()  // When serachResults page displays
{
	locateServer();
	if(parent.document.title == 'gmdrxMini')
	{
		smallWindowSizer('expandPop');	
	}
	swapTabInfo();
	var doc = getIFrameDoc('notesIFrame');
	var cdH2;
	var noteExists = true;
	try{
		doc.getElementById('note_1').id;
	}
	catch(e){
		noteExists = false;		
	}	
	var getStartValue = getCookie('getStart');
	if(getStartValue == 'true')
	{
		showAdditInfo('startPop'); 
	}
	else
	{
		if(noteExists){
			showAdditInfo('note_1');
		}
		else{
			showAdditInfo('startPop');
		}
	}
	if(compareType != 'none')
	{
		swapTabStartStop();
		smallWindowSizer('50-50');
	}
	if(getCookie('skipMinorIneractions') == 'skip')
	{
		document.getElementById('minorsYes').checked = true; // = '<strong>Interactions Showing: Major Only</strong>';
	}
	else
	{
		document.getElementById('minorsNo').checked = true;    //document.getElementById('skipAlert').innerHTML = '<strong>Interactions Showing: All</strong>';
	}
															 
}

function setToScreen()
{
	var width = screen.width;
//	alert('width=' + width);
	if(width <1100)
	{
		document.getElementById('resultsSpace').width = 425;
		document.getElementById('tab4ContentDiv').style.width = '450px';
		document.getElementById('notesIFrame').style.width = '375px';
		document.getElementById('intRepImage').width = 190;
		document.getElementById('tableIFrame').width = 448;
		document.getElementById('tabFade').width = 375;
		document.getElementById('tbInfoImage1').width = 375;
		document.getElementById('tabInfoHolder').style.width = '378px';
		document.getElementById('start_stopIFrame').width = 375;
		document.getElementById('largeFrame').width = 800;
		document.getElementById('largeFrame').height = 450;
	}
	var height = document.documentElement.clientHeight || document.body.clientHeight;
	if(height < 700)
	{
		document.getElementById('tab4ContentDiv').style.height = '370px';
		document.getElementById('tableIFrame').height = 345;
		document.getElementById('tabInfoContent').style.height = '370px';
		document.getElementById('notesIFrame').height = 340;
		document.getElementById('start_stopIFrame').height = 340;
		document.getElementById('tab5RightDiv').style.height = '370px';
		document.getElementById('tabInfoHolder').style.height = '378px';
		document.getElementById('tabStartStopContent').style.height = '370px';
	}	
}
	
  		
function showDetails(tableName) 
{

	var expanderSpan = tableName.concat('_expander');
	var cdHexpander = document.getElementById(expanderSpan);	
 	var cdHcontainer = document.getElementById(tableName); 
	var txt = '';
	if(document.getElementById(tableName).className=="table1none" ) 
	{
	  	document.getElementById(tableName).className="table1vis";
//		txt = "<img src='images/expand.gif' width='24' height='22'>";
//		cdHexpander.innerHTML = txt;  // changes to minus sign button
		if(document.title == 'gmdrxMini')		
			smallWindowSizer('expandPop');
  	}
	else
	{
		//CLOSING
		txt = "<img src='images/expand.gif' width='24' height='22'>";
		cdHexpander.innerHTML = txt;  // changes to minus sign button		
		document.getElementById(tableName).className="table1none";
  	}
  }
/*
function showStartStop()    // getStartValue is sent only from setup
  {
	//	alert(document.getElementById("resultsIFrame").className);
	//	frames['largeFrame'].document.body.innerHTML = page;
		if((document.title != 'gmdrxMini') && document.getElementById("resultsSpan").className != "listVis")
		{
			alert('Go to the Search Results page first. The "Changes Due to Starting and Stopping Drugs" page is a part of the search results if you mark drugs being started or stopped.');
			return;
		}
		var doc = getIFrameDoc('tableIFrame');
		var doc2 = getIFrameDoc('notesIFrame');
		if(doc.getElementById('note_100').id != 'note_100')
		{
			alert('There are is no "Changes Due to Starting and Stopping Drugs" report for this search. You need to mark drugs that are being started or stopped in the drug  entry page to get this report.'); 
			return;
		}
		doc2.getElementById('utilityDiv').innerHTML = doc.getElementById('note_100').innerHTML;
	//	var cv = frames['notesIFrame'].currentNoteVis;
		var cv = frames.notesIFrame.currentNoteVis;		
		doc2.getElementById(cv).className="note4Hid";
		doc2.getElementById('utilityDiv').className="note4Vis";
		frames.notesIFrame.currentNoteVis = 'utilityDiv';
//		frames['notesIFrame'].currentNoteVis = 'utilityDiv'; 
		smallWindowSizer('utilityDiv');
		document.getElementById('start-Stop').disabled = true;
		if(noteShowing)
		{
			document.getElementById(noteShowing).className = 'clickable';
		}		
}
*/
 	
function showDiv(div)
{
		var cdH = document.getElementById(div);	
		cdH.innerHTML = confText;
		cdH.style.visibility = "visible";
		cdH = document.getElementById('explainLink');	
		cdH.innerHTML = explainLinkCloser;			
}

function hideDiv(div)
{
		var cdH = document.getElementById(div);	
		cdH.innerHTML = '';
		cdH.style.visibility = "hidden";
		cdH = document.getElementById('explainLink');	
		cdH.innerHTML = expalinLinkOpener;			
}

  var confText = '<strong>Strength of Evidence Rating System</strong>  <br><br>High = multiple clinical reports <br><br><img src="strth2.jpg" width="30" height="40">Intermediate = one clinical report<br><br>Low = prediction from in vitro studies.';
		
  var explainLinkCloser = '<a href=\"javascript:hideDiv(\'confPop\')\">Hide explanation</a>';
  var expalinLinkOpener = '<a href=\"javascript:showDiv(\'confPop\')\">explain</a>';

/*
function showNote(noteNum) 
{
	alert('showNote() is not suppoed to be called.');
	showAdditInfo(noteNum);
}
*/

function showAdditInfo(id)   // utilityDiv
{
	var currentShowing = frames.notesIFrame.additShowing;
	var doc = getIFrameDoc('notesIFrame'); //tableIFrame'); //notesIFrame');
	try{
		doc.getElementById(currentShowing).className="note4Hid";
	}
	catch(e){
		currentShowing = '';    // Used below for setting note highlighting
	}
	doc.getElementById(id).className="notes4Vis";
	doc.getElementById('drugNamesDiv').className='hideIt';
	frames.notesIFrame.additShowing=id;
	if(parent.document.title == 'gmdrxMini'){
		var doc = getIFrameDoc('notesIFrame');
		doc.getElementById('startandStopDiv').className='hideIt';
		smallWindowSizer();
	}
	else
 		swapTabInfo();
// Handles highlighting main table notes cell
	var doc2 = getIFrameDoc('tableIFrame');
	var noteTd;	
	if(id.substring(0,5) == 'note_' )   // Gray the note area if a note is being displayed	
	{
		if(parent.document.title != 'gmdrxMini')
			doc.getElementById('drugNamesDiv').className='showIt';
		noteTd = 'td_' + id;
		doc2.getElementById(noteTd).className = 'clicked';
	}
	if(currentShowing != id && currentShowing.substring(0,5) == 'note_')// && noteShowing != '')  // Ungray old note if there is one
	{
		noteTd = 'td_' + currentShowing;
		doc2.getElementById(noteTd).className = 'clickable';
	}	
}


function popUp(objectID,extra)  // getStartValue sent only by setUp()
{
	showAdditInfo(objectID);	
}


function getIFrameDoc(id) 
{
	var iframe =  document.getElementById(id);
	if(!iframe)
	var saf = navigator.userAgent.match(/Safari/i);
	if(navigator.userAgent.match(/Safari/i)) {
				// Safari
			//	alert(iframe);
				alert('id= ' + id + ' iframe id= ' + iframe.id);
				iframe.className = "showIt";
				alert('showState= ' + iframe.className + ' id= ' + id + ' iframe.document= ' + iframe.document);
				return iframe.document;		
			}
					
    var iframe =  document.getElementById(id);
    var  doc = (iframe.contentWindow || iframe.contentDocument );
	//		var  doc = (iframe.contentWindow || iframe.contentDocument || iframe.document);
    if (doc.document) {
                doc = doc.document;
    }
    return  doc;	
}
		
		
function showRef(ref)
{
	if("number" == typeof(ref))
	{
		var pubMed = 'http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=PubMed&cmd=Retrieve&list_uids=' + ref + '&dopt=Abstract';
		showRefSub(pubMed);
		return;
	}
	if("string" == typeof(ref))
	{
		if(ref.search(/\//) > 0)
		{
			if(ref.substring(0,7) != 'http://') {
				ref = 'http://' + ref;
			}
			window.open(ref,"","");
		}
		else
		{
			  alert(ref);
		}
	}
}

function showRefSub(pubMed)
{
	window.open(pubMed,"","scrollbars=yes,resizable=yes,width=825,height=700,left=50,top=50");
}

function showDrugData(victim,culps)		// culp format: '' or 'x,y,z'.
{
	var sep = ',';
	if(!culps){
		sep = '';
	}
	var drugList = 'drugList([`' + victim + sep + culps + '`])';
	drugList = drugList.replace(/,\ /g,',');	
	drugList = drugList.replace(/,/g,'`,`');
	var iframeDoc = parent.getIFrameDoc('notesIFrame');
	var url = prologEngine + '?server=' + serverLocation + '&drugTables=' + drugList;
	sendAjax(url);
}



function select_1(index,param2)  // Menu in lists page
{
    var num = index.toString();
    var file;
	var iFrm = 'largeFrame';
    switch (num)  // Menu in drug selection page
    {
        case '0':
            file = serverAddress + "preResults.html";
            break;
        case '9':
            var wo = serverAddress + "userManual.html";
            window.open(wo,"","");
            return;
        case '1':
            file = serverAddress + 'aboutW.html';
            break;
        case '2':
            file = 'http://www.mhc.com/reg/e_mail.HTML?goal=togmrx';
            break;
        case '3':
            file = serverAddress + 'contact.html';   
            break;
        case '4':
            file = 'http://www.mhc.com/Cytochromes/';
            break;
        case '5':
            window.open("http://www.healthanddna.com/professional/pharmacogenetics.html","","");
            return;
        case '6':
            file = serverAddress + "warning.html";
            break;
        case '7':
            file = serverAddress + "authorsW.html";
            break;
        case '8':
            file = serverAddress + "newsW.html";
            break;
        case '10':
            file = serverAddress + "resources/warfarinCalc.html";
            break;
        case '11':
			var wo= "http://www.genemedrx.com/Cytochrome_Drug_Interaction_Links.php";
            window.open(wo,"","");
            return;
        case '12':
			var wo = "http://www.genemedrx.com/UGTtable.php";
            window.open(wo,"","");
            return;
        case '13':
			var wo = "http://www.genemedrx.com/CYP450Table.php";
            window.open(wo,"","");
            return;
        case '14':
			var wo = "http://www.genemedrx.com/PGP_Introduction.php";
            window.open(wo,"","");
            return;
        case '15':
			var wo = "http://www.genemedrx.com/PGPtable.php";
            window.open(wo,"","");
            return;
        case '16':
            window.open("http://www.healthanddna.com/professional/pharmacogenetics.html","","");
            return;
        case '17':
            alert('We will guide you to get a new password mailed to you...');
            file = "http://mhc.com/reg/e_mail.HTML?goal=toGmrx";
            break;   
        case '18':
            file = serverAddress + "privacy.html";
            break;
        case '19':
            window.open("http://www.healthanddna.com/drtorderformdetail.htm","","");
            return;
        case '20':   // SUBSCRIBER FROM LEFT MENU
            if(!checkLogIn()){
                return;
            }       
            var email = document.getElementById('email').value;
            var pswrd = document.getElementById('password').value;
            file = serverAddress + 
'registration/subscrDataV4.html?email=' + email + '&password=' + pswrd +

'&goal=update';
            break;
        case '21':   // NEW SUBSCRIPTION  ETC
            email = document.getElementById('email').value;
            pswrd = document.getElementById('password').value;
            file = serverAddress + 'registration/subscrDataV4.html';  
//?email=' + email + '&password=' + pswrd + '&goal=buyExt';
            break;
        case '22': // RENEW SUBSCRIPTION
            email = document.getElementById('email').value;
            pswrd = document.getElementById('password').value;
            file = serverAddress + 
'registration/subscrDataV4.html?email=' + email + '&password=' + pswrd; 
// + '&goal=buyExt';           
            break;
        case '23':   // ONE OF ABOVE FROM MENU
            var subscrStatus;
            try{
            subscrStatus = document.getElementById('renuSubscr').href;
            }
            catch(ex)  // Not logged in
            {
                alert('Please try logging in. If that fails it will give you an opportunity to purchase.');
                return;
            }
            index = subscrStatus.match(/\d{2}/);
            select_1(index);   //Recursive call           
            return;
        case '24':
            if(!checkLogIn()){
                return;
            }
            file = serverAddress + "preferences.html";
            break;
        case '25':   // Blog
            window.open("http://personalizedmedicineblog.com/","","");
            return;
        case '26':
            file = serverAddress + "introScreen.html";
            break;
        case '27':   // loginProblems
        //    alert(12345);
            email = document.getElementById('email').value;
            pswrd = document.getElementById('password').value;
            file = serverAddress + 'registration/registAjax.php?task=loginProblems&email=' + email + '&password=' + pswrd;           
            break;
        case '29':
            file = serverAddress + "warning.html";
            break;   
        case '30': // Tell a friend
            var name;
            try{
                name = document.getElementById('logInName').innerHTML;
            }
            catch(e){
                name = '';
            }
            window.location.href ="mailto:?subject=GeneMedRx drug interaction program&body=%0A%0A%0A%0AHere is a link to the GeneMedRx drug-drug and drug-gene interaction program.%22%0A%0A" + prologEngine + "?task=getDrugList%22%0A%0AYou can try the program. Medical professionals get a free trial subscription and others get a tour of the live program with example drug sets you can change. Also learn about complimentary subscription extensions for new subscribers and those who referred them. %0A%0A" + name;
			return;
        case '31':
            
			window.open("http://www.genemedrx.com/Cytochrome_P450_Metabolism_Table.php","","");
            return;       
        case '32':
			var wo = "http://www.genemedrx.com/CYPs_UGTS_childhood.php";
            window.open(wo,"","");
            return;
        case '33':
			var wo = "http://www.genemedrx.com/SLC_Transporters.php";
            window.open(wo,"","");
            return;
        case '34':
			var wo = "http://www.genemedrx.com/CYPs_UGTS_pregnancy.php";
            window.open(wo,"","");
            return;
        case '35':
            email = document.getElementById('email').value;
            file = 'http://www.mhc.com/registAjax.php?task=sendPassword_2&email=' + email;
            break;
        case '36':
            window.open("http://personalizedmedicineblog.com/genemedrx-news-and-updates/","","");
            return;       
        case '37':
            window.open("http://personalizedmedicineblog.com/recommended-literature/","","");
            return;       
        case '38':
            window.open("http://personalizedmedicineblog.com/recommended-presentations/","","");
            return;
        case '39':   // Guest wants demo
            file = serverAddress + 'registration/subscrDataV4.html'; 
            break;
        case '40':   //  by callback after log in
            file = serverAddress + "healthVaultRecords.html";
            break;
        case '41':    // Go get HV info'
                window.location="http://198.64.152.37:82/Default.aspx";
                //window.open("http://198.64.152.37:82/","","");
            return;
            break;
        case '42':    // Store HV info
            window.location="http://198.64.152.37:82/Store.aspx" + "?" + param2;          
			alert('window.location="http://198.64.152.37:82/Store.aspx"' + "?" + param2);
			window.open("http://198.64.152.37:82/Store.aspx","","");
            break;
        case '43':    //
                file = serverAddress + "help.html";
            break;
        case '44':    //
                file = serverAddress + "healthVault/recordFailed.html";
            break;
        case '45':    //
            window.open(param2,"","");
            return;   
        case '46':
			var wo = "http://www.genemedrx.com/ABCtransporters.php";
            window.open(wo,"","");
            return;
        case '48':   //
		   file = serverAddress + 'registration/subscrDataV4.html?goal=activateNonMed';
			iFrm = 'largeFrame2';
			docloc0 = 'zero';
           break;
        case '47':   // 
		   file = serverAddress + 'registration/subscrDataV4.html?goal=demo';
			iFrm = 'largeFrame2';
			docloc0 = 'zero';
           break;
  /*      case '49':
			var wo = "http://www.fda.gov/Drugs/GuidanceComplianceRegulatoryInformation/Surveillance/AdverseDrugEffects/ucm115894.htm";
            window.open(wo,"","");
            return;		*/   
    }

    keyHandlerStatus = false;       

    if(num == '0'){
        makeVisible('drugLists');
    }
    else{
        makeVisible(iFrm);
    }
//alert('docloc= ' + docloc0);
    if(docloc0 == 'zero')  // !!! Prevents browser from blocking web sites after the first away site.
    {
        if(navigator.userAgent.match(/Safari/i))
        {
            alert('Safari Requires in docloc');
        }
        var c = 0;
        var iframeDoc = frames[iFrm].document;
        docloc = iframeDoc.location;
        docloc0 = 1;
    }
//    alert('replacing' + file);
    docloc.replace(file);   
}


// For select_1()
var docloc;
var docloc0 = 'zero';http://localhost/cgi-bin/ddiD49.exe?server=local&task=getDrugList

function exampleSetup()
{
	document.getElementById("examplesIFrame").className="showIt";
}

function printSetup()
{
	try{
		theDrugSet.length;
	}
	catch(e){
		alert('I don\'t see any search results to print. Maybe you made a change in the medications since you last checked for interactions. If so, please make the new search. Then you can print.');
		return;
	}
	var doc = getIFrameDoc('recNotesIFr'); 
	var note = doc.getElementById("recNoteText").value;
	if(!guestUser){
		doc = getIFrameDoc('printIFrame'); 
		doc.getElementById("subscrName").value = document.getElementById("logInName").innerHTML;
	}
	document.getElementById("printIFrame").className="showIt";
//	skipMinorIneractions = getCookie('skipMinorIneractions');  // Set up because IE can't get cookie info from an iframs 08-11-09
//	alert('skipMinorIneractions=' + skipMinorIneractions);
	var smi = getCookie('skipMinorIneractions');
	if(smi != 'skip' && smi != 'show')
		setCookie('skipMinorIneractions','show',1500); 
	window.frames['printIFrame'].setup(note);
	
	
}

function delRecord()
{
	if(dnaTest)
	{
		alert('Sorry, in DNA test results mode GeneMedRx cannot delete the gene information in this record. However, you can delete individual drugs.');
		return;
	}
	var ret3way = getSelQuiet("selectRecord");
	if(ret3way.text == 'Select a record')
	{
		alert('Select a record first.');
		return;
	}
	var val = ret3way.value;
	if(val== 'xmpl' || val == 'HealthVaultPt')
	{
		if(val == 'HealthVaultPt')
		{
			healthVaultNoDelete();
			return;
		}
		alert('You cannot delete this example record but in the Preferences page you can choose not to load the example records.');
		return;
	}
	if(window.confirm('Do you want to delete the record of ' + ret3way.text + '?'))
	{
		var name = ret3way.text;  // New 09-02-20
		if(name.search(/UnknownName/) != -1)
		{
			arN = name.split("-- ");
			hash = 	arN[1];
		}
		else
		{
			hash = secureEncrypt(name,'kgH4C00PaD38Gbu');
			previousWindowVis = parent.windowVis;
			document.getElementById('selectRecord').size = 1;
			hash = hash.replace(/ /g,'+');
		}
		var url = serverAddress + 'ptData.php?task=delete&key=' + hash +
							 '&session=' + sessionNumber;
		sendAjax(url);
		document.getElementById('selectRecord').options[ret3way.index] = null;
		document.getElementById('selectRecord').selectedIndex = 0;
		document.getElementById("dateSpan").innerHTML = "-";
		delSelection('', 'all');
	}
}

function remvFromSelectBox(box)
{
//	alert('box is ' + box);
	var ret3way = getSelQuiet(box);
//	if(ret3way == null)
	if(!ret3way)
	{
		alert('First select name to delete.');
		return;
	}	
	document.getElementById(box).options[ret3way.index] = null;
}

function getSelQuiet(sel)
{
	cdH = document.getElementById(sel);
	var index = cdH.selectedIndex;
	if(index != -1) // A selection was made
	{
		var value = cdH.options[index].value;
		var text = cdH.options[index].text;
		return new SelectionData(index, text, value);
	}
	return null;
}

function SelectionData(i, t, v)
{
	this.index = i;
	this.text = t;
	this.value = v;
}

function saveSearch()
{
	if(!checkLogIn()){
		return;
	}
	if(checkGuestUser())
		return;
	var ret3way = getSelQuiet('selectRecord');
	if(!ret3way || ret3way.text == 'Select a record')  // There is no Current Record.
	{
		saveAs();
		return;
	}
	saveAnySearch(ret3way.text);
}

function saveAs()
{
	if(!checkLogIn()){
		return;
	}
	if(exTask == 'healthVault')
	{
		healthVaultSaveAsMes()
		return;
	}
	if(checkGuestUser()){
		return;
	}
	if(!makeDrugList())  // drgList is unused but if there is no list it warns user
		return;
//	alert('keyhandler');
	keyHandlerStatus = false;
	var text = '<table class="ninePntTrue"  border="0" cellspacing="20" cellpadding="0" bgcolor="#EEFFEE"><tr><td><div align="right"\ border="0" ><img onClick="hvCancelButton()" src="../ddi53/images/closeRed.jpg" width="25" height="25">\
    </div>\</td></tr>\
<td><span class="mj">Patient Name\
  </span></td>\
</tr><tr>\
<td>\
  <p>Please enter the patient\'s last name first so names<br>can be alphabetized.<br>\
  <br>\
    Last name, First name <input type="text" id="ptName">\
    <br>\
    <br>\
    <input type="submit" onClick="savePtName()" id="ptNameButton" value="Save">\
 </td>\
</tr></table>';
	document.getElementById("utilityDiv").className="showIt";
	document.getElementById("utilityDiv").innerHTML = text;	
	document.getElementById('ptName').focus();
}
	
function savePtName()
{
//	keyHandlerStatus = true;
	var nm = document.getElementById("ptName").value;
	if(nm == '')
	{
		alert('No name. Skipping save.');
		document.getElementById("utilityDiv").className="hideIt";
		return
	}
	document.getElementById("utilityDiv").className="hideIt";
	saveAnySearch(nm);	
}
		
function saveAnySearch(id)
{
	if(exTask != 'healthVault')
	{
		newName = id;
		var doc = getIFrameDoc('recNotesIFr');	 
		var note = doc.getElementById("recNoteText").value;
		var hash =  secureEncrypt(id,'kgH4C00PaD38Gbu');
		hash = hash.replace(/ /g,'+');
		noteHash = escape(note);
		var drgList = makeDrugList();
		if(!drgList || drgList == 0)
			return;
		rand = Math.random()* 100;
		var url = serverAddress + 'ptData.php?task=put&key=' + hash + '&drugs=' + drgList +
							 '&session=' + sessionNumber + '&note=' + noteHash + '&random=' + rand;
		sendAjax(url);
	}
	else
		sendHealthVaultMeds();
}


function openRecord()   
{
//	alert('open record');
	var ret3way = getSelQuiet("selectRecord");
	var hash;
	var xmpl = false;
	if(ret3way.value == 'xmpl')
		xmpl = true;
	if(ret3way.value == 'HealthVaultPt')
	{
		healthVaultOpenPtRecord();
		return;	
	}
	var name = ret3way.text;
	if(name.search(/UnknownName/) != -1)
	{
		arN = name.split("-- ");
		hash = 	arN[1];
	}
	else
	{
		hash = secureEncrypt(name,'kgH4C00PaD38Gbu');
		previousWindowVis = parent.windowVis;
		document.getElementById('selectRecord').size = 1;
		hash = hash.replace(/ /g,'+');
	}
	rand = Math.random()* 100;
	var paramsP = 'task=getOne&session=' + sessionNumber + '&key=' + hash +'&example=' + xmpl;
	var url = serverAddress +  'ptData.php?task=getOne&session=' + sessionNumber + '&key=' + hash +'&example=' + xmpl + '&random=' + rand;
	sendAjax(url);
	theDrugSet = null;
	compareType = 'none';	
	makeVisible('drugLists');
	cleanClinicalNote();
}


function urlencode(str) {
return escape(str).replace('+', '%2B').replace('%20', '+').replace('*', '%2A').replace('/', '%2F').replace('@', '%40');
}

function urldecode(str) {
return unescape(str.replace('+', ' '));
}

function openRecordMenu()
{
	if(!checkLogIn()){
		return;
	}
	if(globals.hvMember == 1)
	{
	//	alert('Since you keep your records in Microsoft HealthVault we will take you to HealthVault\'s place to select a record to open.');
		select_1(40);
		return;
	}
	alert('Select the record from the "Current Record" drop down list.');	
}

function newRecordMenu()
{
	if(!checkLogIn()) // || checkGuestUser() )
	{
		return;
	}
	if(dnaTest || exTask == 'healthVault')
	{
		if(exTask == 'healthVault')
		{
			healthVaultNewRec();
			return;
		}
		alert('Sorry, in DNA test results mode GeneMedRx cannot delete the gene information in this record. However, you can delete individual drugs.');
		return;
	}
	
	delSelection('drug','all');
	document.getElementById('selectRecord').selectedIndex = 0;
	document.getElementById("dateSpan").innerHTML = "-";
	makeVisible('drugLists');
	cleanClinicalNote();
}

function cleanClinicalNote()
{
	var doc = getIFrameDoc('recNotesIFr');
	doc.getElementById("recNoteText").value = '';
	document.getElementById("userNote").value = 'Click here to attach a note.';	// Display the first words of the note in the red bar.
	document.getElementById('recNotesIFr').className="hideIt";	
}

function getRecordsList()
{
//	alert('in getRecords');
	var ex = 'yes';
	if(getCookie('exampleRecords') == 'del') 
		ex = 'no';
	previousWindowVis = parent.windowVis;
	var url = serverAddress +  'ptData.php?task=getAll&session=' + sessionNumber + '&examples=' + ex;
	sendAjax(url);
}

function showOptions() {
	var iframeDoc = getIFrameDoc('noteWindow'); 
	var rep = serverAddress + "options.html:"
	iframeDoc.location.replace(rep); 		
}

// ------------------------- COOKIES ----------------------------------------
function setCookie(cookieName,cookieValue,nDays) 
{
 var today = new Date();
 var expire = new Date();
 if (!nDays){ nDays=1;}
 expire.setTime(today.getTime() + 3600000*24*nDays);
 document.cookie = cookieName+"="+escape(cookieValue)
                 + ";expires="+expire.toGMTString();
//alert(document.cookie.indexOf(cookieName) + '  ' + cookieName);
 if(document.cookie.indexOf(cookieName) == -1)
 	alert('Cookies must be enabled in your browser for setting to be saved.');
}

function getCookie(cookieName) {
 var theCookie=""+document.cookie;
 var ind=theCookie.indexOf(cookieName);
 if (ind==-1 || !cookieName){ return ""; }
 var ind1=theCookie.indexOf(';',ind);
 if (ind1==-1){ ind1=theCookie.length;} 
 return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}

function gettingStarted(checked)
{
	if(checked){
		setCookie('getStart','false',1500);
	}
	else{ 
		setCookie('getStart','true',1500);
	}
}

//getRecordsList()
//<input onClick="parent.setPreference('examples', this.checked);parent.setPreference('exampleRecords', this.checked); document.getElementById('examples1').checked = false;
function setPreference(type, checked)
{
//alert(type + ' ' + checked);
	if(type == 'examplesWindow')
	{
//	alert('in' + checked);
		if(checked)
			setTo = 'no';		
		else 
			setTo = 'yes';
	}
	
	if(type == 'exampleRecords')
	{
		if(checked)
		{
			setCookie(type,'keep',1500);   //setTo = 'keep';
	//		alert('set examples to keep'); 
			getRecordsList();
			return;
		} 
		else
		{ 
			setTo = 'del';
		}
	}
	if(type == 'getStart')
	{
		if(checked)
		{
			setTo = 'false'; 
		}
		else 
			setTo = 'false';
	}
	
	if(type == 'drugNames')
	{
		if(checked)
		{
			setCookie(type,'show',1500);   //setTo = 'keep';
			return;
		} 
		else
		{ 
			setTo = 'hide';
		}
	}	
	setCookie(type,setTo,1500);
}

function gettingStartedSuite(checked)
{
	if(checked){
		setCookie('getStart','true',1500);
		setCookie('introScreen','show',1500);
		setCookie('examplesWindow','yes',1500);
		setCookie('exampleRecords','keep',1500);
	}
	else{ 
		setCookie('getStart','false',1500);
		setCookie('introScreen','skip',1500);
		setCookie('examplesWindow','no',1500);
		setCookie('exampleRecords','del',1500);	
	}
}

function introScreen(checked)
{
	if(checked){
		setCookie('introScreen','show',1500);
	}
	else{ 
		setCookie('introScreen','skip',1500);
	}
}


function skipMinorIneractions(val)
{
	if(val == 'skip')
	{
		setCookie('skipMinorIneractions','skip',1500);
	}
	else{ 
		setCookie('skipMinorIneractions','show',1500);
	}
	theDrugSet = null;   // Force new search after change
}

function saveLogin(checked)
{
	if(checked) // Checked means do not save log in info
	{
		setCookie('loginPreference','yes',1500);
		setCookie('new','',1500);
		setCookie('email','',1500);		
	}
	else{ 
		setCookie('loginPreference','no',1500);
	}
}



function updateLoginName(firstName,lastName)
{
	document.getElementById('logInName').innerHTML = '<b>' + firstName + ' ' + lastName + '</b>';
}

function saveLoginBox(checkedStatus) // Attempting to save log in info; be sure its allowed by the preference setting
{
	if(getCookie('loginPreference') == 'yes' && checkedStatus == true)
	{
		alert('You have set your preference to not save log in information. Change the preference (in the preferences menu item on the left of the screen) before attempting to save log in information.');
		document.getElementById('saveLoginInfo').checked= false;	
	}
}

function showAltNamesWindow()  //id,domStyle,event)    // Displays the window when showAlternativeNames button is clicked
{
	var doc = getIFrameDoc('iFrame0');
	cdH = doc.getElementById('drugSelect');
	var index = cdH.selectedIndex;
	if(index == -1)
	{
		alert('Please select a drug first.');
		return;
	}	
	var genericID = cdH.options[index].value;
	var name = cdH.options[index].text;
	document.getElementById('formAlt').action = serverAddress + 'ddiAjax4.php';		
	document.getElementById("genericID").value = genericID;
	document.getElementById('name').value = name;
	document.getElementById('formAlt').submit();
	makeVisible('largeFrame');
}

function sendAjax(url)
{	
	xmlHttp.open("GET",url,true);
	xmlHttp.onreadystatechange = callback;
	xmlHttp.send(null);
}

function sendAjaxPOST(url,queryString)
{	
	xmlHttp.open("POST",url,true);
	xmlHttp.onreadystatechange = callback;
	xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
	xmlHttp.send(queryString);
}

function callback()
{
	if(xmlHttp.readyState == 4)
	{
		if(xmlHttp.status == 200)
		{
			doCallBackWork(xmlHttp.responseText);  
		}
	}
}
//	doCallBackWork('callBackID*=*logIn*,*status*=*good*,*name*=*owner');
function doCallBackWork(resp)
{
//alert('resp=' + resp);
	switch (getKeyValue('callBackID',resp))
	{
		case 'logIn':
//		alert('In ddi44 ' + resp);
			if(parent.exTask == 'medDem' || parent.exTask == 'toActivDNASubscr')
			{
				document.getElementById('mainDiv').className= 'showIt';
				document.getElementById('regDiv').className= 'hideIt';
		//		document.getElementById('bMenu').style.display='block'; 
			}
				
			var status = getKeyValue('status',resp);
			if(status == 'good' || status == 'dnaUser')
			{
				var email = document.getElementById('email').value;
				var thisstuff = document.getElementById('password').value;
				if(cookiesEnabled() && getCookie('loginPreference') != 'yes' && document.getElementById('saveLoginInfo').checked)
				{
					setCookie('new',thisstuff,1500);
					setCookie('email',email,1500);
				}			
				document.getElementById("loginDiv").className="hideIt";
				document.getElementById("logoutDiv").className="right";
				document.getElementById("logInText").innerHTML = getKeyValue('logInText',resp);
				sessionNumber = getKeyValue('sessionNumber',resp);
				makeVisible('drugLists');
	//			alert('in log in');
	//			Loadd = 0;
				Go();
	//			document.getElementById('gmxMenu').className= 'showIt';
	//			alert(343434);
				logInDone = true;
				var hvMemb = getKeyValue('healthVaultRecords',resp);
				if(hvMemb == 0 && globals.intoPageNewHVUser == true)  // User can set this to true from intro page intoPageNewHVUser
				{
					hvMemb = 1;
					var url = parent.serverAddress + 'ddiAjax4.php?task=whereSaveRecords&sessionNumber=' + sessionNumber + '&hvType=1';
					sendAjax(url);
					globals.hvMember = true;
				}
				if(hvMemb == 1)
				{
					globals.hvMember = true;
					if(exTask == 'none')
					{
						select_1(40);
						logInDone = false;
						return;
					}
					if(exTask == 'healthVault')
					{
				//		alert('will get records 1');
						getRecordsList();
					}
				}
				else
				{
					getRecordsList();
				}
				if(getCookie('examplesWindow') != 'no')
					exampleSetup();				
			}
			else if(status == 'unknown')
			{
					select_1(27);
			}
			else if(status == 'failure')
			{
				var mes = getKeyValue('message',resp);
				alert(mes);
			}	
			else if (status == 'bad')
			{	// res == bad
				var subscriberType = getKeyValue('subscriberType',resp);
				if(subscriberType == 'demo'){
					alert('Your demo subscription has expired. Purchase a subscription in the window which appears after this one. First we will confirm your registration information. When the purchase is completed log in again (above).');
					select_1(21);
				}
				else{
					alert('Your subscription has expired. Purchase a subscription in the window which appears after this one. First we will confirm your registration information. When the purchase is completed log in again (above).');
					select_1(22);   // Paid subscriber lapsed subscription
				}					
			}
			break;
		case 'regSearch':
//		alert('in research' + resp);
			var table = getKeyValue('table',resp);
			var notes = getKeyValue('notes',resp);
			var compareText = getKeyValue('compareText',resp);
			makeVisible('searchResults');
			var doc = getIFrameDoc('tableIFrame');
			doc.getElementById("tableDiv").innerHTML = table;
			var doc3 = getIFrameDoc('start_stopIFrame');			
			var doc2 = getIFrameDoc('notesIFrame');
			doc2.getElementById('notesDiv').innerHTML = notes;
			doc2.getElementById("namesText").className='note4Hid';
			doc3.getElementById('startStopDiv').innerHTML = compareText;
			if(showAlgo != '')
			{
				if(algoWin)
					algoWin.close();
				var algoAd = serverAddress + "algo.html";
				algoWin = window.open(algoAd,"","height=300, width=700, resizable=yes, scrollbars=yes, toolbar=no");
				algoWin.document.write(getKeyValue('algo',resp));
				algoWin.document.close();
			}
			parent.setUp();
			try
			{
				frames.updatingFrame.updateCurious();  // runs the curious update function
			}
			catch(e){;}
			break;		
		case 'getClasses':
			doc = parent.getIFrameDoc("notesIFrame");
			doc.getElementById('utilityDiv').innerHTML = getKeyValue('classes',resp);
			showAdditInfo('utilityDiv');
			// 07-07-13 popUp('utilityDiv','halfHalf');
			break;			
		case 'getDrugs':
			document.getElementById('drugsDiv').innerHTML = getKeyValue('drugList',resp);
			break;
		case 'alternDrugs':
//			alert(resp);
			doc = parent.getIFrameDoc("notesIFrame");
			doc.getElementById('utilityDivSub').innerHTML = getKeyValue('drugList',resp);
			showAdditInfo('utilityDiv');
			break;			
		case 'drugTables':
			doc = parent.getIFrameDoc("notesIFrame");
//			alert('finding utility div in ' + doc.title);
			doc.getElementById('utilityDiv').innerHTML = getKeyValue('tables',resp);
			// 07-07-13 popUp('utilityDiv');
			showAdditInfo('utilityDiv');
			break;
		case 'gotRecord':
			if(getKeyValue('version',resp) == 1){
				openVer1(getKeyValue('drugList',resp));
			}
			else{
				openVer0(getKeyValue('drugList',resp));
			}
			break;
		case 'lookMoreFound':
			var name= getKeyValue('name',resp);
			var genericID = getKeyValue('genericID',resp);
			addToList(name,genericID);
			alert('Found it!');
			break;
		case 'lookMoreSelectBox':
			var page= getKeyValue('page',resp);
			makeVisible('largeFrame');
		//	frames['largeFrame'].document.body.innerHTML = page;  //07-10-17
			frames.largeFrame.document.body.innerHTML = page;  //07-11-8

			break;
		case 'updating':
			var drug= getKeyValue('drug',resp);
			var gene= getKeyValue('gene',resp);
			document.getElementById("recentDrugSpan").innerHTML = drug;
			document.getElementById("recentGeneSpan").innerHTML = gene;			
			break;
		case 'recordInserted':
			if(getKeyValue('value',resp) == 'yes')
			{
				if(findExactItem(newName,"selectRecord") == -1)
				{
					toBox = document.getElementById("selectRecord");
					var len = toBox.options.length;
					toBox.options[len] = new Option(newName,'ver2');
					toBox.options.selectedIndex = len;
				}
				document.getElementById("dateSpan").innerHTML = getKeyValue('date',resp);
				if(window.ActiveXObject)
				{
					alert('Record saved');
				}
				else 
				{
					document.getElementById("dateSpan").className = 'blinkON';
					window.setTimeout("stopBlinking('dateSpan');",5000);
				}
				newName = '';
			}
			else if(getKeyValue('value',resp) == 'debug' || getKeyValue('value',resp) == 'no')
			{
				var mes =getKeyValue('message',resp);
				alert(mes);
			}			
			break;
		case 'getOne':
//			alert(resp);
			if(getKeyValue('drugs',resp) == 'notFound')
			{
				// v50 09-01-01 
				var key = getKeyValue('key',resp);
//				key = urldecode(key);
				var name = secureDecrypt(key,'kgH4C00PaD38Gbu');
				alert('I could not find any record for ' + name +'.');
				break;
			}
			else	
			{
				document.getElementById("dateSpan").innerHTML = getKeyValue('date',resp);
				parseDrugList(getKeyValue('drugs',resp));
				var doc = getIFrameDoc('recNotesIFr');
				var noteHash = getKeyValue('note',resp);
				if(noteHash != 'DVpsb 57yRI=')
				{
					if(noteHash.length != 0)
					{
						noteHash = unescape(noteHash);
						doc.getElementById("recNoteText").value = noteHash;
					}
					else
						doc.getElementById("recNoteText").value = '';
					frames['recNotesIFr'].displayTeaser();	// Display the first words of the note in the red bar.
				}
				if(getKeyValue('type',resp) == 'dnaTest')
				{
					dnaTest = true;   // Used to prevent deletion of genes
				}								
			}
			break;
		case 'gotAll':
			var c = 1;
			if(globals.hvMember == true)   // && exTask == 'healthVault')
			{
				healthVaultMeds();
				c++;
			}
			
	//		alert('get all');		
			var names= getKeyValue('names',resp);
			var encryptedNamesArray = names.split(',');
			var frag = 'Number of names=' + encryptedNamesArray.length;
//			addToDebugDiv(frag);			
			var myAr = new Array();
			for(i_encr in encryptedNamesArray)
			{
//				console.log(i_encr);
	//			try
	//			{
					frag = '<br>index=' + i_encr + ' content: ' + encryptedNamesArray[i_encr];
		//			addToDebugDiv(frag);
			//		alert('wil dcrpy ' + i_encr);
					var datPair = encryptedNamesArray[i_encr].split('^');
					var encrName = datPair[0].replace(/ /g,'+'); 
	//				alert('wil dcrpy ' + i_encr + '  ' + encrName);
					var uncrypt = secureDecrypt(encrName,'kgH4C00PaD38Gbu');
					if(uncrypt == '')
					{
						uncrypt = 'UnknownName ' + i_encr + ' -- ' + datPair[0];
						var email = getCookie('email');
						var url = serverAddress + 'ptData.php?task=encrypterrors&email=' + email + '&key=' + datPair[0];
						sendAjax(url);	
	
					}
					//09-02-19 myAr[i_encr] = secureDecrypt(encrName,'kgH4C00PaD38Gbu') + '^' + datPair[1];
					myAr[i_encr] = uncrypt + '^' + datPair[1];
		/*		}
				catch(e)
				{
					console.log('heelo');
					console.log(encryptedNamesArray[i_encr]);
				}
				*/
			}
			var alphaArray = myAr.sort();
			toBox = document.getElementById("selectRecord");
			var dNum = 0;
			var dnaTestRecord;
			var dnaName;
//			alert('encryptedNamesArray =' + encryptedNamesArray.length);
/* 08-05-12 */
	//		frag = '<br>******* Done" Number unencrypted=' +  alphaArray.length;
	//		addToDebugDiv(frag);
			for(i_al in alphaArray)
			{
				var datPair = alphaArray[i_al].split('^');
				if(datPair[0].length > 2)
				{
					var val = datPair[1];
					toBox.options[c] = new Option(datPair[0],val);
					if(val.search(/dnaTest/) != -1)
					{
						dNum++;  // Sets up display of dnaTestRecord only if there is only one dnaTest record.
						dnaTestRecord = c;
						dnaName = name;
					}	
					c++;
				}

			}
			
			if(showDNATestPt && dNum == 1)  // There is one dnaTest record to display. | showDNATestPt is set true only in registration code
			{
				var sel = document.getElementById("selectRecord");
				sel.selectedIndex = dnaTestRecord;
				openRecord();
			}
			var decrypt = 'good';
			if(alphaArray.length != encryptedNamesArray.length)				
				decrypt = 'bad';
			postLogIn();
			sendDebug(decrypt);
			break;	
		case 'deleted':
			if(getKeyValue('message',resp) != 1)
			{
				var key = getKeyValue('key',resp);   // 09-01-01 v50 added name info - changed alert text
				var name = secureDecrypt(key,'kgH4C00PaD38Gbu');
				alert('Record of ' + name + ' has been deleted.');

	//			var mes = getKeyValue('message',resp);
	//			alert(mes);
				break;
			}
			alert('Record deleted.');
			break;
		case 'updateCurious':
			doc = parent.getIFrameDoc("updatingFrame");
			doc.getElementById('dbChanges').innerHTML = getKeyValue('dbChanges',resp);
			doc.getElementById('recentPred').innerHTML = getKeyValue('recentPred',resp);			
			break;
		case 'sendEmail_stored':  // Do nothing!
//			alert(resp);
			break;
		case 'logInGuest':
//			alert(resp);
			document.getElementById("loginDiv").className="hideIt";
			document.getElementById("logoutDiv").className="right";
			document.getElementById("logInText").innerHTML = getKeyValue('logInText',resp);
			sessionNumber = getKeyValue('sessionNumber',resp);
			logInDone = true;
			guestUser = true;
			url = serverAddress +  'ptData.php?task=getAll&session=' + sessionNumber + '&examples=yes';
			sendAjax(url);
			var doc = getIFrameDoc('guestIFr');	
			doc.getElementById("name").innerHTML = document.getElementById('logInName').innerHTML;
			break;
		case 'logInTour':
			document.getElementById("loginDiv").className="hideIt";
			document.getElementById("logoutDiv").className="right";
			document.getElementById("logInText").innerHTML = getKeyValue('logInText',resp);
			sessionNumber = getKeyValue('sessionNumber',resp);
			logInDone = true;
			guestUser = true;
			setupTourSub();
			break;
		case 'noSessionActive':
			alert('Your log in session has expired or you have logged in on another computer. Please log in again.');
			break;				
	}
}

function dnaUserPatientNames(_0)
{
	this.namesAr = _0;
}

function parseDrugList(drugList)
{
//alert('druglist = ' + drugList);
	var ar = drugList.split("],[");
//	if(!drugList || ar.length < 2)  // Server can return malformed cList if ptID wrong.
//	{
//		alert('I could not retrieve a record with that identifier.');
//		return;
//	}
//	parent.parent.
	delSelection('drug','all','parser');
	var toBox = document.getElementById('chosenList');
	var frag;
//	alert('array len=' + ar.length);
	for(j=0;j<ar.length;j++)
	{
//		alert('0 ar[' + j +']=' + ar[j]);
		var x = ar[j];
		ar[j] = ar[j].replace(/`\d-/g,'');   // Remove "0-" before genericID
//		alert('1 before = ' + x + ' and after = ' + ar[j]);
//		frag = ar[j].replace(/\w+\(\[|\]|\[|`|\)/g,'');
		frag = ar[j].replace(/\w+\(\[|\]|\[|`/g,'');
//		alert('2 frag = ' + frag);
//		frag = ar[j].replace(/\]|\[|`|\d-/g,'');
//		alert(frag);
		var ar2 = frag.split(',');
//		alert('2a frag = ' + frag);
		var uFin = ar2[1].split(':');
//		alert('3 uFin 0 and ar2[0] ' + uFin[0],ar2[0]);
		addToList(uFin[0],ar2[0]);  // drug name, drug id
//		alert('4 frag = ' + frag);
		uFin[1] = uFin[1].replace(/\)/g,'');
//		alert('5 uFin = ' + uFin[1]);
		switch(uFin[1])  // Set the start/stop.cont status
		{
			case 'cont':
				setDrugToContinue(ar2[0]);		
				break;
			case 'start':
				setDrugToStart(ar2[0]);
				break;
			case 'stop':
				setDrugToStop(ar2[0]);
				break;
		}
	}
}

function openVer1(cList)  // For version 2 records on server only
{
//	alert(cList);
	var ar = cList.split("],[");
	if(!cList || ar.length < 2)  // Server can return malformed cList if ptID wrong.
	{
		alert('I could not retrieve a record with that identifier.');
		return;
	}
//	parent.parent.
	delSelection('drug','all');
	var toBox = document.getElementById('chosenList');
	var frag;
	for(j=0;j<ar.length;j++)
	{
		fragp = ar[j].replace(/\]/g,'');
		frag = fragp.replace(/\[/g,'');
		var ar2 = frag.split(",");
		var uFin = ar2[1].split(":");
		var tx;
		
		var drugName = uFin[0];
		var id = ar2[0];
		var status = uFin[1];
		switch(uFin[1])
		{
			case 'cont':
				toBox.options[j] = new Option(uFin[0],ar2[0]);
				toBox.options[j].className ='normal';
				
				break;
			case 'start':
				tx = uFin[0] + ' START';				
				toBox.options[j] = new Option(tx,ar2[0]);
				toBox.options[j].className ='start';
				break;
			case 'stop':
				tx = uFin[0] + ' STOP';
				toBox.options[j] = new Option(tx,ar2[0]);
				toBox.options[j].className ='stop';
				break;
		}
	}
	parent.parent.hidePtFileWindow();	
}

function createXMLHttpRequest()
{
	if(window.ActiveXObject)
	{
		xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	else if(window.XMLHttpRequest){
		xmlHttp = new XMLHttpRequest();
	}
		
}

//"callBackID=selectClass,subclassList=" . $list . ",classMemeberList=" . $memberList;
function getKeyValue(key,inputString)
{
	var keyArray = inputString.split('*,*');
	for(i in keyArray)
	{
		var kv = keyArray[i].split('*=*');
		if(kv[0] == key){
			return kv[1];
		}
	}
	return -1;
}
//----------------------------------------- ALTERNATIVE DRUGS WINDOW ---------------------------------------------------------------

function showAlternatives(type,route,drug,genericID,mode)
{
	//Get the list of classes
//	createXMLHttpRequest();
	var url = serverAddress + 'ddiAjax4.php?task=getClasses&type=' + type + '&route=' + route + '&drug=' + drug + '&genericid=' + genericID + '&mode=' + mode;	
	sendAjax(url);
//	xmlHttp.onreadystatechange = callback;
//	xmlHttp.open("POST",url);
//	xmlHttp.onreadystatechange = callback;
//	xmlHttp.send(null);	
} 
	

function hideAlternativesWindow()
{
	document.getElementById("alternativesField").className = 'listNone';
}

//--------------------------------------------------------------------------------------------------

function flippingAnchor(theSpan) // If it is showing take it away; if not show it.
{
	cdH = document.getElementById('utilityDivSub').innerHTML = document.getElementById(theSpan).innerHTML;
}

function getAlternatives(classID,classx,typex,route,drug,mode)
{
	var url = prologEngine + '?progType=alternDrugs&type=' + typex + '&class=' + classx + '&route=' + route + '&drug=' + drug + '&mode=' + mode;	
	sendAjax(url);
}

function showCasesWindow(evt)
{
	var topVal = evt.clientY + 30;
	var leftVal = evt.clientX;
	parent.document.getElementById("casesField").style.left = leftVal;
	parent.document.getElementById("casesField").style.top = topVal;
	parent.document.getElementById('casesSpan').innerHTML = '<form name=\"form9\">Clinical vignettes and comments entered here will appear immediately in the \"For the Curious\" window of the drug entry page  <input type=\"button\"  onClick= \"javascript:displayVignettes()\"  value="See\">. The authors attempt to respond when it may be helpful. Include your name and e-mail in the message if you like.<br> Headline: <input type=\"text\"  id=\"title\"  size=\"35\"><textarea  name=\"note\" rows=\"7\" cols=\"35\"  value=\"\"></textarea>My e-mail is <input type=\"text\"  id=\"emailAddr\" size=\"20\"> (If you would like us to respond. It will not display with your message.)<input type=\"button\" name=\"sendCaseBtn\" value=\"Send\" onClick=\"sendCase(form9.title.value, form9.note.value, form9.emailAddr.value)\"></form>';
	parent.document.getElementById("casesField").className = 'showIt';	
}	

function hideCasesWindow()
{
	parent.document.getElementById("casesField").className = 'listNone';
}
function sendCase(title,note,emailAddr)
{
	if(title.length < 5)
	{
		alert('A heading or title of some kind is needed so people can find your note by topic.');
		return;
	}
	if(note.length > 10)
	{
//		createXMLHttpRequest();
		var url = serverAddress + 'ddiAjax4.php?task=caseReport&title=' + title + '&note=' + note + '&emailAddr=' + emailAddr;
		sendAjax(url);	
//		xmlHttp.onreadystatechange = callback;
//		xmlHttp.open("GET",url);
	//	xmlHttp.onreadystatechange = callback;
//		xmlHttp.send(null);
	}
	else{
		alert("Thank you but there did not seem to be any message.");
	}
//	parent.document.getElementById("casesField").className = 'listNone';
}

function logIn()
{
//alert('login init');
	var email = document.getElementById('email').value;
	var thisstuff = document.getElementById('password').value;
	logInSub(email,thisstuff);
}

function logInSub(email,thisstuff)
{
	var n = Math.round(100000*Math.random())
	var url = serverAddress + 'registration/registAjax.php?task=logIn&email=' + email + '&password=' + thisstuff + '&rand=' + n;
	sendAjax(url);
}


function logOut()
{
	document.getElementById("password").value = '';
	document.getElementById("email").value = '';
	document.getElementById("logoutDiv").className="hideIt";
	document.getElementById("loginDiv").className="right";
	document.getElementById("selectRecord").options.length=1;
	makeVisible('drugLists');
	exTask = 'none';
	logInDone = false;
	guestUser = false;
	delSelection('drug','all');
}

function checkLogIn()
{
	if(logInDone){
		return true;
	}
	else
	{
		alert('Please log in');
		return false;
	}
}

function checkGuestUser()
{
//alert(guestUser);
	if(!guestUser){
		return false;
	}
	else
	{
		alert('Sorry, This function is only available to subscribers.');
		return true;
	}
}

function lookMore()
{
	var name = document.getElementById('initLetBox').value;
	if(!name){
		alert('Please enter at least the initial letter first.');
		return;
	}
//	alert(sessionNumber);
//	createXMLHttpRequest();
	var url = serverAddress + 'ddiAjax4.php?task=lookMore&name=' + name;
//	alert(url);
	sendAjax(url);
//	xmlHttp.onreadystatechange = callback;	
//	xmlHttp.open("get",url);
//	xmlHttp.onreadystatechange = callback;
//	xmlHttp.send(null);	
}

function showIt(doc)
{
	switch(doc)
	{
/* 08-11-01	 ? not used	case '1':
			window.open('http://www.genemedrx.com/contact.html',"","");
			break;
			*/
		case '2':
		
			Mail="mailto: joesterheld@gwi.net?subject=Help&message=themessage";
			window.location.href=Mail;
			break;	
		case '3':
		
			Mail="mailto: Kristine Ashcraft <KAshcraft@genelex.com>?subject=Help&message=themessage";
			window.location.href=Mail;
			break;	
	}
}
/*
function extWindow(num)
{
	if(num = 1){
		window.open("http://robertpatterson.wordpress.com/tag/p450/","","");
	}
}
*/

function smallWindowSizer(type)
{
	if(parent.document.title != 'gmdrxMini'){
		return;
	}
	var cdH = parent.frames.tableIFrame.document.getElementById('note_100');	
	if(!cdH){
		parent.document.getElementById('start-Stop').disabled = true;
	}
	else{
		parent.document.getElementById('start-Stop').disabled = false;
	}		
	switch (type)
	{
		case 'utilityDiv':  // Show bottom window full screen
		//	parent.document.getElementById("tableIFrame").height="200";
			parent.document.getElementById("notesIFrame").height="370";
			parent.document.getElementById("notesIFrame").className="showIt";
			parent.document.getElementById("tableIFrame").className="hideIt";
			parent.document.getElementById('btm').disabled = true;
			parent.document.getElementById('top').disabled = false;
			parent.document.getElementById('both').disabled = false;
			parent.document.getElementById("devider").className="hideIt";		
			break;
		case 'expandPop':    // Show Main results - top - only

			parent.document.getElementById("tableIFrame").height="370";
			parent.document.getElementById("notesIFrame").className="hideIt";
			parent.document.getElementById("tableIFrame").className="showIt";
			parent.document.getElementById('top').disabled = true;
			parent.document.getElementById('btm').disabled = false;
			parent.document.getElementById('both').disabled = false;
			parent.document.getElementById("devider").className="hideIt";		
			break;
		default:  // '50-50':
			parent.document.getElementById("tableIFrame").height="201";
			parent.document.getElementById("notesIFrame").height="169";
			parent.document.getElementById("notesIFrame").className="showIt";
			parent.document.getElementById("tableIFrame").className="showIt";		
			parent.document.getElementById('btm').disabled = false;
			parent.document.getElementById('top').disabled = false;
			parent.document.getElementById('both').disabled = true;
			parent.document.getElementById("devider").className="showIt";
			break;						
	}	
}

function st_stPopUp(type)
{
	var text = parent.frames.notesIFrame.document.getElementById(type).innerHTML;
	document.getElementById('helpSpan').innerHTML = '<strong>Help:</strong> ' + text;
}


function makeVisible(item)
{
//	var oppVisibility = 'showIt';makeVisible('comparison')
//	if(className == 'showIt')
//		oppVisibility = 'hideIt';
	switch (item)  // Menu in drug selection page
	{
		case 'drugLists':
			if(globals.hvMember && !logInDone)
			{
				alert("Please click \'Copy from HealthVault\' or \'Skip HealthVault this time.\'");
				return;
			}
			document.getElementById('drugLists').className='showIt';
			document.getElementById('utilityWindows').className='hideIt';
			document.getElementById('searchResults').className='hideIt';
			document.getElementById('initLetBox').focus();
			document.getElementById('initLetBox').value = '';
			document.getElementById('startHereImg').className='showIt';
			keyHandlerStatus = true;
			document.getElementById('menu_li_0').className='selected';
			document.getElementById('menu_li_1').className='';
			document.getElementById('goBack').className='hideIt';
			break;
		case 'searchResults':
			document.getElementById('menu_li_1').className='selected';
			document.getElementById('menu_li_0').className='';
			document.getElementById('drugLists').className='hideIt';
			document.getElementById('utilityWindows').className='hideIt';
			document.getElementById('searchResults').className='showIt';
			document.getElementById('preResultIFrame').className='hideIt';		
			document.getElementById('resultsSpace').className='showIt';
			document.getElementById('startHereImg').className='hideIt';
			document.getElementById('goBack').className='showIt';
			
			break;
		case 'largeFrame':
			document.getElementById('menu_li_0').className='';
			document.getElementById('menu_li_1').className='';
			document.getElementById('drugLists').className='hideIt';
			document.getElementById('searchResults').className='hideIt';
			document.getElementById('utilityWindows').className='showIt';
			document.getElementById('largeFrame').className='showIt';
			document.getElementById('startHereImg').className =  'hideIt';
			document.getElementById('goBack').className='showIt';
			break;			
		case 'gettingResultsPage':
			document.getElementById('searchResults').className='showIt';
			document.getElementById('preResultIFrame').className='showIt';
			document.getElementById('drugLists').className='hideIt';
			document.getElementById('utilityWindows').className='hideIt';
			document.getElementById('resultsSpace').className='hideIt';
			break;
	}
}

var debugText = '';

function addToDebugDiv(frag)
{
	debugText = debugText + frag;	
}

function sendDebug(decrypt)
{
	
	document.getElementById('debugDiv').innerHTML = debugText;	
	document.getElementById('debugDiv').className= 'showIt';
}

function updateMessage()
{
	var text = "<table width=\"700\" class=\"ninePntTrue\"  border=\"0\" cellspacing=\"20\" cellpadding=\"0\" bgcolor=\"#EEFFEE\"><tr><td><div align=\"right\" border=\"0\" ><img\ onClick=\"hvCancelButton()\" src=\"../ddi53/images/closeRed.jpg\" width=\"25\" height=\"25\">\
    </div>\</td></tr>\
<p><strong>GeneMedRx Update<br><br>\
<strong>July 22, 2009 Version Upgrade</strong></p>\
<p>GeneMedRx was recently updated.  In addition to extensive note and drug interaction updates, improvements you  will notice include:</p>\
<ul type=\"disc\">\
  <li><strong>Drugs With No Metabolism Information Flagged.</strong> Medications for which there is no published metabolism information are now flagged with \"No Data\" so\ clinicians can       distinguish between drugs predicted to have no change and those where a prediction is not possible.<br />\
    <br />\
  </li>\
  <li><strong>Supplements Added.</strong> The Herbals section has been renamed &quot;Supplements/Herbals&quot; and numerous supplements have been added.<br />\
    <br />\
  </li>\
  <li><strong>Michael Jackson Medication Example Added</strong> -&nbsp;The purported drug list of the late Michael Jackson has been added. GeneMedRx predicts problems that most \drug interaction       programs would miss.<br />\
    <br />\
  </li>\
  <li><strong>Drug Package Inserts Expanded</strong>- Package inserts for many more medications are now available in the evidence column.<br />\
    <br />\
  </li>\
  <li><strong>Layout Improvements </strong>Several changes have been made to improve readability including: </li>\
  <ul type=\"circle\">\
    <li>Printing - If minor interactions were omitted it is stated in the main heading of the report.</li>\
    <li>Genes and some patient characteristics now show &quot;Not Relevant&quot; because the concept of change in exposure does not apply to them.<br />\
      <br />\
    </li>\
  </ul>\
  <li><strong>Percentage Change Displayed When Available</strong> - In the &quot;will go&quot; column the up or down arrow is now accompanied by the percentage change  \     predicted when it is quantifiable. This gives more information about what  the algorithm predicts for each interaction.<br />\
    <br />\
  </li>\
  <li><strong>Drug-Class Interactions Improved</strong> Drug interaction predictions based on whole classes of drugs have been improved. The program uses information about       the\ hierarchy of drug classes to make its predictions. Multiple drug-class interactions can be reported for any drug.<br />\
    <br />\
  </li>\
  <li><strong>ADR Reporting Simplified</strong> The results page now has a link to the FDA       adverse drug reaction reporting pages.<strong><br />\
  </strong></li>\
</ul>\
<p>We look forward to  continuing to work with you to improve this tool for safer and more effective  prescribing.<br />\
    <br />\
  Best Regards,<br />\
  <br />\
  <img src=\"http://www.genemedrx.com/images/logo_genemedrx.gif\" alt=\"logo\" width=\"120\" height=\"41\" /><br />\
  The GeneMedRx Team</p>\
<p>P.S.&nbsp;<strong>90-day  Subscription Extension for Referrals. </strong>Remember that we reward  you for referrals, when subscribers help us spread the word about GeneMedRx we  give back extensions of subscriptions. Simply click on the tell-a-friend button  to tell colleagues about GeneMedRx and if they purchase, you both receive a  90-day extension.</p>\
  </div><input type=\"checkbox\" onClick=\"hideUpdateBox()\" /> Do not show this window in the future.</td>\
</tr></table>";
	document.getElementById("utilityDiv").className="showIt";
	document.getElementById("utilityDiv").innerHTML = text;	
}

function upgrade(x)
{
	window.open("http://mhc.daytondcs.com:8080/cgi-bin/ddiD53?task=getDrugList","","");
}

function hideUpdateBox()
{
	setCookie('updateBox7-22','skip',1500);
	document.getElementById("utilityDiv").className="hideIt";
}

