/** 
 * 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
 *  16      07/02/2010    Infosys(Selva Kumar P)        HPQC #814 - Updated code to handle Match All Terms/ Match Any Terms for all regions.
 *  17		07/21/2010    Infosys(Sujay Padalkar)       Added code to restrict access to cart pages for EU Registered User
 *  18		08/05/2010    Infosys(Deepak Suneja)        EU punchout changes
 *  18		08/20/2010    Infosys(Deepak Suneja)        HPQC # 1004,1002 - The account setting tab enabled for EU punchout user and display of comapny name
 *  19		08/31/2010    Infosys(Sujay Padalkar)       Changed the user type for the Eu registered user
 *  20		09/01/2010    Infosys(Deepak Suneja)        HPQC # 1003 -  display of company name on home page for EU punchout user
 *  21		09/15/2010    Infosys(Deepak Suneja)        The sign link issue on WCM pages
 *  22		09/18/2010    Infosys(Veena Khatwani)       Changed the MY-Account link for punchout user
 *  23      09/30/2010    Infosys(Veena Khatwani)       Removed the "|" between US and its flag image
 *  24      09/30/2010    Infosys(Sujay Padalkar)       Added methods to mask/unmask textboxes.  
 *  25      10/01/2010    Infosys(Gayathri Kannan)      added condition to display EU banner for users logged in from nonUSIP regions
 *  26      10/04/2010    Infosys(Gayathri Kannan)      added methods to create cookie for EU banner link
 *  27      10/06/2010    Infosys(Veena Khatwani)       Updated code to block US link for punchout user
 *  28		11/02/2010	  Infosys(Sujay Padalkar)		Added code to display region specific 'Need Help' link on home page
 *  29		12/23/2010    Infosys(Sujay Padalkar)		Added code to change Need Help link for EU region
 *  30		01/04/2011    Infosys(Selva Kumar P)		Added code to remove search box focus in Canada region.
 *  31		02/01/2011    Infosys(Gayathri Kannan)		Added code to remove null object error observed in create new account page.
 *  32      04/12/2011    Infosys(Gayathri Kannan)      Added code to display signin link for Canada
 *  33		06/06/2011    Infosys(Sujay Padalkar)		Added code to display Canada specific need help  link on home page
 *  34		06/23/2011	  Infosys(Sujay Padalkar)		Added code to display Canada Launch Banner
 *  35		01/06/2012	  Infosys(Arun S)		        Modified code for  implementing Brazil cart
 * 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;
//resgistered user value corresponds to its defn in Person_LinkBean.java
var registeredUserType = "6";

/*
 * 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(uri) {
	createXmlHttpRequest();
	headerData = true;
	xmlHttp.open("GET", "/servlet/WcmData?dummy="+new Date().getTime()+"&uri="+escape(uri), true);
	xmlHttp.setRequestHeader("Content-Type", "text/html;charset=UTF-8");
	xmlHttp.onreadystatechange = handleStateChange;
	xmlHttp.send(null);		
	window.focus();
}

/*
 * getSignInData()	- sends out the request to the servlet WcmData
 */

function getSignInData(uri) {
	createXmlHttpRequest();
	signInData = true;
	xmlHttp.open("GET", "/servlet/WcmData?dummy="+new Date().getTime()+"&uri="+escape(uri), true);
	xmlHttp.setRequestHeader("Content-Type", "text/html;charset=UTF-8");
	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];
	var userType = '';
	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();
		if(null != user.getElementsByTagName("userType")[0]){
			userType = user.getElementsByTagName("userType")[0].firstChild.data;
		}
		var items = user.getElementsByTagName("items")[0].firstChild.data;
		var shoppingcart = user.getElementsByTagName("shoppingcart")[0];
		var products = shoppingcart.getElementsByTagName("product");
		var region = user.getElementsByTagName("region")[0].firstChild.data;
		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>";
			if(region == 'US'|| region == 'CA'|| region == 'BR'){
				document.getElementById("header_field2").innerHTML = "|&nbsp;&nbsp;<a href='/sale/Account_main.jsp?tab=settings'> My Account </a>";
				
			}else if (region == 'EU'){
				document.getElementById("header_field2").innerHTML = "|&nbsp;&nbsp;<a href='/eu-sales/account/dci/settings'> My Account </a>";	
			}
			
		}else if(user.getElementsByTagName("sciquest")[0] != null && region == 'EU'){
			document.getElementById("header_field2").innerHTML = "|&nbsp;&nbsp;<a href='/eu-sales/account/dci/settings'> My Account </a>";
		}else if(user.getElementsByTagName("sciquest")[0] != null && region == 'US'){
			document.getElementById("regionName.href").href = '#';
			if(user.getElementsByTagName("PunchOutSubAccount")[0] != null){
				document.getElementById("header_field2").innerHTML = "|&nbsp;&nbsp;<a href='/sale/Account_main.jsp?tab=shippingPunchOut'> My Account </a>";
			}
		}
		if (document.getElementById("member") != null) document.getElementById("member").style.display = '';		
		
		if(null != userType && registeredUserType == userType){
			document.getElementById("header_field3").innerHTML = '';
		}else{
			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 = null;
		var authvalue = null;
		var matchAllTerms = null;
		//not to reference response object when null
		if(response!=null){
			msg = response.getElementsByTagName("NonUSIP")[0];
			authvalue = response.getElementsByTagName("authentication")[0];
			matchAllTerms = response.getElementsByTagName("matchAllTermsFlag")[0].firstChild.data;
		}
		if(authvalue==null){
			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';
			}
		}
		// EU banner page has to be shown for all users
		if(authvalue!= null || msg!=null){
			//Code added to display the EU banner when its NONUSIP			
			displayEUBanner();	
		}
		else
		{	//Code added to not display the EU banner when its USIP
			if (document.getElementById("notification_container") != null){
				document.getElementById("notification_container").style.display = 'none';
				document.getElementById("notification_banner").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 = "";
		var region = user.getElementsByTagName("region")[0].firstChild.data;
		if(user.getElementsByTagName("sciquest")[0] != null && region == 'EU'){
			htmlContent = "<H2>Welcome, "+ user.getElementsByTagName("companyName")[0].firstChild.data+"</H2>" + "<DIV>"
		}else{
			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>"
		}
		if(user.getElementsByTagName("sciquest")[0] != null && region == 'EU'){
			htmlContent = htmlContent + "<A href='/eu-sales/account/dci/settings'>My Account</A>" + "<BR>"
		}
		if(region == 'EU'){
			//For Europe region the 'Need Help' support link should navigate to eCommerce support page 
			htmlContent = htmlContent + "<A href='/eu/support/ordering/'>Need Help?</A>" ;
		}else if(region == 'US'){
			htmlContent = htmlContent + "<A href='/support/technical/'>Need Help?</A>" ;
		}else if(region == 'CA'){
			htmlContent = htmlContent + "<A href='/ca/support/technical/'>Need Help?</A>" ;
		}
		htmlContent = htmlContent + "</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");
	}	
}


function removeMask(id, displayValue){
	var maskValue = document.getElementById(id).value;
	if(maskValue == displayValue){
		document.getElementById(id).value = '';
	}
}

function inputMask(id, displayValue){
	var maskValue = document.getElementById(id).value;
	if(null == maskValue || '' == maskValue){
		document.getElementById(id).value = displayValue;
	}
}
//To create cookie for dismiss link present in EU banner
function makeCookie(name,value,days){
		var cookie = "";	
			cookie =name+"="+value+";";
		if(days){
		    var date = new Date();
		    date.setTime(date.getTime()+(days*24*60*60*1000));
		    var expires = "; expires="+date.toGMTString();
		     cookie = cookie+" expires="+date.toGMTString()+";";
		}
		else var expires = "";
		cookie = cookie+expires;
	   cookie = cookie+"; path=/";
	   document.cookie = cookie;
	  	
	}
function get_cookie ( cookie_name )
{
  var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );

  if ( results )
    return ( unescape ( results[2] ) );
  else
    return null;
}

function delete_cookie ( cookie_name )
{
  var cookie_date = new Date ( );  // current date & time
  cookie_date.setTime ( cookie_date.getTime() - 1 );
  document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}

function createCookie(name, value, days){	
	var cookie = "";	
		if(getCookie(name) != value && value.indexOf("http")<0){			
			cookie = name+"="+value+";";
			if(days){
			    var date = new Date();
			    date.setTime(date.getTime()+(days*24*60*60*1000));
			     cookie = cookie+" expires="+date.toGMTString()+";";
			}
		   cookie = cookie+"; path=/";
		   document.cookie = cookie;
		}
}

function deleteCookie(name,path ,domain){
	if(getCookie(name)){		
		document.cookie = name +"=" 
							   +((path)?";path="+path:"")
							   +((domain)?";domain="+domain:"")
							   +";expires=Thu, 01-Jan-1970 00:00:01 GMT";
	}
}

function getCookie( cookieName ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ ){
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == cookieName ){
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found ){
		return null;
	}
}

function createPermanentCookie(name, value, days){	
	var checked = document.getElementById("remember").checked;
	var cookie = "";	
	if (checked){		
		if(getCookie(name) != value && value.indexOf("http")<0){			
			cookie = name+"="+value+";";
			if(days){
			    var date = new Date();
			    date.setTime(date.getTime()+(days*24*60*60*1000));
			     cookie = cookie+" expires="+date.toGMTString()+";";
			}
		   cookie = cookie+"; path=/";
		   document.cookie = cookie;
		}
    }else{
    	if(getCookie(name) == value && value.indexOf("http")<0){
    		deleteCookie(name, "", "");
    	}
    }
}


function updateCheckBox(){		
	if(!document.getElementById("remember").checked){			
		document.getElementById("rememberRegion").value = '';
	}else{
		document.getElementById("rememberRegion").value = 'remember';
	}
}

function displayEUBanner(){
	if(getCookie('dismissme')){
		if(document.getElementById("notification_container")!= null){
			document.getElementById("notification_container").style.display = 'none';
			document.getElementById("notification_banner").style.display = 'none';
		}
	}else{
		if (document.getElementById("notification_container") != null){		
			$(document).ready(function() {
				if($("div#notification_banner").is(":hidden")){
				  $("div#notification_banner").slideDown(1000);
				}
			});	
		}
		if(document.getElementById("notification_container")!= null){
			document.getElementById("notification_container").style.display = '';
			document.getElementById("notification_banner").style.display = '';
		}
	}
}

function displayCABanner(){
	if(getCookie('dismissme')){
		if(document.getElementById("notification_container_ca")!= null){
			$(document).ready(function() {
				$("div#notification_container_ca").css("display", "none");
				$("div#notification_container_ca").children("div#notification_banner").css("display", "none");
			});
		}
	}else{
		if (document.getElementById("notification_container_ca") != null){		
			$(document).ready(function() {
				if($("div#notification_banner").is(":hidden")){
				  $("div#notification_banner").slideDown(1000);
				}
			});	
		}
		if(document.getElementById("notification_container_ca")!= null){
			$(document).ready(function() {
				$("div#notification_container_ca").css("display", "");
				$("div#notification_container_ca").children("div#notification_banner").css("display", "");
			});
		}
	}
}

function dismissBanner(){
	$("div#notification_banner").slideUp(500);
}

