function selfFocus(){
	self.focus();
}


function popUpContentWindow(url){
  // alert("error "+ url);
  var contentwin = window.open(url,"ErrorPage", "width=400,height=250,scrollbars=yes,menubars=no,toolbar=no,resizable=yes");
  contentwin.focus();
}

function popUpWhatIsSignaTrust(URL){
	var newwin = window.open("/usacontent/productservices/html/esig_whatIsSignaTrust.htm", "WhatIsSignaTrust", "height=543,width=617,location=no,scrollbars=yes,menubars=no,toolbar=no,resizable=yes,status=yes");
	newwin.focus();
}

function closeWindow(focusObject)
{
  focusObject.focus();
  window.close();
}




function openWindow(url)
{
//alert(url);
  //var productsamplesURL = 'index.jsp?menuItem=Request Product Samples'+document.forms['productForm'].product.value;
  if(url == "" || url == null)
  {
    alert("You must select a Product.");
  }
  else if(url.indexOf("http")>=0)
  {
    window.open(url);

  }
  else if(url.indexOf("/")>=0)
  {

    this.location=url;
  }
  else if(url.indexOf("|")>=0)
  {
    //alert(document.productForm.selectBy.value);
    var delimitIndex =url.indexOf("|");
    document.productForm.selectBy.value=url.substring(0,delimitIndex);
    document.productForm.menuItem.value=url.substring(delimitIndex+1);
    //alert('product ID from url   '+url.substring(0,delimitIndex));
    //alert('product ID  '+document.productForm.selectBy.value);
    //alert('menu item   '+document.productForm.menuItem.value);
    document.productForm.submit();
  }
  else
  {
    this.location=url;

  }

}

function printthis(URL){
  var hobo = window.open(URL, "MerckProductServicesCheckoutWindow", "width=756,height=550,resizable=yes,status=yes,scrollbars=yes,menubar=yes,toolbar=yes,location=no");
  hobo.focus();
}
function moveto(URL)
{
  this.location=URL;
  this.focus();
}
function locateErrorAddressField(field, value)
{
  field.value=value;
  field.focus();
}

function buildRedirectURl(q1,q2)
{
  var frmAction = document.forms['shippingform'].action + "?";
  var inpt_name;
  var inpt_value;
  //
  //alert(document.shippingform.q1.name);
  document.shippingform.q1.value = frmAction;
  for(i=0;i<document.forms['shippingform'].elements.length;i++)
  {
    inpt_name = document.forms['shippingform'].elements[i].name;
    if((inpt_name!=q1)&&(inpt_name!=q2)&&(inpt_name!='epi-process'))
    {
      inpt_value = document.forms['shippingform'].elements[i].value;
      document.shippingform.q1.value += inpt_name + "=" + inpt_value;
      if (document.forms['shippingform'].elements[i+1])
        document.shippingform.q1.value += "&";
    }
    if((inpt_name=='epi-content'))
    {
      document.forms['shippingform'].elements[i].value='REDIR_PROCESS';
      // alert(document.forms['shippingform'].elements[i].name);
    }
  }

  //alert(document.shippingform.q1.value);


  return false;
}


function fieldsetWidth(){
	var tableObj = document.getElementById("infoTable");
	//var newWidth = tableObj.offsetWidth+50;
	var newWidth = 367;
	document.getElementById("yourinfo").style.width = newWidth+"px";
}


// Shipping Info handling
function same_as_myinfo()
{

	var checkbox_status = document.forms[0].elements['same'].checked

	if ( !checkbox_status )
	{

		document.forms[0].elements['same'].checked = checkbox_status
		document.forms[0].elements['address1'].value = document.forms[0].elements['address1_shipping'].value
		document.forms[0].elements['address2'].value = document.forms[0].elements['address2_shipping'].value
		document.forms[0].elements['city'].value = document.forms[0].elements['city_shipping'].value
		document.forms[0].elements['state'].value = document.forms[0].elements['state_shipping'].value
		document.forms[0].elements['zip'].value = document.forms[0].elements['zip_shipping'].value

	}
	else
	{

		document.forms[0].elements['same'].checked = checkbox_status
		document.forms[0].elements['address1'].value = document.forms[0].elements['address1_myinfo'].value
		document.forms[0].elements['address2'].value = document.forms[0].elements['address2_myinfo'].value
		document.forms[0].elements['city'].value =
document.forms[0].elements['city_myinfo'].value
		document.forms[0].elements['state'].value =
document.forms[0].elements['state_myinfo'].value
		document.forms[0].elements['zip'].value =
document.forms[0].elements['zip_myinfo'].value

	}

}

// Regular expressions to validate data format
	var regExpText=/^[A-Za-z0-9 '-.#]{1,35}$/;
	var regExpZip=/^(?!00000)(?!99999)(\d{5})$/;
	var regExpFax=/^\(?([2-9])(\d{2})\)?[- .]?(\d{3})[- .]?(\d{4})$/;

	function validateField(strId, objRegExp, strError){
		var objField = document.getElementById(strId);
		var objErrorMsg = document.getElementById(strId+"Error");
		var objFieldRow = document.getElementById(strId+"Row");

		//alert(objField.id);
		if(objField.value.length<1){
			//alert(objField.id+"length less than 1");
			//alert(objErrorMsg.id);
			objErrorMsg.innerHTML=strError;
			//alert(objFieldRow.id);
			objFieldRow.className="row error";
			return true;
		}
		else{
			//alert(objField.id+"Regular Expression");
			if(!(objRegExp.test(objField.value))){
				objErrorMsg.innerHTML=strError;
				objFieldRow.className="row error";
				return true;
			}
			else{
				objFieldRow.className="row";
			}
		}
		return false;
	}



	function validateFields(hasSample){
		// If any of the fields are invalid indicate so by highlighted the "form box" and displaying a appropriate message.
		var bolAddress = validateField("address1", regExpText, "Please enter your Address.");
		var bolCity = validateField("city", regExpText, "Please enter your City.");
		var bolZip = validateField("zip", regExpZip, "Please enter a valid ZIP Code.");
		var bolState = validateField("state", regExpText, "Please choose your State.");
		if (hasSample)
		{
			var bolFax = validateField("fax", regExpFax, "Please enter a valid Fax number.");
		}

		var regExpPOBox = /^p(ost)?[ |\\.]*o(ffice)?[ |\\.]*(box)?[ a-z0-9]*\\d+/;
		var regExpPOBox2 = /^p(ost)?[ |\\.]*o(ffice)?[ |\\.]*(box)$/;
		var regExpPOBox3 = /^p(ost)?[ |\\.]*o(ffice)?[ |\\.]*$/;
		var regExpPOBox4 = /^p(ost)?[ |\\.]*o(ffice)?[ |\\.]*(box)?[ 0-9]*[^[a-z ]]*/;
		//var regExpPOBox3 = /^p(ost)?[ |\\.]*o(ffice)?[ |\\.]*$/;
		//var regExpPOBox3 = /P\.* *O\.* *B*O*X*/i;



		var sValue = document.getElementById("address1").value.toLowerCase();
		var sValue2 = document.getElementById("address2").value.toLowerCase();

		/*
			Validate Fields & PO Box

			if (validation fails) {
				Highlight fields/form
				Don't do POBox validation
			}
			else { // validation successful
				No highlights
				Do POBox validation
			}

		*/

		// if any of the fields is not valid -- No need to do POBox validation
		if (bolAddress || bolCity || bolZip || bolState || bolFax ){
			//alert("field validation failed");
			document.getElementById("userMessage").className="errorFound";
			document.getElementById("formBox").className="highlight";
			return false;

		}

		else{  // If all fields are valid -- PO Box testing should be done here.

			//alert("field validation successful");
			document.getElementById("userMessage").className="noError";
			document.getElementById("formBox").className="default";

			// Now check for POBox
			//alert("fields valid - checking for POBOX");

			if (regExpPOBox.test(sValue)){
				//alert("po box here");
				document.getElementById("address1Row").className="row error";
				document.getElementById("formBox").className="highlight";
				document.getElementById("poBoxMessage").style.color="red";
				return false;
			}
			else if (regExpPOBox2.test(sValue)){
				//alert("po box here");
				document.getElementById("address1Row").className="row error";
				document.getElementById("formBox").className="highlight";
				document.getElementById("poBoxMessage").style.color="red";
				return false;
			}
			else if (regExpPOBox3.test(sValue)){
				//alert("po box here");
				document.getElementById("address1Row").className="row error";
				document.getElementById("formBox").className="highlight";
				document.getElementById("poBoxMessage").style.color="red";
				return false;
			}
			else if (regExpPOBox4.test(sValue)){
				//alert("po box here");
				document.getElementById("address1Row").className="row error";
				document.getElementById("formBox").className="highlight";
				document.getElementById("poBoxMessage").style.color="red";
				return false;
			}
			else if (regExpPOBox.test(sValue2)){
			//if (regExpPOBox.test(sValue2)){
				//alert("po box here");
				document.getElementById("address2").className="highlight";
				document.getElementById("address2Row").className="row error";
				document.getElementById("formBox").className="highlight";
				document.getElementById("poBoxMessage").style.color="red";
				return false;
			}
			else if (regExpPOBox2.test(sValue2)){
				//alert("po box here");
				document.getElementById("address2").className="highlight";
				document.getElementById("address2Row").className="row error";
				document.getElementById("formBox").className="highlight";
				document.getElementById("poBoxMessage").style.color="red";
				return false;
			}
			else if (regExpPOBox3.test(sValue2)){
				//alert("po box here");
				document.getElementById("address2").className="highlight";
				document.getElementById("address2Row").className="row error";
				document.getElementById("formBox").className="highlight";
				document.getElementById("poBoxMessage").style.color="red";
				return false;
			}
			else if (regExpPOBox4.test(sValue2)){
				//alert("po box here");
				document.getElementById("address2").className="highlight";
				document.getElementById("address2Row").className="row error";
				document.getElementById("formBox").className="highlight";
				document.getElementById("poBoxMessage").style.color="red";
				return false;
			}
			else {
				document.getElementById("poBoxMessage").style.color="#868686";
				document.getElementById("address2Row").className="";
				document.getElementById("address2").className="";
			}

		}

		disableForm(document.getElementById("shippingInfoForm"));
		//alert("form + PO - All Valid");
		return true;
	}

	function disableForm(theform){
		for (i = 0; i < theform.length; i++){
			var tempobj = theform.elements[i];
			if (tempobj.type.toLowerCase() == "submit")
			tempobj.disabled = true;
		}
	}


/**********************************************************************************
 *  Toggle visibility of divs by ID
 *********************************************************************************/
function toggle(toggleID)
{
	eID = document.getElementById(toggleID);
	if (eID.style.display == 'none') {
		eID.style.display = 'block';
	} else {
		eID.style.display = 'none';
	}
}

/**********************************************************************************
 *  Resize Sample Request Form Overlay
 *********************************************************************************/
function resizeRequestSampleForm() {
	var totalHeight;
	if (window.innerHeight) {
		totalHeight = window.innerHeight;
	}
	else {
		totalHeight = document.body.clientHeight;
	}
	document.getElementById('srf-screen').style.height = totalHeight - 105 + "px";
	document.getElementById('srf-frame').style.height = totalHeight - 147 + "px";
}

// Check for popup blocked - on Requests Confirmed page
	function IsPopupBlocker()
     {
	 	//insert name of actual window in this test
		var oWin = window.open("","testpopupblocker","width=100,height=50,top=0,left=0");

		if (oWin==null || typeof(oWin)=="undefined"){

			document.getElementById("popupBad").className="popupMessageBad";
			document.getElementById("popupGood").className="hidden";
			document.title = "Request Submission Error";
			return false;
		}
		else{
			document.getElementById("popupGood").className="popupMessageGood";
			document.getElementById("popupBad").className="hidden";
			oWin.close();
		}

		return false;

     }

	 // Check to see if user has Adobe 7 installed and show error if it is
	 function AcroPluginCheck() {
		if(Pdf1.GetVersions().indexOf("7.0") != 1)
		document.getElementById("pluginCheck").className="pluginMissing";
    	//alert("Acrobat 7 not Found")
	}


	/*if success = true
		loads URL in parent window and close this window
	else
		Load URL in the same window */
	function targetParent(success, URL)
	{
		if(success == true) {
			if (! (window.focus && window.opener) ) return true;
			window.opener.focus();
			window.opener.location.href=URL;
			window.close();
		}
		else {
			window.location.href=URL;
		}
		return false;
	}


// TRIM function
		function Trim(s)
		{
		// Remove leading spaces and carriage returns
		while ((s.substring(0,1) == ' ') || (s.substring(0,1) == '\n') || (s.substring(0,1) == '\r'))
		{ s = s.substring(1,s.length); }

		// Remove trailing spaces and carriage returns
		while ((s.substring(s.length-1,s.length) == ' ') || (s.substring(s.length-1,s.length) == '\n') || (s.substring(s.length-1,s.length) == '\r'))
		{ s = s.substring(0,s.length-1); }

		return s;
		}


//Material Catalog validation
		function UpdateQuantity(formName, maxQuantity, totQtyAllowed, myCurrentItems, prevQty){
		//alert(formName);
		var maxQty = document.getElementById("maxQty");
		var myItemsCurrent = document.getElementById("myItemsCurrent");
		var totalQtyAllowed = document.getElementById("totalQtyAllowed");

		var objField = document.getElementById(formName+"qty");
		var objFieldRow = document.getElementById(formName+"edMtlRow");
		var objFieldInput = document.getElementById(formName+"edMatlInput");
		//alert("test");
		//alert("object field" + objField);
		//alert("New amount entered= " + objField.value);

		var trimFieldValue

		if (objField != null){
			trimFieldValue = Trim(objField.value);
			//objField = "1";
		}
		else {
			trimFieldValue = "1";
		}


		//alert("new object field" + trimFieldValue);

		//var trimFieldValue = Trim(objField.value);
		//objField.value=trimFieldValue;

		var adjustedTotal = parseInt(myCurrentItems)-parseInt(prevQty);
		var currentTotalItems = parseInt(trimFieldValue)+parseInt(adjustedTotal) ;
		//alert("Previous amount= " + prevQty);
		//alert("New amount entered= " + objField.value);
		//alert("Adjusted total before New Amount= " + adjustedTotal);
		//alert("New total= " + currentTotalItems);

		if (parseInt(currentTotalItems)>parseInt(totQtyAllowed)){
				alert("Adding "+currentTotalItems+" items to \"My Items\" would bring the total to over 14, the maximum number of items per single request. \n You may request fewer of this item, or submit your items now and request this item later.");
				document.getElementById(formName+"qty").value = 1;
				return false;
		}

		else if((parseInt(trimFieldValue)<1) || (parseInt(trimFieldValue)>parseInt(maxQuantity)) || (isNaN(trimFieldValue)) || (trimFieldValue=="")){
		//else if((parseInt(objField.value)<1) || (parseInt(objField.value)>parseInt(maxQuantity)) || (isNaN(objField.value))){
			document.getElementById(formName+"formBox").className="EdMtlhighlight";
			objFieldRow.className="boldError";
			objFieldInput.className="error";
			return false;
		}else{
				//document.formName.submit();
				return true;
		}

	}


// FInalize Requests pop up
function openThis(URL){
     openWin = window.open(URL, "openWindow", "width=756,height=550,resizable=yes,status=yes,scrollbars=yes,menubar=yes,toolbar=yes,location=no");
  openWin.focus();
  return false;
}

//var page_submitted = false;

	//function openThis(URL){
	//if (page_submitted)
	//{
		//alert ( "Your request has already been submitted. Please wait..." );
    	//return false;
	//}
	//else
	//{
    	//openWin = window.open(URL, "MerckProductServicesCheckoutWindow", "width=756,height=550,resizable=yes,status=yes,scrollbars=yes,menubar=yes,toolbar=yes,location=no");
  		//page_submitted = true;
		//openWin.focus();
  		//return false;
	//}
//}


//Review Items validation
		function UpdateQty(formName, maxQuantity, totQtyAllowed, myCurrentItems, dbValue){

		var objField = document.getElementById(formName+"qty");
		var tempObjField = document.getElementById(formName+"qty");
		var objFieldRow = document.getElementById(formName+"edMtlRow");
		var objFieldInput = document.getElementById(formName+"edMatlInput");
		var adjustedTotal = parseInt(myCurrentItems)-parseInt(dbValue);
		var currentTotalItems = parseInt(objField.value)+parseInt(adjustedTotal) ;
		var trimFieldValue = Trim(objField.value);
		objField.value=trimFieldValue;


		//alert("Previous amount= " + dbValue);
		//alert("New amount entered= " + objField.value);
		//alert("Adjusted total before New Amount= " + adjustedTotal);
		//alert("New total= " + currentTotalItems);

		if (parseInt(currentTotalItems)>parseInt(totQtyAllowed)){
				alert("Adding "+currentTotalItems+" items to \"My Items\" would bring the total to over 14, the maximum number of items per single request. \n You may request fewer of this item, or submit your items now and request this item later.");
				document.getElementById(formName+"qty").value =dbValue;
				return false;
		}

		else if((parseInt(objField.value)<1) || (parseInt(objField.value)>parseInt(maxQuantity)) || (isNaN(objField.value)) || (trimFieldValue=="")){
			//document.getElementById(formName+"formBox").className="EdMtlhighlight";
			objFieldRow.className="boldError";
			objFieldInput.className="error";
			return false;
		}else{
				return true;
		}

	}

// ShippingInfo my info / shipping info comparison
//function shippingInfoCompare() {
//var myInfo = new Array("<%=regAddress.getAddress1()%>", "<%=regAddress.getAddress2()%>", "<%=regAddress.getCity()%>", "<%=regAddress.getState()%>", "<%=regAddress.getZip()%>");

//var shipping = new Array("<%=address.getAddress1()%>", "<%=address.getAddress2()%>", "<%=address.getCity()%>", "<%=address.getState()%>", "<%=address.getZip()%>");

//var thing = document.form.address1;

//if (myInfo[0] == shipping[0] && myInfo[1] == shipping[1] && myInfo[2] == shipping[2] && myInfo[3] == shipping[3] && myInfo[4] == shipping[4]){
	//alert("same");
	//document.all.same.checked=true;
	//alert("shipping identical");
	//}
//else{
	//alert("different");
	//document.all.same.checked=false;
	//alert("shipping different");
	//alert(shipping[0]);
//}



//}


// Acrobat version check

function acrobatCheck(){
/*******************************************************
ADOBE ACROBAT DETECT (INTERNET EXPLORER)
*******************************************************/

//Script type required to validate
var displayString;


var acrobat=new Object();
var versionNumber=new Number(acrobat.version);

acrobat.installed=false;
acrobat.version='0.0';

if (navigator.plugins && navigator.plugins.length) {
	for (x=0; x<navigator.plugins.length;x++) {
		if (navigator.plugins[x].description.indexOf('Adobe Acrobat')!= -1)
		{
		acrobat.version=parseFloat(navigator.plugins[x].description.split('Version ')[1]);

			if (acrobat.version.toString().length == 1) acrobat.version+='.0';

				acrobat.installed=true;
				versionNumber=acrobat.version.value;
				displayString = 'Acrobat Version: '+acrobat.version+versionNumber;
				break;
		}
}
}

else if (window.ActiveXObject)
{
for (x=2; x<10; x++)
{
try
{
oAcro=eval("new ActiveXObject('PDF.PdfCtrl."+x+"');");
if (oAcro)
{
acrobat.installed=true;

acrobat.version=x+'.0';
//var versionNumber=new Number(acrobat.version);
displayString = 'Acrobat Version: '+acrobat.version+versionNumber;
}
}
catch(e) {}
}

try
{
oAcro4=new ActiveXObject('PDF.PdfCtrl.1');
if (oAcro4)
{
acrobat.installed=true;
acrobat.version='4.0';
//var versionNumber=new Number(acrobat.version);
displayString = 'Acrobat Version: '+acrobat.version;
}
}
catch(e) {}

try
{
oAcro7=new ActiveXObject('AcroPDF.PDF.1');
if (oAcro7)
{
acrobat.installed=true;
acrobat.version='7.0';
//var versionNumber=new Number(acrobat.version);
displayString = 'Acrobat Version: '+acrobat.version;
}
}
catch(e) {}

}

// Always do SOMETHING in case it goes wrong
var versionNumber=new Number(acrobat.version);

if (! displayString) { displayString = 'Acrobat Installed: Information Not Available'; }



if (isNaN(versionNumber) || versionNumber<7.0)
	{
	//alert("vsn number " + versionNumber);
	//alert(displayString);
	//alert("NOT adobe 7");
	document.getElementById("pluginCheck").className="pluginMissing";
	}
//alert("vsn number " + versionNumber);
//alert(displayString);
//document.getElementById("pluginCheck").className="pluginMissing";

// this alert is just to test if document.write doesn't work
//alert(displayString);
//alert(versionNumber);
}


// Acrobat Check for Finalize Request page - hides the ESig Submit Online button

function acrobatFinalizeRequestCheck(){
/*******************************************************
ADOBE ACROBAT DETECT (INTERNET EXPLORER)
*******************************************************/

//Script type required to validate
var displayString;


var acrobat=new Object();
var versionNumber=new Number(acrobat.version);

acrobat.installed=false;
acrobat.version='0.0';

if (navigator.plugins && navigator.plugins.length) {
	for (x=0; x<navigator.plugins.length;x++) {
		if (navigator.plugins[x].description.indexOf('Adobe Acrobat')!= -1)
		{
		acrobat.version=parseFloat(navigator.plugins[x].description.split('Version ')[1]);

			if (acrobat.version.toString().length == 1) acrobat.version+='.0';

				acrobat.installed=true;
				versionNumber=acrobat.version.value;
				displayString = 'Acrobat Version: '+acrobat.version+versionNumber;
				break;
		}
}
}

else if (window.ActiveXObject)
{
for (x=2; x<10; x++)
{
try
{
oAcro=eval("new ActiveXObject('PDF.PdfCtrl."+x+"');");
if (oAcro)
{
acrobat.installed=true;

acrobat.version=x+'.0';
//var versionNumber=new Number(acrobat.version);
displayString = 'Acrobat Version: '+acrobat.version+versionNumber;
}
}
catch(e) {}
}

try
{
oAcro4=new ActiveXObject('PDF.PdfCtrl.1');
if (oAcro4)
{
acrobat.installed=true;
acrobat.version='4.0';
//var versionNumber=new Number(acrobat.version);
displayString = 'Acrobat Version: '+acrobat.version;
}
}
catch(e) {}

try
{
oAcro7=new ActiveXObject('AcroPDF.PDF.1');
if (oAcro7)
{
acrobat.installed=true;
acrobat.version='7.0';
//var versionNumber=new Number(acrobat.version);
displayString = 'Acrobat Version: '+acrobat.version;
}
}
catch(e) {}

}

// Always do SOMETHING in case it goes wrong
var versionNumber=new Number(acrobat.version);

if (! displayString) { displayString = 'Acrobat Installed: Information Not Available'; }



if (isNaN(versionNumber) || versionNumber<7.0)
	{
	//alert("vsn number " + versionNumber);
	//alert(displayString);
	//alert("NOT adobe 7");
	document.getElementById("pluginCheck").className="pluginMissing";
	//document.getElementById("submitOnlineFinalizeRequests").className="hidden";
	//document.getElementById("submitOnlineFinalizeRequests2").className="hidden";
	}
//alert("vsn number " + versionNumber);
//alert(displayString);
//document.getElementById("pluginCheck").className="pluginMissing";

// this alert is just to test if document.write doesn't work
//alert(displayString);
//alert(versionNumber);
}

// Fuction  Prevent double click on shopping cart pages

function check_submit(validate) {

	if (submitted == true) {
		return false;
	}
	else {
	// everything is ok check the fields, ie using if (document.... .lenght == 0) alert...
	submitted = true ;
		if(validate==true){
			validateFields();
		}
		else{
			return true;
		}

	}
}

//Shopping Cart Release 30 Product Flyout
function scpfOver(divid) {
	document.getElementById(divid).style.backgroundImage="url('/usacontent/productservices/images/rolloverControl.gif')";
	document.getElementById(divid+"img").src="/usacontent/productservices/images/arrowDown.gif";
	//document.getElementById(divid).style.fontWeight="bold";
}

function scpfOut(divid) {
	document.getElementById(divid).style.backgroundImage="url('/usacontent/productservices/images/regularControl.gif')";
	document.getElementById(divid+"img").src="/usacontent/productservices/images/arrowRight.gif";
	//document.getElementById(divid).style.fontWeight="normal";
}

//Swap ShoppingCartProductFlyout Div

function scpfSwapDIV(url,target) {
    // native XMLHttpRequest object
    document.getElementById(target).innerHTML = 'loading...';
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        req.onreadystatechange = function() {scpfSwapDIVDone(target);};
        req.open("GET", url, true);
        req.send(null);
    // IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = function() {scpfSwapDIVDone(target);};
            req.open("GET", url, true);
            req.send();
        }
    }
}

function scpfSwapDIVDone(target) {
    // only if req is "loaded"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            results = req.responseText;
            if (results.indexOf("ERRORSTO", 0) != -1 || results.indexOf("authorized to view", 0) != -1  )
			            {
			            	scpswapDIVForSession("/portal/site/merckproductservices/?front_door=true&epi-content=ERRORSTO", "gridcontent")
						}
						else
						{
							document.getElementById(target).innerHTML = results;
						}
			        } else {
			            document.getElementById(target).innerHTML="jah error:\n" +
			                req.statusText;
			        }
			    }
			}



function scpswapDIVForSession(url,target) {

			    // native XMLHttpRequest object
			    document.getElementById(target).innerHTML = 'loading...';

			    if (window.XMLHttpRequest) {
			        req = new XMLHttpRequest();
					req.onreadystatechange = function() {scpfSwapDIVDone(target);};
					req.open("GET", url, true);
			        req.send(null);
			    // IE/Windows ActiveX version
			    } else if (window.ActiveXObject) {
			        req = new ActiveXObject("Microsoft.XMLHTTP");
			        if (req) {
			            req.onreadystatechange = function() {scpfSwapDIVDone(target);};
			            req.open("GET", url, true);
			            req.send();
			        }
			    }
}

function scpfshowdiv(id) {
	document.getElementById(id).style.display='block';
}

function scpfhidediv(id) {
	document.getElementById(id).style.display='none';
}

function scpfshowhidediv(id) {
	if (document.getElementById(id).style.display == 'none') {
		document.getElementById(id).style.display='block';
	} else {
		document.getElementById(id).style.display='none';
	}
}

/* My Item Status page */
var itemdetailclass = 'itemdetail';
var itemheaderclass = 'itemheader';

function addClass(element,classname){
	Element.addClassName(element,classname);
}
function removeClass(element,classname){
	Element.removeClassName(element,classname);
}

function getNextNonTextSibling(theElement){
	var val = null;

	if($(theElement).nextSibling==null){
		return val;
	}
	else {
		var nextSib = $(theElement).nextSibling;

		while (nextSib.nodeType != 1){
			if(nextSib.nextSibling==null){
				nextSib = null;
				break;
			}
			else{nextSib = nextSib.nextSibling}
		}
		val = nextSib;
	}
	return val;
}

function disableLinks(disableView,disableHide){

	viewAllLink = $("viewhidelinks").getElementsByTagName("a")[0];
	hideAllLink = $("viewhidelinks").getElementsByTagName("a")[1];

	if(disableView){
		Element.addClassName(viewAllLink,'disabled');
		viewAllLink.disabled=true;
		viewAllLink.onclick = function(){return false;};
	}
	if(disableHide){
		Element.addClassName(hideAllLink,'disabled');
		hideAllLink.disabled=true;
		hideAllLink.onclick = function(){return false;};
	}
}

function enableLinks(enableView,enableHide){
	viewAllLink = $("viewhidelinks").getElementsByTagName("a")[0];
	hideAllLink = $("viewhidelinks").getElementsByTagName("a")[1];

	if(enableView){
		Element.removeClassName(viewAllLink,'disabled');
		viewAllLink.disabled=false;
		viewAllLink.onclick = function (){viewAll('itemstatusdetails');return false;};
	}
	if(enableHide){
		Element.removeClassName(hideAllLink,'disabled');
		hideAllLink.disabled=false;
		hideAllLink.onclick = function (){hideAll('itemstatusdetails');return false;};
	}
}

// Check reponse for error
function sessionExpired(theResponse){
	isExpired = false;
	isExpired = (theResponse.indexOf("ERRORSTO", 0) != -1 || theResponse.indexOf("authorized to view", 0) != -1)?true:false;
	return isExpired;
}

function toggleDetail(rootElement,isViewAll,isLast){
	reqDetailRow = getNextNonTextSibling(rootElement);

	if(reqDetailRow!=null && Element.hasClassName(reqDetailRow,itemdetailclass)){ // if the detail is open, close it
		totalOrders = document.getElementsByClassName(itemheaderclass).length;
		totalOpen = document.getElementsByClassName(itemdetailclass).length

		Element.remove(reqDetailRow);
		Element.removeClassName(rootElement,'open');

		// if it's the only one open, disable Close All link
		// if all are open, enable View All link


		if(totalOpen == 1){
			disableLinks(false,true);
		}
		else if (totalOpen == totalOrders){
			enableLinks(true,false);
		}
	}
	else{
		// if not looping through via View All link and there are no open details, enable Hide All link
		if(!isViewAll && document.getElementsByClassName(itemdetailclass).length < 1){
			enableLinks(false,true);
		}
		// if not looping through and the number of open links is one less than all orders, disable View All link
		if(!isViewAll){
			if (document.getElementsByClassName(itemdetailclass).length == (document.getElementsByClassName(itemheaderclass).length-1)){
				disableLinks(true,false);
			}
		}

		Element.addClassName(rootElement,'open');
		var newResponseNode = '';
		newResponseNode += '<tr class="'+itemdetailclass+'">';
		newResponseNode += '<td colspan="3">';
		newResponseNode += '</td></tr>';

		new Insertion.After($(rootElement),newResponseNode);

		var url = $F(rootElement.id+'url');

		var myAjax = new Ajax.Request(
			url,
			{
				method: 'post',
				parameters: '',
				onLoading: function (response){itemStatusLoading(rootElement,response);},
				onComplete: function (response){itemStatusResponse(rootElement,response,isLast);},
				onFailure: function (response){itemStatusFailure(rootElement);}
		});
	}
}

function itemStatusLoading(rootElement,originalRequest){
	reqDetailRow = getNextNonTextSibling(rootElement);
	// insert new loading node
	var newLoadingNode = document.createElement('p');
	newLoadingNode.innerHTML = "loading...";
	reqDetailRow.firstChild.appendChild(newLoadingNode);
}

function itemStatusResponse(rootElement,originalRequest,isLast){
	if(sessionExpired(originalRequest.responseText)){
		window.location.href = "/portal/site/merckproductservices/?front_door=true&epi-content=ERRORSTO";
	}
	else {
		reqDetailRow = getNextNonTextSibling(rootElement);
		reqDetailRow.firstChild.innerHTML = "";
		reqDetailRow.firstChild.innerHTML = originalRequest.responseText;
	}
	if(isLast){enableLinks(false, true);} //isLast passed in as true from the View All link which loops through all orders and calls toggleDetail numerous times
}

function itemStatusFailure(rootElement){
	reqDetailRow = getNextNonTextSibling(rootElement);
	reqDetailRow.firstChild.innerHTML = "";
	reqDetailRow.firstChild.innerHTML = "An error occurred while loading the data.";
}

function viewAll(rootEl){
	disableLinks(true,true);
	// get handle on all itemheader rows
	var headerRows = document.getElementsByClassName(itemheaderclass,rootEl);

	// iterate through and for each header:
	// 1. remove open detail row if exists
	// 2. make server request

	if(headerRows.length > 0){
		for(i=0;i<headerRows.length;i++){
			// 1. remove open detail row if exists
			nextSiblingRow = getNextNonTextSibling(headerRows[i]);

			if(nextSiblingRow!=null && Element.hasClassName(nextSiblingRow,itemdetailclass)){ // if the details are open, close em
				Element.remove(nextSiblingRow);
				//Element.removeClassName(rootElement,'open');
			}

			// 2. make server request
			// (all itemdetail rows will be closed)
			if(i == headerRows.length-1){isLast = true;}
			else {isLast = false;}
			isViewAll = true;
			toggleDetail(headerRows[i],isViewAll,isLast);
		}
	}
}
function hideAll(rootEl){
	disableLinks(true,true);
	// get handle on all itemdetail rows
	var openRows = document.getElementsByClassName(itemdetailclass,rootEl);

	// iterate through and remove the open rows from DOM
	if(openRows.length > 0){
		openRows.each(
			function(element){
				Element.remove(element);
			}
		)
	}

	// get handle on all itemheader rows
	var headerRows = document.getElementsByClassName(itemheaderclass,rootEl);

	// iterate through and remove the "open" class from header rows
	if(headerRows.length > 0){
		headerRows.each(
			function(element){
				removeClass(element,'open');
			}
		)
	}
	enableLinks(true,false);
}

function checkAnchor(anchorName){
	anchorList = document.getElementsByName(anchorName);
	if(anchorList.length==1){
		new Effect.ScrollTo(anchorList[0],{duration:0.0,offset:-5});
	}
}

/* end My Item Status page */

function generalPopup(url,winoptions){

	// Detect existence of the popup
	if(typeof genpopup!="object"){ // check if the pop-up was created
		genpopup = window.open(url,"newwin",winoptions);
	}
	else if(typeof genpopup=="object" && genpopup.closed){ // check if mocpopup was created, but the window is closed
		genpopup = window.open(url,"newwin",winoptions);
	}
	else {
		genpopup.location.href = url;
	}
	genpopup.focus();
}


