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

		Script loaded if HealthVault member

*/
/* 6/4/08
function medCheckWindow()
{
	var iframeDoc = getIFrameDoc('hvFrame'); 
	document.getElementById("hvFrame").className="showIt";
}

function healthVaultPtName(ptName)  //healthVaultMeds()
{
//	healthVaultOpenPtRecord();
	toBox = document.getElementById("selectRecord");
	var len = toBox.options.length;
	toBox.options[len] = new Option(ptName,'HealthVaultPt');  // ptName is a global added to page
	toBox.options.selectedIndex = len;
//	alert('selected it');
	document.getElementById('foreignLogo').innerHTML = '<img src=\"../ddi46/images/stored_in_hv_198x23.jpg\" width=\"198\" height=\"23\" alt=\"HealthVault logo\"/>';
}

function healthVaultOpenPtRecord(medString)
{
	delSelection('drug','all','parser');
	var medAr = medString.split(",");
	for(i in medAr)
	{
		var dataPair = medAr[i];
		var smAr = dataPair.split("^");
		addToList(smAr[1],smAr[0]);		
	}
	medCheckWindow();
}

function hvData(a,b)
{
	this.ptDrugList = a;
	this.hvDataIn = b;	
}

*/
var sendingAr = [];
var hvSaveCancelled = false;

function sendHealthVaultMeds()
{
	alert('sendHealthVaultMeds 1');
	var ret3way = getSelQuiet('selectRecord');
	if(ret3way.value != 'HealthVaultPt')  // There is no Current Record.
	{
		alert('When you have a Microsoft HealthVault record open you cannot save other records.');
		return;
	}
	var cdH = document.getElementById('chosenList');
	var newAr = [];
	for(c=0;c<cdH.options.length;c++)  // Gets all current drugs list members as new
	{
		newAr[c] = true;
	}
	var sendingArIndex = 0;
	var drug;
	var found = false;
	if(ptDrugList == 'none')
		ptDrugList = '';
	alert('sendHealthVaultMeds 2');	
	for( i in ptDrugList)
	{
		var tempAr = ptDrugList[i].split('^');
		found = false;
		for(c=0;c<cdH.options.length;c++)
		{
			if(tempAr[1] == cdH.options[c].text)   // Is old drug name same as new; tries all new drugs
			{
				found = true;
				newAr[c] = false;  // Found; so its not new
			}
		}
		if(found == false)
		{
			var innerAr = [tempAr[1] , '2','']
			sendingAr[sendingArIndex] = innerAr; //[txt , 'started',''];
			sendingArIndex++;
		}
	}
	for( e in newAr)
	{
		if(newAr[e] == true) // Current list drug was not found in old list.
		{
			var txt = cdH.options[e].text;
			var innerAr = [txt , '1','']
			sendingAr[sendingArIndex] = innerAr; //[txt , 'started',''];
			sendingArIndex++;			
		}
	}
	alert('sendHealthVaultMeds 3');
	getDates();	
}

function getDates()
{
	if(hvSaveCancelled)
		return;
	var outString = 'item=';
	var sep = '';
	for(c in sendingAr)
	{
		if(sendingAr[c][2] == '')
		{
			getDateStopped(sendingAr[c][0],sendingAr[c][1]);  //sendingAr[c][0], sendingAr[c][1]);
			return;
		}
	}
	for(n in sendingAr)
	{
//		alert(sendingAr[n][2]);
		outString += sep + sendingAr[n][2] + '^' + sendingAr[n][1] + '^0^' + sendingAr[n][0];
//		alert('outstring==' + outString);
		sep = ',';
	}
	select_1(42,outString);
}

function getDateStopped(drugName,number)
{
	var date = '';
	var d = new Date();
	var month = d.getMonth() + 1;
	var yr = d.getFullYear();
	var today = month + '/' + d.getDate() + '/' + yr;
	var word = 'stopped';
	if(number == 1)
		word = 'started';
	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">When was the '+ drugName + ' ' + word + '?\
  </span></td>\
</tr><tr>\
<td>\
  <p>If necessary, please change the date that ' + drugName + ' was ' + word + '.<br>\
  </p>\
  <be>\
    Date (format: mm/dd/yyyy) \
    <input type="text" id="date" value="' + today + '">\
    <br>\
    <br>\
    <input type="submit" onClick="saveDate()" id="dateButton" value="Save">\
 </td>\
</tr></table>';
	document.getElementById("utilityDiv").className="showIt";
	document.getElementById("utilityDiv").innerHTML = text;
}

function saveDate()
{
	document.getElementById("utilityDiv").className="hideIt";
	var date = document.getElementById("date").value;
	var res = isValidDate(date);
	if(res == false)
	{
		return;
	}
	for(c in sendingAr)  //FROM WHERE????????????????????????????????????????????????????????????????????????
	{
		if(sendingAr[c][2] == '')
		{
			sendingAr[c][2] = date;
			break;
		}
	}
	getDates();	
}

function hvCancelButton()
{
	hvSaveCancelled = true;
	document.getElementById("utilityDiv").className="hideIt";	
}

function isValidDate(dateStr) 
{
	// Checks for the following valid date formats:
	// MM/DD/YY   MM/DD/YYYY   MM-DD-YY   MM-DD-YYYY
	// Also separates date into month, day, and year variables
	var month; // parse date into variables
	var day;
	var year;
	
	
	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;
	
	// To require a 4 digit year entry, use this line instead:
	// var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
	
	var matchArray = dateStr.match(datePat); // is the format ok?
	if (matchArray == null) {
	alert("Date is not in a valid format.")
	return false;
	}
	month = matchArray[1]; // parse date into variables
	day = matchArray[3];
	year = matchArray[4];
	if (month < 1 || month > 12) { // check month range
	alert("Month must be between 1 and 12.");
	return false;
	}
	if (day < 1 || day > 31) {
	alert("Day must be between 1 and 31.");
	return false;
	}
	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
	alert("Month "+month+" doesn't have 31 days!")
	return false
	}
	if (month == 2) { // check for february 29th
	var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
	if (day>29 || (day==29 && !isleap)) {
	alert("February " + year + " doesn't have " + day + " days!");
	return false;
	   }
	}
	var fin = month + '/' + day + '/' + year;
	return fin;  // date is valid
}


function medCheckWindow()
{
	document.getElementById("hvFrame").className="showIt";
}

function healthVaultMeds()
{
	healthVaultOpenPtRecord()
	toBox = document.getElementById("selectRecord");
	var len = toBox.options.length;
	toBox.options[len] = new Option(ptName,'HealthVaultPt');  // ptName is a global added to page
	toBox.options.selectedIndex = len;
//	alert('selected it');
	document.getElementById('foreignLogo').innerHTML = '<img src=\"' + serverAddress + 'images/microsoft/stored_in_hv_198x23.jpg\" width=\"198\" height=\"23\" alt=\"HealthVault logo\"/>';
}

function healthVaultOpenPtRecord()
{
//alert('in healthVaultOpenPtRecord');
	delSelection('drug','all','parser');
	if(ptDrugList == undefined || ptDrugList == 'none')
	{
		ptDrugList = '';
		return;
	}	
	for( i in ptDrugList)
	{
		oneDrug = ptDrugList[i];
		var smAr = oneDrug.split("^");
		addToList(smAr[1],smAr[0]);
	}
	medCheckWindow();
}


function healthVaultSaveAsMes()
{
	alert('This record is saved in Microsoft HealthVault. The name cannot be changed. You can use the Save function, however.');
}

function healthVaultNoDelete()
{
	alert('This record is stored in Microsoft HealthVault. To record that you are no longer taking any medications, delete each one individually and then save the empty record in order to update the HealthVault record.');
}

function healthVaultNewRec()
{
	alert('This record is stored in Microsoft HealthVault and it cannot be deleted. To record that you are no longer taking any medications, delete each one individually and then save the empty record in order to update the HealthVault record.');
}

function hvCalling()
{
	alert('HealthVAult called me!');
}


function selectHV(place)  // Menu in lists page
{
	var num = index.toString();
	var file;
	switch (num)  // Menu in drug selection page
	{
		case '9':
			var wo = serverAddress + "userManual.html";
			window.open(wo,"","");
			return;
		case '18':
			file = serverAddress + "privacy.html"; 
			break;
		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 '41':    // Go get HV info'
			//	file = "http://198.64.152.37:82/";
				window.open("http://198.64.152.37:82/","","");
			break;
		case '42':    // Go get HV info'
				file = "http://198.64.152.37:82/Store.aspx?" + param2;
				alert(file);
		//		window.open("http://198.64.152.37:82/Store.aspx","","");
			break;						
	}
	keyHandlerStatus = false;		
	if(num == '0'){
		makeVisible('drugLists');
	}
	else{
		makeVisible('largeFrame');
	}
	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['largeFrame'].document;
		docloc = iframeDoc.location;
		docloc0 = 1;
	}
	docloc.replace(file);	
}

function tourForHV()
{
	document.getElementById("loginDiv").className="hideIt";
	document.getElementById("logoutDiv").className="right";
	document.getElementById("logInText").innerHTML = '<br /><span class=\"grey\"><b>GUEST TAKING A TOUR</b></span>';
//	sessionNumber = getKeyValue('sessionNumber',resp);
	logInDone = true;
	guestUser = true;
	setupTourSub();
}