
//Global popup window handle;
var popup;
var popupName;

/* ------------------ Table sort functions--------------------------------------- */
  
// Regular expressions for normalizing white space.
var whtSpEnds = new RegExp("^\\s*|\\s*$", "g");
var whtSpMult = new RegExp("\\s\\s+", "g");


// This code is necessary for browsers that don't reflect the DOM
// constants (like IE).
if (document.ELEMENT_NODE == null) 
{
  document.ELEMENT_NODE = 1;
  document.TEXT_NODE = 3;
}
                
function normalizeString(s) {
        
  s = s.replace(whtSpMult, " ");  // Collapse any multiple whites space.
  s = s.replace(whtSpEnds, "");   // Remove leading or trailing white space.
                                          
  return s;
}

function getTextValue(el) 
{
  var i;
  var s;

  // Find and concatenate the values of all text nodes contained
  // within the element.
  s = "";
  for (i = 0; i < el.childNodes.length; i++)
    if (el.childNodes[i].nodeType == document.TEXT_NODE)
      s += el.childNodes[i].nodeValue;
    else if (el.childNodes[i].nodeType == document.ELEMENT_NODE &&
             el.childNodes[i].tagName == "BR")
      s += " ";
    else
      // Use recursion to get text within sub-elements.
      s += getTextValue(el.childNodes[i]);

  return normalizeString(s);
}

function compareValues(v1, v2) 
{
/* we don't need numeric comparison, so for speed this is commented out
        var f1, f2;
        If the values are numeric, convert them to floats.
        f1 = parseFloat(v1);
        f2 = parseFloat(v2);
        if (!isNaN(f1) && !isNaN(f2)) {
          v1 = f1;
          v2 = f2;
        }
*/
  // Compare the two values.
  if (v1 == v2)
    return 0;
  if (v1 > v2)
    return 1
  return -1;
}


/* Make the alternate row styles */
// Style class names.
//      var rowClsNm = "rowBeige";
// Regular expressions for setting class names.
//      var rowTest = new RegExp(rowClsNm, "gi");
function makePretty(tableElement) 
{
	//, col) {
  var i;
  var rowEl, cellEl;
  // Set style classes on each row to alternate their appearance.
  var count = 0;
  var len = tableElement.rows.length;
  for (i = 0; i < len; i++) 
  {
	  rowEl = tableElement.rows[i];
   	if (tableElement.rows[i].style.display != "none") // do only visible rows
   	{
      	count++;
         if (count % 2 != 0)
         	rowEl.className = "rowWhite";
         else
            rowEl.className = "rowShaded";
    }
  }
}

//-----------------------------------------------------------------------------
// sortTable(id, col, direction)
//
//  id  - ID of the TABLE, TBODY, THEAD or TFOOT element to be sorted.
//  col - Index of the column to sort, 0 = first column, 1 = second column,
//        etc.
//  direction - "descending" or "ascending"
//
//-----------------------------------------------------------------------------

function sortTable(id, col, direction) 
{
	var reverseMarker;
	if(direction == 'ascending')
	{
		reverseMarker = false;
	}
	else
	{
		reverseMarker = true;
	}
	
	
	// Get the table or table section to sort.
   var tableElement = document.getElementById(id);

   // The first time this function is called for a given table, set up an
   // array of reverse sort flags.
   if (tableElement.reverseSort == null) 
	{
   	tableElement.reverseSort = new Array();
      tableElement.lastColumn = 99; // Set to out of range
   }

	// If this column has not been sorted before, set the initial sort direction.
   if (tableElement.reverseSort[col] == null)
	{
           tableElement.reverseSort[col] = reverseMarker;
	}

   document.body.style.cursor = "wait";
	//Attach these variables to this window object so
	//we can find them in other functions that are called.
   window.top100_currTable = tableElement;
   window.top100_currCol = col;
	window.top100_currRev = reverseMarker;
   setTimeout( 'sortLoop()', 200)
}

function sortLoop()
{
	
	//Collect our variables from the window object for this sort
   var tableElement = window.top100_currTable;
	
	//Column to sort
   var col = window.top100_currCol;

	// Controls the sort direction and the sort marker image that is displayed.
	// If true, the current sort of the column will be reversed and the 
	// displayed image will be toggled (up to down or down to up)
   var revMarker = window.top100_currRev;
	
	// If this column was the last one sorted, reverse its sort direction.	
   if (tableElement.lastColumn !=null && col == tableElement.lastColumn) 
	{
		//Toggle the value for this column.
		revMarker = true;
      tableElement.reverseSort[col] =!tableElement.reverseSort[col];
		window.top100_currRev = revMarker;

   }

   var oldDsply = tableElement.style.display;
   tableElement.style.display = "none";
  
   // Sort the rows based on the content of the specified column
   var tmpEl;
   var sortArray = buildArray(tableElement, col);

   sortArray.sort(compare2);
	// Reverse the sort if true
   if (tableElement.reverseSort[col])
	{
       sortArray.reverse();
	}
   var nextSibling = tableElement.nextSibling;         
   var parent = tableElement.parentNode;
   parent.removeChild(tableElement);

   // insert in the new order
   var len = sortArray.length;
   for (var i = 0; i < len; i++) 
	{
      tableElement.appendChild(sortArray[i].element);
   }
   parent.insertBefore(tableElement, nextSibling);
   tableElement.lastColumn = col;         // Remember this column as the last one sorted.
   makePretty(tableElement);         // Re-do alternate row styling.
   setSortMarker(col, revMarker); // put sort mark on sorted column header
   tableElement.style.display = oldDsply;   // Restore the table's display style.
   document.body.style.cursor = "default";
   
	return false;
}

// create sort array
function buildArray (table, col) 
{
   var len = table.rows.length;
   var a = new Array(len);
   for (var i = 0; i < len; i++) 
	{
      var row = table.rows[i]; 
      var str;
      var c = row.cells[col];
      if (typeof c.innerText != "undefined")
		{
   	   str = c.innerText;
		}
      else
		{
         str = getInnerText(c);
		}
      a[i] = {value:str, element: row};
   };
   return a;
};

function getInnerText(oNode) 
{
	var s = "";
   var cs = oNode.childNodes;
   var l = cs.length;
   for (var i = 0; i < l; i++) 
	{
   	switch (cs[i].nodeType) 
		{
      	case 1: //ELEMENT_NODE
         	s += getInnerText(cs[i]);
            break;
         case 3: //TEXT_NODE
            s += cs[i].nodeValue;
            break;
       }
   }
        return s;
};

// sort comparator
function compare2(v1, v2)
{
  if (v1.value == v2.value)
    return 0;
  if (v1.value > v2.value)
    return 1
  return -1;
}

function setSortMarker(col, revMarker)
{
   var markers = new Array("col1SortMarker", "col2SortMarker",
      "col3SortMarker", "col4SortMarker","col5SortMarker", "col6SortMarker", "col7SortMarker");

      
   // turn off all sort markers except then one in column 'col'
   for (var ii = 0; ii < 7; ii++) 
	{
      var elem = document.getElementById(markers[ii]);
      if (elem != null) 
		{
         if (ii == col) 
			{
            elem.style.display = "inline";
				//Toggle the marker if true
         	if (revMarker)
				{
               reverseMarker(elem)
				}
         }
         else 
			{        
            elem.style.display = "none";
         }
      }
   }
}

//This will toggle the image marker specifed in the src value of the element.
// Arrow Up and Down values are used here.
function reverseMarker(elem)
{
 	var imgsrc = elem.src;
   var index = imgsrc.indexOf("arrow_sort_up");
   if (index >= 0)
	{
   	imgsrc = imgsrc.replace("arrow_sort_up", "arrow_sort_down");
	}
   else 
	{
   	index = imgsrc.indexOf("arrow_sort_down");
     	if (index >= 0)
		{
        	imgsrc = imgsrc.replace("arrow_sort_down", "arrow_sort_up");
		}
   }
   elem.src = imgsrc;
}

/* ------------------ End of Table sort functions--------------------------------------- */

// Submits the form based on the state selected from the Map
// Current Sort column and Sort direction are also sent in 
// order to preserve the values for the next page.
function performSubmitForMap(state)
{
	state = state.toUpperCase();
   document.reportSearch.StateCode.value = state;
	// If the table has been sorted at least once, then
	// window.top100_currTable will be defined
	if(window.top100_currTable)
	{
		document.reportSearch.LastSortColumn.value = window.top100_currCol;
		if(window.top100_currRev)
		{
			document.reportSearch.LastSortDirection.value = 'descending';
		}
		else
		{
			document.reportSearch.LastSortDirection.value = 'ascending';
		}
	}
	document.reportSearch.submit();
}

function performSubmit()
{
	if(document.reportSearch.StateCode.value !='')
	{
		document.reportSearch.submit();
	}
}


function doTableSortOnLoad()
{
	//Default values to be used if not supplied
	var column = 0;
	var direction = 'ascending';
	
	//Look for values on the page.  This will retain the previous sort
	//order and column selection
	var lastSortColumn = window.document.getElementById("LastSortColumn");
	if(lastSortColumn)
	{
		column = lastSortColumn.value;
	}
	var lastSortDirection = window.document.getElementById("LastSortDirection");
	if(lastSortDirection)
	{
		direction = lastSortDirection.value;
	}
	
	var tableBodyId = window.document.getElementById("id_of_tablebody");
	if(tableBodyId)
	{
		sortTable("id_of_tablebody",column,direction);
	}
}

function doWinnerLogout()
{
	if(popup !=undefined)
	{
		popup.close();
	}
	window.location="/top100hospitals/librarian/PFActionId/pf.Logout";
	window.location="http://www.100tophospitals.com";	
}

function doAdminLogout()
{
	if(popup !=undefined)
	{
		popup.close();
	}
	window.location="/top100hospitals/librarian/PFActionId/pf.Logout";
}


function doClose()
{
	var browserName=navigator.appName;
	var ie7 = (document.all && !window.opera && window.XMLHttpRequest) ? true : false;  
  	if (ie7) 
   {
	    //This closes a window without any prompt for IE7
	    window.open('','_parent','');
	    window.close();
	}
  	else 
   {
		if(browserName=="Microsoft Internet Explorer")
		{
		    //This closes a window without any prompt for IE6
		    this.focus();
		    self.opener = this;
		    self.close();
		 }
		 else if(browserName=="Netscape")
		 {
		 	window.open('','_parent',''); 
			window.close();
		 }
		 else
		 {
		 	window.close();
			self.close();	
		 }
    }
}

function doPopupWindow(URL)
{
	//Create a name for the popup window that is unique to this domain name.
	//Replace any non alphanumeric characters with underscore
	var domain = window.document.domain;
	popupReg = RegExp("\\W", "gi");
	popupName = domain.replace(popupReg,"_") + "_ReportWindow";
	if(popup == undefined)
	{
			popup = window.open(URL, popupName, "scrollbars=yes,resizable=yes,toolbar=no,location=no");
	}
	else
	{
		popup.close();
		popup = window.open(URL, popupName, "scrollbars=yes,resizable=yes,toolbar=no,location=no");
	}

}


function warningMsg()
{
	var retValue;
	retValue = confirm("Do you really want to delete this user?");
	return retValue;
}

function warningMsgAllUserDelete()
{
	var retValue;
	retValue = confirm("Do you really want to delete all users from this group?");
	return retValue;
}

function warningMsgAllUserRemove()
{
	var retValue;
	retValue = confirm("Do you really want to remove all users from this study group?");
	return retValue;
}

function warningMsgGroupDelete()
{
	var retValue;
	retValue = confirm("Do you really want to delete this Study Group?");
	return retValue;
}