//******************************************************************************
//* Created By: Jack Liao                       
//* Created On: 7/15/2007                       
//* ---------------------------------------------------------------------------- 
//* Description:                                
//*    This is the main javascript library for  
//*    all Arbor Research web sites.            
//* ---------------------------------------------------------------------------- 
//* HISTORY (MM/DD/YYYY NAME: CHANGE DESCRIPTION)
//*   7/15/2009 Jack: Created initial sets of common functions that
//*                   is based on DOPPSLink application. 
//******************************************************************************


// Recursively find its parent with matching keyword using DOM
function findParentNode(obj, matchPart) {
	var re = new RegExp(matchPart);
	var parent = obj.parentNode;
	if (parent && parent != null) {
		if (!parent.id || parent.id == null)
			parent = findParentNode(parent, matchPart);
		else if (!re.test(parent.id))
			parent = findParentNode(parent, matchPart);
	}
	else 
		parent = obj;
	
	return parent;
}

// Put the cursor at the end of text in a textbox
function setCursorToEndOfText(tbid) {
    var textbox = document.getElementById(tbid);
    if(textbox != null && textbox.value.length > 0) {
        var fieldRange = textbox.createTextRange();
        fieldRange.moveStart('character', textbox.value.length);
        fieldRange.collapse();
        fieldRange.select();
    } else if(textbox != null) {
        // when textbox is empty, then just focus inside it
        textbox.focus();
    }
}

// gets the browser screen view area total width
function getBrowserScreenWidth() {
   if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    return window.innerWidth;
   } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    return document.documentElement.clientWidth;
   } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    return document.body.clientWidth;
   } else {
    return 0;
   }
}

// gets the browser screen view area total height
function getBrowserScreenHeight() {
   if( typeof(window.innerHeight) == 'number' ) {
    //Non-IE
    return window.innerHeight;
   } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    return document.documentElement.clientHeight;
   } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    return document.body.clientHeight;
   } else {
    return 0;
   }
}

// test if passed-in "obj" is an Array
function is_array(obj){
	return obj instanceof Array;
}

function is_in_array(arr, obj) {
    if(is_array(arr) && arr.length > 0) {
        for(var i=0; i<arr.length; i++) {
            if(arr[i] == obj) return true;
        }
    }
    return false;
}

// converts a boolean value to integer 1 or 0
// true --> 1, false --> 0
function ConvertBoolTo01(tf) {
    if(tf) {
        return 1;
    }
    return 0;
}

// clears all input elements inside a div
function clearDivContent(div_id) {
    var div = document.getElementById(div_id);
    if(div != null) {
        var inputs = div.getElementsByTagName("input");
        for(var i=0; i<inputs.length; i++) {
            if(inputs[i].type == "text") {
                inputs[i].value = "";
            }
            else if(inputs[i].type == "hidden") {
                inputs[i].value = "";
            }
        }
    }
}

// Show a popup on top of a gray layer
// the gray layer covers the whole page, so the user can't interact with the form until the popup is closed.
// the popup is at the center of the page
function showModalPopup(popup_id) {
    var div1 = document.getElementById("modalPtDiv");
    if(div1 == null) {
        div1 = document.createElement("DIV");
        div1.id = "modalPtDiv";
        div1.className = "transparentLayer";
        document.body.appendChild(div1);
    }
    
    var div2 = document.getElementById(popup_id);
    if(div2 != null) {
        div1.style.zIndex = 1000;
        div1.style.display = "block";
        div1.style.visibility = "visible";
        if(document.body.scrollHeight ) {
           div1.style.height = document.body.scrollHeight + "px";
        }
        div2.style.zIndex = div1.style.zIndex + 1;
        div2.style.position = "absolute";
        div2.style.display = "block";
        div2.style.visibility = "visible";
        // IMPORTANT: we always display div first, so that we can get its offsetWidth and offsetHeight
        var x = Math.floor((getBrowserScreenWidth() - div2.offsetWidth)/2);
        var y = Math.floor((getBrowserScreenHeight() - div2.offsetHeight)/2);
        if(x < 0) x = 0;
        if(y < 0) y = 0;
        div2.style.left = x + "px";
        div2.style.top = y + "px";   
    }
}

// Hide the popup and the gray layer.
function hideModalPopup(popup_id) {
    var div1 = document.getElementById("modalPtDiv");
    var div2 = document.getElementById(popup_id);
    if(div1 != null) {
      div1.style.display = "none";
      div1.style.visibility = "hidden";
    }
    if(div2 != null) {
      div2.style.display = "none";
      div2.style.visibility = "hidden";
    }	
}

// trim the leading and trailing character specified
 function trim(string, ch) {
    // leading
    while(string.charAt(0) == ch) {
        string = string.substring(1);
    }
    // trailing
    while(string.charAt(string.length-1) == ch) {
        string = string.substring(0, string.length - 1);
    }
    return string;
 }
 
 // test if a character is a digit
 function isDigit(c) {
    return ((c >= "0") && (c <= "9"))
 }

 // test if a string is integer
 function isInteger(s) {
    var i;
    for (i = 0; i < s.length; i++) {
	     var c = s.charAt(i);
         if (!isDigit(c)) return false;
    }
    return true;
 }
 
 // test if a string only contains alphabet [a-z]
 function isAlphabet(s) {
    var pattern = /^[A-Za-z]$/;
    for(var i=0; i<s.length; i++) {
        if(!s.charAt(i).match(pattern)) return false;
    }
    return true;
 }
 
 function IsValidDayForMonth(month, day, year) {
   var leapYear = new Array(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
   var regularYear = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
 
   var maxDays;
   if (IsLeapYear(year))
      maxDays = leapYear[month - 1];
   else
      maxDays = regularYear[month - 1];
    
   if(day > maxDays || day < 1)
      return false;
 
   return true;
 }
 
 function IsLeapYear(year)
 {
   return new Date(year,2-1,29).getDate() == 29;
 }
 
 
 // define an iframe for fixing the bug of select box appearing above the message div
 var popupIFrame = null;
   
 function createIFrame(iFrame_id) {
   var new_iframe = document.createElement("IFRAME");
   new_iframe.id = iFrame_id;
   new_iframe.style.filter = "alpha(opacity=0)";
   document.body.appendChild(new_iframe);
   return new_iframe;
 }

 function hideIFrame() {
   // destroy the iframe when hiding the div
   if(popupIFrame != null)
     document.body.removeChild(popupIFrame);
   popupIFrame = null;
 }
 
function showIFrame(div) {
  // create an iframe that has the same position and size as div, so that the 
  // div will be above the select box
  if(popupIFrame == null) {
  //		popupIFrame = document.createElement("IFRAME");
  //		popupIFrame.id = "floatIFrame";
    popupIFrame = createIFrame("floatIFrame");
    popupIFrame.style.zIndex=div.style.zIndex - 1;
    popupIFrame.style.position="absolute";
    popupIFrame.style.left = div.offsetLeft + "px";
    popupIFrame.style.top = div.offsetTop + "px";
    popupIFrame.style.width = div.offsetWidth + "px";
    popupIFrame.style.height = div.offsetHeight + "px";
  //		popupIFrame.style.filter = "alpha(opacity=0)";
  //		document.body.appendChild(popupIFrame);
  }
}

function convertStringToType(value, data_type) {
	if(value != null && value.length > 0) {
	  switch(data_type.toLowerCase()) {
			case "float":
				return parseFloat(localizeNumberToENUS(value));
				
			case "int":
				return parseInt(value);
				
			case "datetime":
				return new Date(value);
	  }
  }
  return null;
}

function localizeNumberToENUS(val) {
  // convert 1,43 to 1.43
  // since client side doesn't allow number group seperator, it is safe to just 
  // change "," to "."
  return val.replace(",", ".");
}

function set_dropdown_options(option_str, ddl) {
    if(ddl != null && option_str.length > 0) {
        //if(ddl.options.length > 0) {
            RemoveAllOptionsInDropDown(ddl);
        //}
                
        var options = option_str.split(';');
        for(var i=0; i<options.length; i++) {
            var vals = options[i].split('|');
            var opt = document.createElement("option");
            opt.text = vals[0];
            // vals[2] indicates if it is a N/A option
//            if(vals[2] == "0") {
                opt.value = vals[1];
//                opt.selected = true;
//            } else {
//                opt.value = "NA";
//            }
            ddl.options.add(opt);
        }
        //ddl.click();
//        RecordDropDownSelectedValue(ddl, $get("selectedDdlBatch"));
    }
}

function RemoveAllOptionsInDropDown(ddl) {
    if(ddl != null)
        while(ddl.options.length > 0)
            ddl.options.remove(ddl.options.length - 1);
}

// convert the special chars in vb format to its original ascii format
 function convertSpecialCharsFromVB(str) {
    str = str.replace(/Chr\(34\)/g, '"');
    str = str.replace(/Chr\(44\)/g, ",");
    str = str.replace(/Chr\(58\)/g, ":");
    str = str.replace(/Chr\(13\)/g, "\r");
    str = str.replace(/Chr\(10\)/g, "\n");
    return str
 }
 
 // convert the special chars in its original ascii format to vb format
 function convertSpecialCharsToVB(str) {
    str = str.replace(/\"/g, "Chr(34)");
    str = str.replace(/,/g, "Chr(44)");
    str = str.replace(/:/g, "Chr(58)");
    str = str.replace(/&/g, "Chr(38)");
    str = str.replace(/\|/g, "Chr(124)");
    return str
 }
 
 // Global Enum variable for error types
 var errorTypes = {None:0, Information:1, Warn:2, Error:3};
 
 function MessagePopup(msg, btn_text, error_type) {
    var div = document.getElementById("standard_msg_popup");
    if(div == null) { // if not exist, create one
        div = document.createElement("DIV");
        div.id = "standard_msg_popup";
        document.body.appendChild(div);
    }
    div.style.border = "solid 2px #003366";
    div.style.backgroundColor = "#ffffff";
    div.style.padding = "2px";
    div.style.maxWidth = "400px";
    if(btn_text == null || btn_text.length <= 0) btn_text = "Close";
    
    div.innerHTML = "<table><tr>" + GetImageHTMLString(error_type) + "<td>" + msg + "</td></tr></table>";
    div.innerHTML += "<br style='line-height:8px;'/><div style='text-align:center;'><a class='button' style='cursor:default;' onclick=\"hideModalPopup('" + div.id + "');\">" + btn_text + "</a></div><br/>";
    showModalPopup(div.id);
 }
 
 function ConfirmPopup(msg, btn_clicked, ok_btn_text, cancel_btn_text, error_type) {
//    var action = "";
//    if(event) action = event.srcElement.toString().replace("javascript:", "");
  
    var div = document.getElementById("custom_confirm_popup");
    if(div == null) { // if not exist, create one
        div = document.createElement("DIV");
        div.id = "custom_confirm_popup";
        document.body.appendChild(div);
    }
    div.style.border = "solid 2px #003366";
    div.style.backgroundColor = "#ffffff";
    div.style.padding = "8px";
    div.style.maxWidth = "300px";
    if(ok_btn_text == null || ok_btn_text.length <= 0) ok_btn_text = "Continue";
    if(cancel_btn_text == null || cancel_btn_text.length <= 0) cancel_btn_text = "Cancel";
    
    div.innerHTML = "<table><tr>" + GetImageHTMLString(error_type) + "<td>" + msg + "</td></tr></table>";
    div.innerHTML += "<br/><br/><div style='text-align:center;'><a class='button' style='cursor:default;' onclick=\"ClickButton('" + btn_clicked.id + "');\">&nbsp;&nbsp;" + ok_btn_text + "&nbsp;&nbsp;</a>&nbsp;<a class='button' style='cursor:default;' onclick=\"hideModalPopup('" + div.id + "');\">&nbsp;&nbsp;" + cancel_btn_text + "&nbsp;&nbsp;</a></div><br/>";
    showModalPopup(div.id);
    
    return false;  // always return false to block postback. The Continue button click will trigger the postback for the same event.
 }
 
 function ClickButton(id) {
    var button = document.getElementById(id);
    if(button != null) {
        var str = button.onclick.toString();
        // remove "return ConfirmPopup(...);"
        str = str.replace(/return ConfirmPopup\(.*\);/i, "");
        button.onclick = str;
        button.click();
    }
 }
 
 // To use this function, you need to have "images" folder at the root level,
 // and have 3 image files in it: alert.gif, info.gif and error_medium.gif
 function GetImageHTMLString(error_type) {
    var image_indicator = "";
    if(error_type != null) {
        if(error_type == 1) image_indicator = "<td valign='top'><img src='" + GetServerRootPath() + "/images/info.gif' /></td>";
        else if(error_type == 2) image_indicator = "<td valign='top'><img src='" + GetServerRootPath() + "/images/alert.gif' /></td>";
        else if(error_type == 3) image_indicator = "<td valign='top'><img src='" + GetServerRootPath() + "/images/error_medium.gif' /></td>";
    }
    return image_indicator;
 }
 
 // To use this function, create a HTML hidden field in the master page or banner user control
 // with id="hidden_server_path", and use the "Request.ApplicationPath" to set the hidden field value
 function GetServerRootPath() {
    var hidden = document.getElementById("hidden_server_path");
    if(hidden != null) {
        return hidden.value;
    }
    return "";
 }
 
 function getCurrentFocusedElementByEvent(e) {
    if(!e) e=event;
    return (e.target) ? e.target : e.srcElement;
 }
 
 function getTargetActionElementID(current_focused_id) {
    if(element_action_mapping != null && element_action_mapping.length>0 && current_focused_id != null) {
        for(var i=0; i<element_action_mapping.length; i++) {
            var map = element_action_mapping[i].split('|');
            var source = map[0];
            var target = map[1];
            if(source.toLowerCase() == current_focused_id.toLowerCase()) {
                return target;
            }
        }
    }
    return "";
}


//Declare bios here//
var title = "title";
var img = "img";
var blurb = "blurb";
var strBioTable = "<table width='350px'><tr><td style=background-color:#003366;><p style=color:White; font-size:14px;>" + title + "</p></td></tr><tr><td valign=top style=border: solid 1px lightgray;>";
strBioTable = strBioTable + "<table align=left cellpadding=0 cellspacing=0><tr><td>" + img + "</td>";
strBioTable = strBioTable + "<td width=10><table border=0 cellpadding=0 cellspacing=0><tr><td width=10></td></tr></table></td>";
strBioTable = strBioTable + "</tr><tr><td height=8px></td></tr></table><span style=font-weight: normal;>" + blurb + "</span></td></tr></table>";



//merion bio//
var strtitleBM = "Robert M. Merion, M.D.";
var strimgBM = "<img src=images/bobm_photo.jpg id=bobmphoto align=left />";
var strbobm = "Robert Merion, MD, is President of Arbor Research, Professor of Surgery at the University of Michigan (UM), and President of the American Society of Transplant Surgeons.  He serves as the clinical transplant director of the U.S. Department of Health and Human Services-funded <a href='http://www.ustransplant.org' target='_blank'>Scientific Registry of Transplant Recipients</a> and principal investigator of the National Institutes of Health-funded Adult to Adult Living Donor Liver Transplantation Study and the Renal and Lung Living Donors Evaluation Study. At UM, he directs the transplant fellowship training program. His previous positions at UM include chief of the Division of Transplantation and director of the Transplant Center.";

var strBM = strBioTable.replace(title, strtitleBM);
strBM = strBM.replace(img, strimgBM);
strBM = strBM.replace(blurb, strbobm);


//wolfe bio//
var strtitleBW = "Robert A. Wolfe, PhD";
var strimgBW = "<img src=images/wolfe_photo.jpg id=bobmphoto align=left />";
var strbobw = "Robert A. Wolfe, PhD, is Vice President of Arbor Research and a Professor Emeritus of biostatistics at the University of Michigan (UM) School of Public Health. He is principal investigator of the federally funded <a href='http://www.ustransplant.org' target='_blank'>Scientific Registry of Transplant Recipients</a> and the <a href='http://www.arborresearch.org/ESRD.aspx'>ESRD Measures project</a>. He also is co-investigator of the <a href='http://www.dopps.org' target='_blank'>Dialysis Outcomes and Practice Patterns Study</a> and deputy project director of the Clinical Outcomes of Live Organ Donors &ndash; Data Coordinating Center, funded by the National Institutes of Health (NIH). He was founder and director of the UM Kidney Epidemiology and Cost Center; co-PI and director of biostatistics for the NIH-funded United States Renal Data System (USRDS) from 1988 to 1997; and USRDS director from 1997 to 1999.";

var strBW = strBioTable.replace(title, strtitleBW);
strBW = strBW.replace(img, strimgBW);
strBW = strBW.replace(blurb, strbobw);

//Ramirez bio//
var strtitleSR = "Sylvia Ramirez, MD, MPH, MBA";
var strimgSR = "<img src=images/Bianca_Ramirez.jpg id=bobmphoto align=left />";
var strsilviar = "Sylvia P. B. Ramirez, MD, MPH, MBA, is Vice President of Global Research and Development at Arbor Research. She is a clinical nephrologist and a population epidemiologist with nearly 20 years of pediatric clinical care, nephrology, and transplant experience. She is principal investigator of the <a href='http://www.arborresearch.org/ESRD_DMDemo.aspx'>Evaluation of End-Stage Renal Disease Disease Management Demonstration</a> and the <a href='http://www.arborresearch.org/ESRD_DMDemo.aspx#Qip'>Quality Incentive Payment Demonstration</a> projects, and is co-investigator of <a href='http://www.arborresearch.org/esrd.aspx'>ESRD Measures Support Work</a>, all funded by the Centers for Medicare & Medicaid. She also is a co-investigator of the <a href='http://www.dopps.org' target='_blank'>Dialysis Outcomes and Practice Patterns Study</a>.  Her past accomplishments include developing, implementing and overseeing screening and educational programs for the National Kidney Foundation of Singapore.";

var strSR = strBioTable.replace(title, strtitleSR);
strSR = strSR.replace(img, strimgSR);
strSR = strSR.replace(blurb, strsilviar);


//robinson bio //
var strtitleBR = "Bruce Robinson, MD, MSCE";
var strimgBR = "<img src=images/Bruce_Robinson.JPG id=bobmphoto align=left />";
var strbruce = "Bruce M. Robinson, MD, MS, is Vice President of Clinical Research at Arbor Research and Adjunct Assistant Professor of Medicine at the University of Michigan. He has been principal investigator of the <a href='http://www.dopps.org' target='_blank'>Dialysis Outcomes and Practice Patterns Study<a> since 2009, and directed the launch of the study&acute;s current phase. He is co-director of the Centers for Medicare & Medicaid Services (CMS)-funded <a href='http://www.arborresearch.org/ESRD_DMDemo.aspx'>ESRD Measures Support Work</a>, and co-investigator of the CMS-funded <a href='http://www.arborresearch.org/ESRD_DMDemo.aspx'>Evaluation of ESRD Disease Management Demonstration</a> and the <a href='http://www.arborresearch.org/ESRD_DMDemo.aspx#Qip'>Quality Incentive Payment Demonstration</a> projects. He also contributes to the National Kidney Disease Surveillance Initiative and the Chronic Renal Insufficiency Cohort Study. Dr. Robinson is the past recipient of several National Institutes of Health career development awards.";

var strBR = strBioTable.replace(title, strtitleBR);
strBR = strBR.replace(img, strimgBR);
strBR = strBR.replace(blurb, strbruce);

//Dickinson bio//
var strtitleDD = "David Dickinson, MA";
var strimgDD = "<img src=images/David_Dickinson.JPG id=bobmphoto align=left />";
var strdavid = "David M. Dickinson, MA, is Vice President of Information and Operations at Arbor Research, where he started as director of information services and a senior research analyst in 1998. He has extensive experience in the design and use of analysis databases for economic and medical outcomes research. He coordinates the database design and electronic data collection functionality for the <a href='http://www.dopps.org' target='_blank'>Dialysis Outcomes and Practice Patterns Study</a>; oversees the adaptation of hundreds of gigabytes of operational transplant data into analysis files for the <a href='http://www.ustransplant.org' target='_blank'>Scientific Registry of Transplant Recipients</a>; and manages multiple research and administrative responsibilities. His work in econometrics and medical research includes positions with the Urban Institute and the University of Michigan.";

var strDD = strBioTable.replace(title, strtitleDD);
strDD = strDD.replace(img, strimgDD);
strDD = strDD.replace(blurb, strdavid);

//Port bio //
var strtitleFP = "Friedrich K. Port, MD, MS";
var strimgFP = "<img src=images/port_photo.jpg id=bobmphoto align=left />";
var strfritz = "Friedrich K. Port, MD, MS, FACP, is a Senior Research Scientist at Arbor Research, Emeritus Professor of Medicine (Nephrology) and Epidemiology at the University of Michigan Schools of Medicine and Public Health, and former President of Arbor Research.  He is, or has served as, principal investigator for the <a href='http://www.ustransplant.org' target='_blank'>Scientific Registry of Transplant Recipients</a>, the <a href='http://www.dopps.org' target='_blank'>Dialysis Outcomes and Practice Patterns Study</a> and several demonstration projects for the Centers for Medicare & Medicaid Services.  He served as deputy director of the National Institutes of Health-funded United States Renal Data System Coordinating Center from 1988 to 1999, and is the recipient of prestigious awards from the American Society of Nephrology (Scribner Award) and the National Kidney Foundation (Seldin Award). ";

var strFP = strBioTable.replace(title, strtitleFP);
strFP = strFP.replace(img, strimgFP);
strFP = strFP.replace(blurb, strfritz);

//Pisoni bio//
var strtitleRP = "Ron Pisoni, PhD, MS";
var strimgRP = "<img src=images/Ron_Pisoni.jpg id=bobmphoto align=left />";
var strron = "Ronald L. Pisoni, PhD, MS, is a Senior Research Scientist at Arbor Research, and Deputy Principal Investigator for the <a href='http://www.dopps.org' target='_blank'>Dialysis Outcomes and Practice Patterns Study</a> (DOPPS). He has held key roles in the DOPPS since its international expansion in 1997. He earned a PhD from Wayne State University in biochemistry in 1981, completed post-doctoral studies at the VA Outpatient Clinic, Boston/Harvard Medical School and the University of Michigan (UM), and an MS in Clinical Research Design and Statistical Analysis from the UM School of Public Health in 1997. Before joining Arbor Research, he served as an assistant research scientist faculty member in the Department of Pediatrics and the Department of Internal Medicine at UM from 1987-1997. ";

var strRP = strBioTable.replace(title, strtitleRP);
strRP = strRP.replace(img, strimgRP);
strRP = strRP.replace(blurb, strron);