//added js functions from the old Sigma-Aldrich site

function OpenWin(URL, windowattributes) {
	//help=window.open(URL,"Help",'window attributes');
	help=window.open(URL,"Help",windowattributes);
	help.focus();
}

function changeParentURL(url){
	window.opener.location = url;
}

function OpenWindow(URL, windowattributes) {
	    help=window.open(URL,"Help",windowattributes);
	    help.focus();
	}

//SCRIPT FOR A JUMP-TO BOX
      function MM_jumpMenu(targ,selObj,restore){ //v3.0
      eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
      if (restore) selObj.selectedIndex=0;
 }     

//**added for CoreMetrics**//

function getMemberId() {
	var hasWCUserActivityCookie  = document.cookie.indexOf("WC_USERACTIVITY_");
	if (hasWCUserActivityCookie != -1 ){ 
		var startcount2 = hasWCUserActivityCookie + 16;// Start cookie value 
		var endcount2 = document.cookie.indexOf("=", startcount2); // End cookie value 
		if (endcount2 == -1) endcount = document.cookie.length; 
			var MemberID = document.cookie.substring(startcount2, endcount2); //Extract value 
	} 
	else 
	{ 
		MemberID = "Unknown"; 
	}

	if(MemberID == "-1002"){MemberID = "Unknown";}
	return MemberID;
}

function getClientId() {
	var ClientID = "Unknown";
	var userCookie = document.cookie;
 	var hasAnonymousClientIdCookie = userCookie.indexOf("AnonymousClientId="); 
	if (hasAnonymousClientIdCookie != -1 )
		{userCookie = userCookie.substring(hasAnonymousClientIdCookie + 21, userCookie.length);} 
 	var hasClientIdCookie = userCookie.indexOf("ClientId=");
	if (hasClientIdCookie != -1 ){
		var startcount = hasClientIdCookie + 9;
		var endcount = userCookie.indexOf(";", startcount);
			if (endcount == -1) endcount = userCookie.length; 
			{ClientID = userCookie.substring(startcount, endcount);}
	}
	return ClientID;
}

function getSiteId() {
	var Site = "SA";
	if (document.location.href.indexOf("safcglobal.com") != -1 ){
	Site = "SAFC";
	} 
	return Site;
}


//**added for Bookmark**//

var addthis_pub = "sigmaaldrich";

function writeSocialBookmark() {


}

//**added for Type ahead Search**//
function searchTypeahead(){
	var NewObj = document.getElementById('typeaheadText');
	var text = document.getElementById("N4");
	if (text != null)
	{
		if(text.value.length > 2)
		{
			CreateRequest();
			var url = getCatalogNameFromURL()+ "/SearchTypeahead.do?searchText=" + text.value;
			request.open("GET", url, true);
    			request.onreadystatechange=UpdateTypeahead;
    			request.send(null);
		}
	}
}

function CreateRequest(){
	try{
		request = new XMLHttpRequest();
	}
	catch(trymicrosoft){
		try{
			request = newActiveXObject("Msxml2.XMLHTTP");
		}
		catch(othermicrosoft){
			try{
				request = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch(failed){
				request = null;
			}
	     	}	
	}
}

function UpdateTypeahead(){
	if (request.readyState == 4){
		var NewData = request.responseText;
		var NewObj = document.getElementById("typeaheadText");
		NewObj.innerHTML = NewData;
		NewObj.style.display='';
	}
}	

function typeaheadLink(name,id){
	document.regularSearch.N25.value = id;
	var typeahead = document.getElementById('typeaheadText');
	typeahead.style.display='none';
	submitRegSearch();
}

function getCatalogNameFromURL(){
    //use catalog as context path if failed
    var url = '/catalog';
    try{
		var path = location.pathname;
			 
		if(path.indexOf("/")==0){
			  var len = path.length;
			  path = path.substring(1, len);
			      
		      if(path.indexOf("/")>=0){
			        var index = path.indexOf("/");
			        url = "/" + path.substring(0,index);
		      }else{		      		
			     	url = "/" + path;
			  }
		}			
			  
    }catch(err){}		
	return url;
}

//**added for popup countryselect**//
var CountryCookie = document.cookie.indexOf("country=");
if (CountryCookie == -1) { 
	if ((document.location.href.indexOf("safcglobal.com") == -1) && (document.location.href.indexOf("/safc-") == -1) && (document.location.href.indexOf("/help") == -1) && (document.location.href.indexOf("SAFCSearch") == -1) && (document.location.href.indexOf("/webapp") == -1) && (document.location.href.indexOf("/splash") == -1) && (document.location.href.indexOf("/sigma-aldrich/home") == -1) && (document.location.href.indexOf("/medialib") == -1) && (document.location.href.indexOf("/errorpage") == -1)) {
	 function start() {
	  grayOut(true,{'opacity':'25'});
	  showPopUp('dialog');
	  load('/site-level/set-country-cookie.html','dialog');
	 }
	if (window.attachEvent) {window.attachEvent('onload', start);}
	else if (window.addEventListener) {window.addEventListener('load', start, false);}
	else {document.addEventListener('load', start, false);}
  }
} 

	// number of days cookie lives for
	num_days = 360;
	function ged(noDays){
		var today = new Date();
		var expr = new Date(today.getTime() + noDays*24*60*60*1000);
		return  expr.toGMTString();
	}

	//This gets called when "submit" is clicked.  It will set the cookie and close the window.
	function setCookieRedirect()
	{
        var selectedValue = document.choosecountry.cscope.options[document.choosecountry.cscope.selectedIndex].value;
                if ((selectedValue) != "" ) {
		//selectedValue = selectedValue.search.replace(/%28/,"(").replace(/%29/,")");
		selectedValue = selectedValue.replace(/[^a-zA-Z % + & =]+/g,'');
		sCode = selectedValue.substring(selectedValue.indexOf("Code=") + 5, selectedValue.indexOf("&Page"));
		sPage = selectedValue.substring(selectedValue.indexOf("Page=") + 5, selectedValue.indexOf("&SO"));
		sSO = selectedValue.substring(selectedValue.indexOf("SO=") + 3);

		document.cookie = "country=" + sCode + ";path=/; expires=" + ged(num_days);

		var SialSiteDef = document.cookie.indexOf("SialSiteDef="); 
		if (SialSiteDef != -1) { 
			//If SialSiteDef exists, get it's value
        		var start = SialSiteDef + 12;                             // Start of cookie value 
        		var end = document.cookie.indexOf(";", start);            // End of cookie value 
        		if (end == -1) end = document.cookie.length; 
        		var SialSiteDef=unescape(document.cookie.substring(start, end)); 
			//Get CountryCode value out of SileSiteDef if it exists
			var resetSialSiteDef = "";
			var arr = SialSiteDef.split("|");
			for(var i=0 ; i< (arr.length - 1) ; i++){
				var tempV = arr[i];
				if(tempV.indexOf("CountryCode") <= -1){
					resetSialSiteDef = resetSialSiteDef + tempV + "|" ;
				}
			} 
			//append new CountryCode at the end of SialSiteDef and set cookie
			resetSialSiteDef = resetSialSiteDef + "CountryCode~" + sSO + "|";
			document.cookie = "SialSiteDef=" + resetSialSiteDef + ";path=/";

        	} else {

			document.cookie = "SialSiteDef=CountryCode~" + sSO + "|" + ";path=/; expires=" + ged(num_days);
		}

		closePopUp('dialog');
		grayOut(false);
		if (document.location.href.indexOf("/catalog") != -1){
			window.location.reload(true);
		}
                } else {
                alert("Please Choose a Country or Region");
                }
	}

function showPopUp(el) {
var dlg = document.getElementById(el)
dlg.style.display = "block"
}
function closePopUp(el) {
var dlg = document.getElementById(el)
dlg.style.display = "none"
}

function grayOut(vis, options) {
// Pass true to gray out screen, false to ungray
// options are optional. This is a JSON object with the following (optional) properties
// opacity:0-100 // Lower number = less grayout higher = more of a blackout 
// zindex: # // HTML elements with a higher zindex appear on top of the gray out
// bgcolor: (#xxxxxx) // Standard RGB Hex color code
// grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});
// Because options is JSON opacity/zindex/bgcolor are all optional and can appear
// in any order. Pass only the properties you need to set.
var options = options || {}; 
var zindex = options.zindex || 50;
var opacity = options.opacity || 70;
var opaque = (opacity / 100);
var bgcolor = options.bgcolor || '#000000';
var dark=document.getElementById('darkenScreenObject');
if (!dark) {
// The dark layer doesn't exist, it's never been created. So we'll
// create it here and apply some basic styles.
// If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917
var tbody = document.getElementsByTagName("body")[0];
var tnode = document.createElement('div'); // Create the layer.
tnode.style.position='absolute'; // Position absolutely
tnode.style.top='0px'; // In the top
tnode.style.left='0px'; // Left corner of the page
tnode.style.overflow='hidden'; // Try to avoid making scroll bars 
tnode.style.display='none'; // Start out Hidden
tnode.id='darkenScreenObject'; // Name it so we can find it later
tbody.appendChild(tnode); // Add it to the web page
dark=document.getElementById('darkenScreenObject'); // Get the object.
}
if (vis) {
// Calculate the page width and height 
if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) ) {
var pageWidth = document.body.scrollWidth+'px';
var pageHeight = document.body.scrollHeight+'px';
} else if( document.body.offsetWidth ) {
var pageWidth = document.body.offsetWidth+'px';
var pageHeight = document.body.offsetHeight+'px';
} else {
var pageWidth='100%';
var pageHeight='100%';
} 
//set the shader to cover the entire page and make it visible.
dark.style.opacity=opaque; 
dark.style.MozOpacity=opaque; 
dark.style.filter='alpha(opacity='+opacity+')'; 
dark.style.zIndex=zindex; 
dark.style.backgroundColor=bgcolor; 
dark.style.width= pageWidth;
dark.style.height= pageHeight;
dark.style.display='block'; 
} else {
dark.style.display='none';
}
}

function ahah(url, target) {
  document.getElementById(target).innerHTML = ' Retrieving data...';
  if (window.XMLHttpRequest) {
    req = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    req = new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (req != undefined) {
    req.onreadystatechange = function() {ahahDone(url, target);};
    req.open("GET", url, true);
    req.send("");
  }
}  

function ahahDone(url, target) {
  if (req.readyState == 4) { // only if req is "loaded"
    if (req.status == 200) { // only if "OK"
      document.getElementById(target).innerHTML = req.responseText;
    } else {
      document.getElementById(target).innerHTML=" Error:\n"+ req.status + "\n" +req.statusText;
    }
  }
}

function load(name, div) {
	ahah(name,div);
	return false;
}

document.write("<div id='dialog'></div>");

