/** 
 * portletData.js	- This file contains the AJAX methods to update the custom header.
 *  
 * Version  	Date          Author       			Comment
 *	1   	04/22/2009    Infosys(Rajesh Lakshmana)		NA 
 *  2       06/17/2009    Infosys(Deepak Suneja)        Changed logic for Non-US IP     
 *  3       06/25/2009    Infosys(Deepak Suneja)        Added javascript validation for numeric check     
 *  4		07/01/2009	  Infosys(Rajesh Lakshmana)		Updated code to handle page refresh after login.
 *  5       06/30/2009    Igor Deinitchenko             Changed delimiter from css to here    
 *  6		07/14/2009	  Infosys(Rajesh Lakshmana)		Updated code to handle sign in bubble on home page. 
 *  7		07/31/2009	  Infosys(Rajesh Lakshmana)		Updated code to handle sciquest user.
 *  8		08/10/2009	  Infosys(Sujay Padalkar)		Mantis # 5535 - Fixed the issue of display of popups on load of page & Transparent popups 
 *  								                    Mantis # 5536 - Resolved issue of changing the links from Sign In to Sign Out. 
 *  9		08/10/2009    Igor Deinitchenko		    	Changed for #5503 - Adjust the Learn More link.
 *  10		08/17/2009    Igor Deinitchenko		    	Changed for #5521 - Prevent the Account links in the SciQuest mode.
 *  11		10/08/2009    Igor Deinitchenko		    	Enhancement R-001 - Sign-in functionality. Behavior during Sign in and Sign Out. 
 *  12		10/09/2009    Igor Deinitchenko		    	Enhancement R-001 - Sign-in functionality. Rolled back changes.
 *  13		10/21/2009	  Infosys(Deepak Suneja)		Mantis # 5901 - Add to cart enabled on Product details page when user is not signed in 
 *  14      11/23/2009    Infosys(Sujay Padalkar)       ENH - 006 eCat Browser
 *  15      01/06/2010    Infosys(Deepak Suneja)        #6258 - Search: Match Any/All Setting Needs to Persist on All Pages
 * Dependencies - Retrieves the data from the WcmData servlet.
 */

var xmlHttp;// global instance of XMLHttpRequest
var headerData = false;
var signInData = false;
var userData = false;
var miniCartData = false;

/*
 * createXmlHttpRequest() - creates the browser dependent XMLHttpRequest 
 */

function createXmlHttpRequest() {
	if (window.XMLHttpRequest)
		xmlHttp = new XMLHttpRequest();
	else if (window.ActiveXObject)
		xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

}

/*
 * getHeaderData()	- sends out the request to the servlet WcmData
 */

function getHeaderData() {
	createXmlHttpRequest();
	headerData = true;
	xmlHttp.open("GET", "/servlet/WcmData?dummy="+new Date().getTime(), true);
	xmlHttp.onreadystatechange = handleStateChange;
	xmlHttp.send(null);
}

/*
 * getSignInData()	- sends out the request to the servlet WcmData
 */

function getSignInData() {
	createXmlHttpRequest();
	signInData = true;
	xmlHttp.open("GET", "/servlet/WcmData", true);
	xmlHttp.onreadystatechange = handleStateChange;
	xmlHttp.send(null);
}

/*
 * getUserData()	- sends out the request to the servlet WcmData
 */

function getUserData() {
	createXmlHttpRequest();
	userData = true;
	xmlHttp.open("GET", "/servlet/WcmData", true);
	xmlHttp.onreadystatechange = handleStateChange;
	xmlHttp.send(null);
}

/**
 * This method send an AJAX call to update the list of categories that have been opened by the user
 * @param categoryId 
 */
function updateCategoryState(categoryId){	
	createXmlHttpRequest();
	xmlHttp.open("GET", "/servlet/CatalogHierarchyServlet?categoryId="+categoryId, true);
	xmlHttp.onreadystatechange = checkResponse;
	xmlHttp.send(null);
}

function checkResponse() {
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
			var message = xmlHttp.responseText;			
		}
	}
}

/*
 * handleStateChange() - retrieves the response from the Servlet
 */

function handleStateChange() {
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
			var message = xmlHttp.responseXML;
			if (userData)
				parseUserDataResponse(message)
				else {
					if (headerData)
						parseHeaderResponse(message);
					if (signInData)
						parseSignInResponse(message);
					if (miniCartData)
						parseMiniCartResponse(message);
				}
		} else {
			// alert("Error"+ xmlHttp.status +":"+xmlHttp.statusText);
		}
	}
}

/*
 * parseHeaderResponse(message) - parse the response message and update the header html objects
 */

function parseHeaderResponse(message) {
	var user = message.getElementsByTagName("user")[0];
	if (null != user) {
	// reload the window if the user is logged in, and the MiniShopping cart is not refreshed	
		if ((null != document.getElementById("onlogin_reload")) && ("true" == document.getElementById("onlogin_reload").value))
		window.location.reload();
		var items = user.getElementsByTagName("items")[0].firstChild.data;
		var shoppingcart = user.getElementsByTagName("shoppingcart")[0];
		var products = shoppingcart.getElementsByTagName("product");
		var matchAllTerms = user.getElementsByTagName("matchAllTermsFlag")[0].firstChild.data;
		if (user.getElementsByTagName("sciquest")[0] == null) {
			document.getElementById("header_field1").innerHTML = "|&nbsp;&nbsp;<a href='/sale/signOut.do'> Sign Out </a>";
			document.getElementById("header_field2").innerHTML = "|&nbsp;&nbsp;<a href='/sale/Account_main.jsp'> My Account </a>";
		}
		if (document.getElementById("member") != null) document.getElementById("member").style.display = '';
		if (products.length > 0)
			document.getElementById("header_field3").innerHTML = "|&nbsp;&nbsp;<a href='/sale/shoppingCart.do'> Cart(" + items + ")</a>"
		else
			document.getElementById("header_field3").innerHTML = "|&nbsp;&nbsp;<a href='/sale/shoppingCart.do'> Cart</a>";
		if(matchAllTerms=='true'){
			document.getElementById("match_all").checked = true;
		}else{
			document.getElementById("match_any").checked = true;
		}
	} else {
		var response = message.getElementsByTagName("response")[0];
		var msg = response.getElementsByTagName("NonUSIP")[0];
		var matchAllTerms = response.getElementsByTagName("matchAllTermsFlag")[0].firstChild.data;
		if(msg==null){
			document.getElementById("header_field1").innerHTML = "|&nbsp;&nbsp;<a href='/sale/SignIn.jsp?originalForwardLocation="+window.location.pathname+"'> Sign In </a>";
			document.getElementById("header_field2").innerHTML = '';
			document.getElementById("header_field3").innerHTML = '';
			if (document.getElementById("member") != null) document.getElementById("member").style.display = '';
		}else{
			document.getElementById("header_field1").innerHTML = '';
			document.getElementById("header_field2").innerHTML = '';
			document.getElementById("header_field3").innerHTML = '';
			// Hide the sign in bubble on home page if non-US IP
			if (document.getElementById("member") != null) document.getElementById("member").style.display = 'none';
		}
		if(matchAllTerms=='true'){
			document.getElementById("match_all").checked = true;
		}else{
			document.getElementById("match_any").checked = true;
		}
	}
}

/*
 * parseSignInResponse(message) - parse the response message and update the SignIn portlet
 *					html objects
 */

function parseSignInResponse(message) {
	var user = message.getElementsByTagName("user")[0];
	if (null != user) {
		if (user.getElementsByTagName("firstname")[0].firstChild != null)
			var firstname = user.getElementsByTagName("firstname")[0].firstChild.data;
		else var firstname = "";
		
		if (user.getElementsByTagName("lastname")[0].firstChild != null)
			var lastname = user.getElementsByTagName("lastname")[0].firstChild.data;
		else var lastname = "";

		var htmlContent = "<H2>Welcome, " + firstname + " " + lastname
		+ "</H2>" + "<DIV>"
		if (user.getElementsByTagName("sciquest")[0] == null) {
			htmlContent = htmlContent + "<A href='/sale/Account_main.jsp'>My Account</A>" + "<BR>"
			htmlContent = htmlContent + "<A href='/sale/signOut.do'>Sign Out</A>" + "<BR>"
		}
		htmlContent = htmlContent + "<A href='/support/technical/'>Need Help?</A>" + "</DIV>";
		document.getElementById("member").innerHTML = htmlContent;
	} else {

		var htmlContent = "<DIV>" + "<DIV id=signin>BD Biosciences Members "
		+ "<A href='/sale/SignIn.jsp'>Sign In to shop our catalog.</A>"
		+ "</DIV>" + "<DIV id=signup>Not a member?" + "<BR>"
		+ "<A href='/sale/CreateNewAccount_step1.jsp'>Sign Up</A> or "
		+ "<A href='/support/ordering/preview_shopping.jsp'>Learn More</A>."
		+ "</DIV>" + "</DIV>";
		//document.getElementById("member").innerHTML = htmlContent;
	}
}

/*
 * parseUserDataResponse(message) - parse the response message and update the SignIn portlet
 *					and the Header portlet html objects
 */

function parseUserDataResponse(message) {
	parseHeaderResponse(message);
	parseSignInResponse(message);
}

var temp = false;
function isNumeric()
{
	var ValidChars = "0123456789.";
    var IsNumber=true;
    var Char;
   sText=document.getElementById('quantity').value;
   sMaterialText=document.getElementById('material').value;
   if(sText=="" || sText==null){
  	 IsNumber = false;
   }	
 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
      if(IsNumber == false){
      //	var requestString     	
      ///	 self.location= requestString+ '&error=InvalidQuantity';
     //	alert('self location'+ self.location);
       temp=true;
      }else{
       	document.cartQuantity.action="/sale/buyProcess.jsp?materialNumber=" +sMaterialText  + "&numOrdered="+sText;
        document.cartQuantity.submit();         
        temp = false;
      }
   }
/**
 * This method is invoked on mouse over event to display the popup.
 * @param id 
 */
function showPop(id){	
	document.getElementById(id).style.visibility = 'visible';
}

/**
 * This method is invoked on mouse out event to hide the popup.
 * @param id 
 */
function hidePop(id){
	document.getElementById(id).style.visibility = 'hidden';
}

function scroll_field(myNum){	
	var section = "#toggleSection_" + myNum;
	var button = "#toggleButton_" + myNum;
	var container = "#toggleContainer_" +myNum;
	if ($(section).is(":hidden")){
		$(section).slideDown("fast");
		$(button).toggleClass("selected");
		$(container).toggleClass("selected");
	} else {
		$(section).slideUp("fast");
		$(button).toggleClass("selected");
		$(container).toggleClass("selected");
	}	
}