//THIS SCRIPT FILE MUST BE INCLUDED IN ALL IMEDICA PAGES.
//It parses <iMedica ... /> nodes.
//It initalizes the iMedica global variable. (which allows you to call C# External Handler code ie 'iMedica.Admin.CodeDescription(...)')

var iMedica = new Array();

try
{
    if (window.external != null)
    {
        window.external.newSession();

        processIMedicaTags();
        iMedicaInit();
    }
} catch (E) {
    //alert("Error encountered in iMedica.js while attempting to access window.external.newSession() (this will happen if we're not running inside the application): " + E.description  );
    // there is apparently a new timing issue which allows call to this AFTER we have removed it.
    // ignore and go on.
}
	

function processIMedicaTags()
{
	try {
		var iMedicaTags = document.all.tags("iMedica");
		for(var i = 0; i < iMedicaTags.length; i++) {
			if(iMedicaTags[i].External != null && iMedicaTags[i].External != "")
				window.external.requestType(iMedicaTags[i].External);
		}
	} catch(E) {
		alert("Error encountered in iMedica.js processIMedicaTags(): " + E.description  );
	}
}


function iMedicaInit()
{
	try {	
		var KeyEnumerator = window.external.getKeyEnumerator();
	
		var key = window.external.getNextKey(KeyEnumerator);
		while(key != null)
		{
			//FIXME: You can do this without eval i just dont remember how.
			//				The syntax is something like: iMedica[key] = window.external.iMedica(key);
			eval("iMedica." + key + " = window.external.getExternalHandler('" + key + "');");
			key = window.external.getNextKey(KeyEnumerator);
		}
		
		KeyEnumerator = null;
		
	} catch(E) {
		alert("Error encountered in iMedica.js iMedicaInit(): " + E.description  );
	}
}

function createMSXMLDOMObject()
{
	// While MSXML3 has a "replace" mode that allows a newer version of MSXML3 to be used
	// to substitute for MSXML2, future releases of MSXML will not allow that (per MSXML4 doc)
	// This code attempts to isolate future changes.
	return new ActiveXObject("MSXML2.DOMDocument.3.0");
}

// resizes the oDiv to display the page content correctly

var gContentAdjustment = 50;
function initDesktop(contentAdjustment)
{
	if (contentAdjustment != null)
		gContentAdjustment += contentAdjustment;
	change();
}

function change()
{
    //Bug 56444 - need to check check if the body has been loaded before attempting to check properties
    if ((document.body !== "undefined" && document.body !== null) && document.body.clientWidth > 1 && document.body.clientHeight > 1)
	{
		type = typeof oDiv;
		if (type!="undefined".valueOf())
		{
			var theheight = document.body.clientHeight - gContentAdjustment;
			if (theheight > 0)
				oDiv.style.height = theheight;
		}
	}
}

window.onresize=change;

var gsOriginalClass;
function EnableAlphaFilter(oControl)
{
	gsOriginalClass = oControl.className;
	oControl.className += " aFilter";
}

var gbContextMenuClick = false;
function DisableAlphaFilter(oControl)
{
	if (!gbContextMenuClick)
	{
		try
		{
			if (typeof(oControl) == "string")
				oControl = eval(oControl);
		}
		catch(e) 
		{}
				
		if (typeof(oControl) == "object")
			oControl.className = gsOriginalClass;
	}
}

  function GetMonth(intMonth){
    var MonthArray = new Array("January", "February", "March",
                               "April", "May", "June",
                               "July", "August", "September",
                               "October", "November", "December") 
    return MonthArray[intMonth] 	  	 
    }
    
  function getDateStr(){
    var today = new Date()
    var year = today.getYear()
    if(year<1000) year+=1900
    var todayStr = GetMonth(today.getMonth()) + " " + today.getDate()
    todayStr += ", " + year
    return todayStr
  }

  function getArgs() {
      var args = new Object();
      var query = location.search.substring(1);
      // Get query string
      var pairs = query.split("&");
      // Break at ampersand
      for (var i = 0; i < pairs.length; i++) {
          var pos = pairs[i].indexOf('=');
          // Look for "name=value"
          if (pos == -1) continue;
          // If not found, skip
          var argname = pairs[i].substring(0, pos);
          // Extract the name
          var value = pairs[i].substring(pos + 1);
          // Extract the value
          args[argname] = unescape(value);
          // Store as a property
          // In JavaScript 1.5, use decodeURIComponent(  ) 
          // instead of escape(  )
      }
      return args;     // Return the object
  }

  //Functions for CDS Webform tab in FNC....They all start with CDS....

  //Load negation reason values into each dropdownlist box  
  function CDSLoadNegationReasons(listBox) {
      //get the negation reason from PRM's ListNegationReason table
      var negationList = iMedica.FNC.GetNegationReasons();

      //initialize the listbox to a default of no value
      CDSAddDropDownOption(listBox, "", "None");
      for (var idx = 0; idx < negationList.length; idx++) {
          CDSAddDropDownOption(listBox, negationList[idx], negationList[idx]);
      }

      //since loading values for the first time, disable the dropdown list box. It will be enabled whenever an SP or SO checkox is set
      listBox.disabled = true;
  }

  //Add a single option to a dropdownlist box  
  function CDSAddDropDownOption(selectbox, text, value)
  {
      if (selectbox != null && selectbox.options != null) {
          var opt = selectbox.options;
          opt[opt.length] = new Option(text, value);
      }
  }  

  function CDSSetNegValue(dropdown, valueToSelect)
  {
      if (dropdown != null)
      {
          if (valueToSelect == null)
              dropdown.value = "None";
          else
              dropdown.value = valueToSelect;
      }
  }

  function CDSGetNegationReasonDropDown(elemName, visitProcedureUid)
  {
      if (visitProcedureUid)
      {
          //search for match on name then on visitprocedureuid. This protects against multiple duplicate procedure codes being used in FNC.
          var ddElemList = document.getElementsByName(elemName);
          if (ddElemList)
          {
              for (var idx = 0; idx < ddElemList.length; idx++)
              {
                 var attrib = ddElemList[idx].getAttribute('visitProcedureUid');
                 if (attrib && attrib == visitProcedureUid)
                    return ddElemList[idx];
              }
          }
      }
      else
      {
          //look up by name
          var dropDown = document.getElementById(elemName);
          return dropDown;
      }
      return null;
  }  

  function CDSServiceNegationReason(code, negationReason, visitProcedureUid)
  {
      //find the appropriate Neg_xxx dropdownlist box
      var dropDownElems = document.getElementsByName("NEG_" + code);
      if (dropDownElems)
      {
          //for safe measure, look for a matching visitprocedureuid attrib
          if (visitProcedureUid)
          {          
              for (var idx = 0; idx < dropDownElems.length; idx++)
              {
                  var attrib = dropDownElems[idx].getAttribute('visitProcedureUid');
                  if(attrib && attrib == visitProcedureUid)
                  {
                      CDSSetNegValue(dropDownElems[idx], negationReason);
                      return;
                  }
              }
          }
      }      
  }

  function CDSGetServiceCheckbox(visitProcedureUidStr)
  {
      var inputlist = document.getElementsByTagName("input");                
      for (var idx = 0; idx < inputlist.length; idx++)
      {
          //find the relative cbox based on the visitprocedureuid
          if (inputlist[idx].getAttribute('type') == 'checkbox')
          {
              var attrib = inputlist[idx].getAttribute('visitProcedureUid');
              if(attrib && attrib == visitProcedureUidStr)
              {
                  return inputlist[idx];
              }
          }
      }
      return null;
  }

//CDSAddService - Add a service
  function CDSAddService(code, isPerformed, negReason, visitProcedureUidStr)
  {
      var cbox;

      //find the checkbox
      if(isPerformed)
          cbox = CDSGetCheckbox("SP_" + code);
      else
          cbox = CDSGetCheckbox("SO_" + code);

      if (cbox)
      {
          cbox.checked = true;
          cbox.setAttribute('visitProcedureUid', visitProcedureUidStr);

          //set negation reason dropdown
          var dropDown = CDSGetNegationReasonDropDown("NEG_" + code, null);
          if (dropDown)
          {
              dropDown.setAttribute('visitProcedureUid', visitProcedureUidStr);
              dropDown.disabled = false;
          }
      }
  }

  //CDSRemoveService - Remove a service
  function CDSRemoveService(code, isPerformed, visitProcedureUidStr)
  {
      var cbox = CDSGetServiceCheckbox(visitProcedureUidStr);
      if(cbox)
      {
          cbox.checked = false;
          cbox.setAttribute('visitProcedureUid', "");

          //reset negation reason
          var dropDown = CDSGetNegationReasonDropDown("NEG_" + code, visitProcedureUidStr);
          if (dropDown)
          {
              CDSSetNegValue(dropDown, null);
              dropDown.setAttribute('visitProcedureUid', "");
              dropDown.disabled = true;
          }
      }
  }

  //Called from CDS webform when user clicks on SP/SO checkbox   
  function CDSServiceClick(cbox, code, isPerformed)
  {
      var sp_cbox;
      var so_cbox;
      var dropDown;
      var newvisitProcedureUidStr;
      var existingVisitProcedureUidAttrib;

      //An SP or SO checkbox has been clicked. The following steps are to be followed:
      //1. Click SP to set checkbox- Call FNC to create a visitprocedure as isperformed, set the vpuid on the checkbox as an attribute
      //2. Click SP to reset checkbox - Call FNC to remove the SP visitprocedure. If user declines to remove the service, keep the checkbox set.
      //3. Click SO to set checkbox- If SP is already checked, ignore the click & reset the checkbox. If SP is not already set, call FNC to create a visitprocedure as isperformed = false, set the vpuid on the checkbox as an attribute
      //4. Click SO to reset checkbox - Call FNC to remove the SO visitprocedure. If user declines to remove the service, keep the checkbox set.

      //get references to both checkboxes on the same row
      sp_cbox = CDSGetCheckbox("SP_" + code);
      so_cbox = CDSGetCheckbox("SO_" + code);

      //get existing visitprocedureuid on the element
      existingVisitProcedureUidAttrib = cbox.getAttribute('visitProcedureUid');

      //handle the checked state
      if (cbox.checked)
      {
          if (!isPerformed && sp_cbox.checked) {
              //SO checkbox
              cbox.checked = false;
              return; //nothing more to do 
          }
          else
          if (isPerformed && so_cbox.checked)
          {
              //SO is currently checked & user has just checked the SP checkbox. Need to first remove the SO.
              var so_visitProcedureUid = so_cbox.getAttribute('visitProcedureUid');
              if (so_visitProcedureUid)
              {
                  removed = iMedica.FNC.RemoveService(so_visitProcedureUid);
                  if (!removed)
                  {
                      //user changed mind to remove so reset the SP checkbox
                      cbox.checked = false;
                      return;
                  }
                  else {
                      //SO was removed so reset the associated dropdown
                      so_cbox.checked = false;
                      dropDown = CDSGetNegationReasonDropDown("NEG_" + code, so_visitProcedureUid);
                      if (dropDown) {
                          CDSSetNegValue(dropDown, null);
                          dropDown.setAttribute('visitProcedureUid', "");
                      }
                      so_cbox.setAttribute('visitProcedureUid', "");
                  }
              }
          }
          newvisitProcedureUidStr = iMedica.FNC.AddService(code, isPerformed);
      }
      else {
          //remove a service  - do not need to explicitly know if it is an SP or SO
          var removed = false;
          if (existingVisitProcedureUidAttrib && existingVisitProcedureUidAttrib != "")
              removed = iMedica.FNC.RemoveService(existingVisitProcedureUidAttrib);
          if (!removed) {
              //user declined the removal so keep the checkbox set
              cbox.checked = true;
              return;
          }
      }

      if (newvisitProcedureUidStr && newvisitProcedureUidStr != "")
      {
          //a checkbox is being set (new SP or SO is being added)

          //set the visitprocedureuid on the associated checkbox & dropdown list box
          cbox.setAttribute('visitProcedureUid', newvisitProcedureUidStr);
          dropDown = CDSGetNegationReasonDropDown("NEG_" + code, null);
          if (dropDown)
          {
              dropDown.setAttribute('visitProcedureUid', newvisitProcedureUidStr);
              dropDown.disabled = false;
          }
      }
      else {
          //a checkbox is being reset (remove SP/SO)

          //reset the visitprocedureuid on the associated checkbox & dropdown list box
          dropDown = CDSGetNegationReasonDropDown("NEG_" + code, existingVisitProcedureUidAttrib);
          if (dropDown) {
              CDSSetNegValue(dropDown, null);
              dropDown.setAttribute('visitProcedureUid', "");
              dropDown.disabled = true;
          }
          cbox.setAttribute('visitProcedureUid', "");
      }
  }

  function CDSGetCheckbox(elemId)
  {
      var element = document.getElementById(elemId);
      return element;
  }

  //Called from CDS webform when negation dropdown box is changed  
  function CDSNegationOnSelectionChange(select, pCode)
  {
      var selectedOption = select.options[select.selectedIndex];
      var attribValue = select.getAttribute('visitProcedureUid');
      if (selectedOption.value == "None")
          iMedica.FNC.SetNegation(attribValue, null);
      else
          iMedica.FNC.SetNegation(attribValue, selectedOption.value);      
  }  

  //Loads the current visit's procedures. Makes a call to FNC to get the current SP & SO procedures into the web page.
  function CDSLoadVisitProcedures()
  {
      var procedureUid;
      var inputlist = document.getElementsByTagName("input");                
      for (var idx = 0; idx < inputlist.length; idx++)
      {
          //get all checkbox controls on the web page
          if ( inputlist[idx].getAttribute("type") == 'checkbox' ) 
          {
              //get checkbox name. e.g. The name is of the form 'SP_9920' for a checkbox in the SP column on the webform. The SP prefix indicates it is an SP checkbox. For an SO checkbox it would be named
              //SO_99210. Determining the prefix in the name will make sure the procedure is handled correctly (looks at the "IsPerformed" flag) as an SP or SO.
              var checkboxname = inputlist[idx].getAttribute("name");

              //only want to get checkboxes that start with SP_ or SO_
              if(checkboxname.match(/SP_/gi) != null || checkboxname.match(/SO_/gi) != null)
              {
                  var serviceType = checkboxname.substring(0, 2);
                  var code = checkboxname.substring(3);
                  if(code.length > 0)
                  {
                      var isPerformed = false; //default is SO
                      if(serviceType == "SP")
                          isPerformed = true;

                      //For the current checkbox, check for the existence of its corresponding SP or SO in FNC. If exists, it will return the found VisitProcedureUid associated with the visitprocedure
                      //and the checkbox will be set. If the service procedure is not in FNC, the checkbox will be unchecked.
                      var visitProcedureUidStr = null;
                      visitProcedureUidStr = iMedica.FNC.VisitProcedureExists(isPerformed, code);

                      var negSelect = document.getElementById("NEG_" + code);

                      if (visitProcedureUidStr)
                      {
                        //set the checkbox (SP/SO) state
                        inputlist[idx].checked = true;
                        inputlist[idx].value = visitProcedureUidStr;
                        inputlist[idx].setAttribute('visitProcedureUid', visitProcedureUidStr);

                        //set the negation reason for the SP/SO
                        var negReason = iMedica.FNC.GetNegationReason(visitProcedureUidStr);
                        if (negSelect)
                        {
                            //enable the negation dropdown list box
                            negSelect.disabled = false;

                            //define an attribute to store the visitProcedureUid for the negation reason dropdownlist box so when a negation reason changes in FNC, we can look for the correct row on the web form & set it.
                            negSelect.setAttribute('visitProcedureUid', visitProcedureUidStr);
                            CDSSetNegValue(negSelect, negReason);
                        }                        
                      }                          
                      else
                      {
                        //there is no service match in FNC (service is not selected for the visit)
                        inputlist[idx].checked = false;
                        inputlist[idx].value = null;
                    }
                  }
              }
          }
      }                
  }