// JavaScript Document

function emailCheck (emailStr) {
/* The following pattern is used to check if the entered e-mail address
   fits the user@domain format.  It also is used to separate the username
   from the domain. */
var emailPat=/^(.+)@(.+)$/
/* The following string represents the pattern for matching all special
   characters.  We don't want to allow special characters in the address.
   These characters include ( ) < > @ , ; : \ " . [ ]    */
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
/* The following string represents the range of characters allowed in a
   username or domainname.  It really states which chars aren't allowed. */
var validChars="\[^\\s" + specialChars + "\]"
/* The following pattern applies if the "user" is a quoted string (in
   which case, there are no rules about which characters are allowed
   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
   is a legal e-mail address. */
var quotedUser="(\"[^\"]*\")"
/* The following pattern applies for domains that are IP addresses,
   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
   e-mail address. NOTE: The square brackets are required. */
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
/* The following string represents an atom (basically a series of
   non-special characters.) */
var atom=validChars + '+'
/* The following string represents one word in the typical username.
   For example, in john.doe@somewhere.com, john and doe are words.
   Basically, a word is either an atom or quoted string. */
var word="(" + atom + "|" + quotedUser + ")"
// The following pattern describes the structure of the user
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
/* The following pattern describes the structure of a normal symbolic
   domain, as opposed to ipDomainPat, shown above. */
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")


/* Finally, let's start trying to figure out if the supplied address is
   valid. */

/* Begin with the coarse pattern to simply break up user@domain into
   different pieces that are easy to analyze. */
var matchArray=emailStr.match(emailPat)
if (matchArray==null) {
  /* Too many/few @'s or something; basically, this address doesn't
     even fit the general mould of a valid e-mail address. */
	showError1("Please enter your E-mail address.")
	return false
}
var user=matchArray[1]
var domain=matchArray[2]

// See if "user" is valid
if (user.match(userPat)==null) {
    // user is not valid
    return false;
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
   host name) make sure the IP address is valid. */
var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
    // this is an IP address
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
	        showError1("Destination IP address is invalid!")
		return false
	    }
    }
    return true
}

// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null) {
	showError1("The domain name doesn't seem to be valid.")
    return false
}

/* domain name seems valid, but now make sure that it ends in a
   three-letter word (like com, edu, gov) or a two-letter word,
   representing country (uk, nl), and that there's a hostname preceding
   the domain or country. */

/* Now we need to break up the domain to get a count of how many atoms
   it consists of. */
var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 ||
    domArr[domArr.length-1].length>3) {
   // the address must end in a two letter or three letter word.
   showError1("The address must end in a three-letter domain, or two letter country.")
   return false
}

// Make sure there's a host name preceding the domain.
if (len<2) {
   var errStr="This address is missing a hostname!"
   showError1(errStr)
   return false
}

// If we've gotten this far, everything's valid!
return true;
}


function homeswitch(direction) {
  var frameAmount = 3;
  var frameCurrent = document.getElementById("keyDump").value;

  if (direction == "+") {

    if (frameCurrent < frameAmount) {

      frameCurrent++;

    } else {
      frameCurrent = 1;
    }

  } else {
    if (frameCurrent > 1) {
      frameCurrent = (frameCurrent - 1);
    } else{
      frameCurrent = frameAmount;
    }
  }

  i = 1

  while (i <= frameAmount) {

    if (i == frameCurrent) {
      document.getElementById("b"+i+"a").style.display = 'block';
      document.getElementById("b"+i+"b").style.display = 'block';
      document.getElementById("keyDump").value = i;
    } else {
      document.getElementById("b"+i+"a").style.display = 'none';
      document.getElementById("b"+i+"b").style.display = 'none';
    }

    i=(i+1)
  }
}


function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}





/***** New Function for Login/Updates/Email Page/Printer Friendly Added by Ankur **/
/*** Function for HTML Document Editing **/
function openEditor(url)
{
window.open(url);

}

var errors = false;

function clearError()
{
	document.getElementById("error_block").style.display="none";
	document.getElementById('field_errors').innerHTML = '';
	errors = false;
}

/** General Add Error function for showing errors **/
function addError(errorText)
{
	errors = true;
    //document.getElementById("error_block").style.display="inline";
    document.getElementById("error_block").style.display = "block";
	document.getElementById('field_errors').innerHTML = document.getElementById('field_errors').innerHTML + errorText;
	document.getElementById('field_errors').focus();
    //document.location='#top'; 
    document.location = '#registration';
}


// JavaScript Document
var hidden = 0
function login_toggle()
{

	if(hidden == 0){
		document.getElementById("login_content").style.display = "none";
		document.getElementById("login_collapse").src = "/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/wyeth_html/home/ia/image/registration_plus.gif";
		hidden = 1;
	}
	else {
		document.getElementById("login_content").style.display = "block";
		document.getElementById("login_collapse").src = "/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/wyeth_html/home/ia/image/registration_minus.gif";
		hidden = 0;
	}
}

/*
This function will be removed once we get the LDAP working.
This simple makes a call and then changes the password of the user
as the initial password needs to be change first time.
*/
function temporaryRegisterLogin(user,password)
{

new Ajax('/irj/servlet/prt/portal/prttarget/uidpwlogon/prteventname/performChangePassword/prtroot/com.sap.portal.navigation.portallauncher.default?login_submit=on&login_do_redirect=0&j_user='+user+'&oldPassword='+password+'&j_password='+password+'&confirmNewPassword='+password+'&j_authscheme=default&performChangePassword=Change', {
		method: 'get',
		onComplete: function(){
		  registrationLogin();
 		  
		}
	}).request();

}

function registrationLogin(user,password)
{

new Ajax('/irj/servlet/prt/portal/prtroot/com.wyeth.security.auth.HCPLogin?isRegistration=true&j_user='+user+'&j_password='+password,
	  {
		
		method:'get',
		onComplete: function(){
		  var response = this.response.text || "We are currently experiencing problems. Please try again later.";
		  if(response == 'failed') {
		  	alert('There is some problem');
		  }
		  else {
		  	document.location.href=response;
		  }
		},
		onFailure: function(){  }
	  }).request();

}




//Logoff scripts
    function delCookie(name,path,domain) {
      var today = new Date();
      var deleteDate = new Date(today.getTime() - 48 * 60 * 60 * 1000); // minus 2 days
      var cookie = name + "="
        + ((path == null) ? "" : "; path=" + path)
        + ((domain == null) ? "" : "; domain=" + domain)
        + "; expires=" + deleteDate;
      document.cookie = cookie;
    }

    function delSSOCookie() {
    	//Does nothing, handled on serverside.
    }


    function removeLitRequestCookies() {
        // 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 domain='';
    
        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.indexOf('LR')==0) || (cookie_name.indexOf('group_')==0) || (cookie_name.indexOf('related_')==0)){
                //alert("cookie to be deleted"+cookie_name);
                document.cookie = cookie_name + "=;path=/"  +
                        ( ( domain ) ? ";domain=" + domain : "" ) +
                        ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
                
            }
            a_temp_cookie = null;
            cookie_name = '';
        }

    }

//Logoff scripts

function logoff()
{
 var date = new Date();
var random  = ''+date.getDate()+date.getHours()+''+date.getMinutes()+''+date.getSeconds();
        removeLitRequestCookies();
new Ajax('/irj/servlet/prt/portal/prtroot/com.wyeth.security.auth.HCPLogoff?var='+random, {
		method: 'get',
		onComplete: function(){
		  var response = this.response.text;
		  document.location.href=response;
		}
	}).request();
	
	delSSOCookie();
}

//Email Page Function

var prevDivText = '';

//Backward compatibility
function emailPage()
{
	emailThisPage();
}

function emailThisPage() 
{

var currDivContent = document.getElementById('content_area');

var currDivText = document.getElementById('content_area').innerHTML;
var response = '';

if ( prevDivText == '' )
{
  
  prevDivText = currDivText;
}


new Ajax('/irj/servlet/prt/portal/prtroot/com.wyeth.page.email.EmailThisPage',
  {    
    method:'get',
    onComplete: function(){
      response = this.response.text || "We are currently experiencing problems. Please try again later.";
      currDivContent.innerHTML = response;
    },
    onFailure: function(){  }
  }).request();
 
  
}

function EmailThisPageResult( )
{

  clearError();	  
  document.getElementById('linkUrl').value = document.location.href;
  var currDivContent = document.getElementById('email_content');
  
  var toEmail = document.getElementById('to').value;
  var name = document.getElementById('name').value;
  var fromEmail = document.getElementById('from').value;
  var ccEmail = 'false';
  if ( document.getElementById('cc').checked )
  {
    ccEmail = 'true';
  }
  var emailErrors = false;
  
  if ( toEmail == null || toEmail == '' )
  {
    addError('<li>To Email Address is mandatory field</li>');
    emailErrors = true;
  }
  if ( fromEmail == null || fromEmail == '' )
  {
    addError('<li>Your E-mail Address is mandatory field</li>');
    emailErrors = true;
  } 
  if(emailErrors == true)
  {
  	return false;
  }
  $('EmailForm').submit();
    
}



function BackToPage( )
{  
  var currDivContent = document.getElementById('main_content');
  currDivContent.innerHTML = prevDivText;
}
var originalHTML = '';


/***** Print Page functionality ************/
function printPage() {  

  var url = document.location.href;
  url = url.substring(url.indexOf('/',9),url.length);

  //dcsMultiTrack('DCS.dcsuri', 'print_'+url);	

  var main_content = '';
	if (document.getElementById("main_content_area")) {
		main_content = document.getElementById("main_content_area").innerHTML;
	}
	
	main_content = ''
		+ '<div id="print_container">'
		+ '<div id="logo_header"><input type="button" onclick="javascript:normalView();" style="position:absolute;left:380px;" class="submit_xlong right" value="Return to normal view" />'
		+ '<img src="/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/wyeth_html/home/shared/img/wyeth_logo_header.gif" /></div>'
		+ '<div id="print_content">' + main_content + '</div>'
		+ '<div class="clear"></div><div id="footer">' + document.getElementById("footer").innerHTML + '</div></div>'
		+ '<link href="/resources/shared/css/print.css" rel="stylesheet" type="text/css" media="all" />';
	
	originalHTML = document.body.innerHTML;
  document.body.innerHTML = main_content;

}

function normalView() {
	document.body.innerHTML = originalHTML;
}


/****** Forgot Password Scripts ***************/
function forgotPassword(email) 
{

var currDivContent = document.getElementById('content_area');

var currDivText = document.getElementById('content_area').innerHTML;


var response = '';

prevDivText = currDivText;


new Ajax('/irj/servlet/prt/portal/prtroot/com.wyeth.security.registration.ForgotPasswordServlet?action=checkuser&email='+email,
  {    
    method:'get',
    onComplete: function(transport){
      response = transport|| "We are currently experiencing problems. Please try again later.";
      currDivContent.innerHTML = response;
      
      
    },
    onFailure: function(){  }
  }).request();
 
}

function emailNewPassword(email) 
{
var date = new Date();
var random  = ''+date.getDate()+date.getHours()+''+date.getMinutes()+''+date.getSeconds();
clearError();
var email = document.emailpassword.email.value;
var showerrors = false;
if ( email == '' || email.length == 0 )
{
  addError('<li>Please enter E-mail Address</li>');
  showerrors = true;
}
else if ( ( ( email.indexOf( '@' ) < 0 ) || ( email.indexOf( '.' ) < 0 ) ) && !( email.indexOf('int') == 0 ) )
{
  addError('<li>The email address you entered  <b>'+ email +'</b> is not a valid email address format.  Please try again.</li>');
  showerrors = true;
}

if ( showerrors == true )
{
  return false;
}


var currDivContent = document.getElementById('content_area');

var currDivText = document.getElementById('content_area').innerHTML;
var response = '';

prevDivText = currDivText;


new Ajax('/irj/servlet/prt/portal/prtroot/com.wyeth.security.registration.ForgotPasswordServlet?action=emailpassword&email='+email,
  {    
    method:'get',
    onComplete: function(transport){
      response = transport || "We are currently experiencing problems. Please try again later.";
      
      if ( response == 'false' )
      {        
      	currDivContent.innerHTML = currDivText;
      	addError('<li>The email address you entered  <b>'+ email +'</b> is not a valid account.  Please try again.</li>');
      }
      else
      {
        currDivContent.innerHTML = response;
      }      
      
    },
    onFailure: function(){  }
  }).request();
 
}

function resetPasswordBySecurityQuestion(email) 
{

clearError();
var email = document.questionpassword.email.value;
var showerrors = false;
if ( email == '' || email.length == 0 )
{
  addError('<li>Enter E-mail Address</li>');
  showerrors = true;
}
else if ( ( email.indexOf( '@' ) < 0 ) || ( email.indexOf( '.' ) < 0 ) )
{
  addError('<li>The email address you entered <b>'+ email +'</b> is not a valid email address format.  Please try again.</li>');
  showerrors = true;
}

if ( showerrors == true )
{
  return false;
}


var currDivContent = document.getElementById('content_area');

var currDivText = document.getElementById('content_area').innerHTML;
var response = '';

prevDivText = currDivText;


new Ajax('/irj/servlet/prt/portal/prtroot/com.wyeth.security.registration.ForgotPasswordServlet?action=getsecurityquestion&email='+email,
  {    
    method:'get',
    onComplete: function(transport){
      if ( transport != 'false' )
      {
	response = transport || "We are currently experiencing problems. Please try again later.";
      	currDivContent.innerHTML = response;
      }
      else
      {
	document.getElementById('questionpassword').style.display = 'none';
      }
    },
    onFailure: function() {  
    }
  }).request();
 
}


function checkSecurityAnswer(email) 
{

var currDivContent = document.getElementById('content_area');

var currDivText = document.getElementById('content_area').innerHTML;
var response = '';

prevDivText = currDivText;


new Ajax('/irj/servlet/prt/portal/prtroot/com.wyeth.security.registration.ForgotPasswordServlet?action=checksecurityanswer&email='+email,
  {    
  
    data: $('securityanswer').toQueryString(),
    method:'get',
    onComplete: function(transport){
      response = transport || "We are currently experiencing problems. Please try again later.";
      if(response =='false')
      {
      	document.getElementById("invalidanswer").style.display = "block";
      }
      else 
      {
      	currDivContent.innerHTML = response;
      }
    },
    onFailure: function(){  }
  }).request();
 
}


function updatepassword(form,email) 
{

	clearError();
	
	if(form.Password.value =='')
	{
		addError('<li>Please enter a valid Password.</li>');
	}

	else if(form.Password.value=='' && form.ConfirmPassword.value=='')
	{
		addError('<li>Please enter a valid Password.</li>');
	}
	else if(form.Password.value!= form.ConfirmPassword.value)
	{
		addError('<li>The Password and Confirm Password do not match.</li>');
	}
	else if(form.Password.value.length < 8)
	{
		addError('<li>Please enter a new password that contains a minimum of 8 characters</li>');
	}
	else {

		var currDivContent = document.getElementById('content_area');
		var currDivText = document.getElementById('content_area').innerHTML;
		var response = '';

		prevDivText = currDivText;


		new Ajax('/irj/servlet/prt/portal/prtroot/com.wyeth.security.registration.ForgotPasswordServlet?action=updatepassword&email='+email,
		  {    
		    data: $('securityanswer').toQueryString(),
		    method:'get',
		    onComplete: function(transport){
		      response = transport || "We are currently experiencing problems. Please try again later.";
		      currDivContent.innerHTML = response;
		    },
		    onFailure: function(){  }
		  }).request();
	}
 
}



/*    
function emailPage() {
  //document.location.href='/emailpage?url='+URLEncode(document.location.href)+'&title='+escape(document.title);
  document.emailForm.url.value = document.location.href;  
  document.emailForm.submit();
}
*/



function URLEncode(plaintext)
{
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()/: ?";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += " ";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;

};




function getCookie(c_name)
{
	if (document.cookie.length > 0) {
		c_start = document.cookie.indexOf(c_name + "=");
		
		if (c_start != -1) { 
			c_start=c_start + c_name.length + 1;
			c_end=document.cookie.indexOf(";", c_start);
			if (c_end == -1) c_end = document.cookie.length;
			
			return unescape(document.cookie.substring(c_start,c_end));
		} 
	}
	
	return "";
}

function setCookie(c_name, value, expiredays)
{
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + expiredays);
	
	document.cookie = c_name + "=" + escape(value) + ((expiredays==null) ? "" : ";expires=" + exdate.toGMTString());
}

function checkCookie()
{
	username = getCookie('username');
	if (username != null && username != "") {
		// alert('Welcome again '+username+'!')
	} else {
		disp_confirm();
		username = "protonixauth";
		
		if (username != null && username != "") {
			setCookie('username', username, 1);
		}
	}
}

function disp_confirm()
{
	var conf_msg = "The section you selected contains information intended for health care professionals only. This material has not been approved for the general public.";
	
	if (confirm(conf_msg)) {
		//document.getElementById("main_content").style.display = "block";
	} else {
		location.href = "http://www.wyeth.com";
	}
}

var docURL = window.location.href;
var myArray = docURL.split("/");
var banner = 0
	for (var loop = 0; loop < 6; loop++) {
		if (myArray[loop] == "protonix") {
			checkCookie();
		}
		else if (myArray[loop] == "protonix?rid=") {
			checkCookie();
		}
	}


function searchWyeth( searchUrl )
{
var currDivContent = document.getElementById('content_area');

var currDivText = document.getElementById('content_area').innerHTML;
var response = '';


  new Ajax(searchUrl,
  {
    data:$('siteSearchForm').toQueryString(),    
    method:'get',
    onComplete: function(transport){
      response = transport || "We are currently experiencing problems. Please try again later.";
      currDivContent.innerHTML = response;
    },
    onFailure: function(){  }
  }).request( ); 

return false;
}

function loadSiteMap( )
{
  
  new Ajax('/irj/servlet/prt/portal/prtroot/com.wyeth.km.cm.document.GetDoc/wyeth_html/home/shared/footer/sitemap.html',
  {
    method:'get',
    onComplete: function(transport){
      response = transport || "We are currently experiencing problems. Please try again later.";
	document.getElementById("content_area").innerHTML = response;	
	document.location.href = document.location.href + '#top';
    },
    onFailure: function(){  }
  }).request( ); 
}

function loadContactUs()

{

  new Ajax('/irj/servlet/prt/portal/prtroot/com.wyeth.km.cm.document.GetDoc/wyeth_html/home/shared/footer/contact.html',
  {
    method:'get',
    onComplete: function(transport){
      response = transport || "We are currently experiencing problems. Please try again later.";
	document.getElementById("content_area").innerHTML = response;	
	document.location.href = document.location.href + '#top';
    },
    onFailure: function(){  }
  }).request( ); 


}

function validateUpdateProfileForm(form) {


	clearError();

	if(form.Password.value != '' || form.ConfirmPassword.value != '')
	{
		if (form.Password.value != form.ConfirmPassword.value)
		{
			addError('<li>Password and Confirm Password do not match.</li>');
		}
		else if (form.Password.value.length <8)
		{
			addError('<li>Please enter a new password that contains a minimum of 8 characters</li>');
		}
	}
	if(form.FirstName.value=='')
	{
		addError('<li>Please enter a valid First Name.</li>');
	}
	if(form.LastName.value=='')
	{
		addError('<li>Please enter a valid Last Name.</li>');
	}
	if(form.State.value=='')
	{
		addError('<li>Please select a valid State.</li>');
	}

	if(form.Country.value=='')
	{
		addError('<li>Please select a valid Country.</li>');
	}

	if(form.ProfessionalDesignation.value=='')
	{
		addError('<li>Please select a valid Professional Designation.</li>');
	}
	if(form.Speciality.value=='')
	{
		addError('<li>Please select a valid Speciality.</li>');
	}
	//Check secretQuestion and answer
	if(form.SecretQuestion.value != '' || form.SecretAnswer.value !='')
	{
		if(form.SecretQuestion.value =='')
		{
			addError('<li>Please select a Security Question</li>');
		}
		if(form.SecretAnswer.value =='')
		{
			addError('<li>Please enter an Answer for the selected Security Question</li>');
		}
	}
	
	if(form.PermissionToEmail[0].checked ==false && form.PermissionToEmail[1].checked == false)
	{
		addError('<li>Please select your Marketing Preference</li>');
	}
	
	return errors;
}

function submitUpdateProfileForm (form)
{

  if(!validateUpdateProfileForm(form))
  {
	form.submit();
  }
 

}


function getLookUp(lookupName,select,selectedValue)
{

new Ajax('/irj/servlet/prt/portal/prtroot/com.wyeth.lookup.DataSet?name='+lookupName,
	  {
		method:'get',
		onSuccess: function(){
		  var response = this.response.text;
		  //We need to split the responses
		  nameValue = response.split('~');
		  var j=0;
		  //testselect.options[j] = new Option('','');
		  j++;
		  for(i=0;i<nameValue.length-2;i=i+2)
		  {
			select.options[j] = new Option(nameValue[i+1],nameValue[i]);
			if(selectedValue == nameValue[i])
			{
				select.options[j].selected = true;
			}
			j++;
		  }
		},
		onFailure: function(){  }
	  }).request();
}

function displayExitPage( target )
{
  var mainContent = document.getElementById( 'content_area' );
  mainContent.innerHTML = '<div id="sub_content"><h1>You Are Now Leaving Wyeth.com</h1>' +
  						'<div class="clear"></div><p>You are leaving <a href="http://www.wyeth.com/">www.Wyeth.com</a>, the Web site for Wyeth. Links to all outside sites are '+	
						'provided as a resource to our visitors.  Wyeth accepts no responsibility for the content of other sites.</p><p><a href="'+ target + '" ' +
						'target="_new">Continue</a> &gt;&gt;</p>'+
  						'</div>';	
  return false;
}

function CreateExcelSheet(table, hide)
{


var x=table.rows;
var xls = new ActiveXObject("Excel.Application")
xls.visible = true;
xls.Workbooks.Add;
var rowCount = 0;
 for (i = 0; i < x.length; i++)
 {
 
 if ( i == 0 && hide == true )
 {
   continue;
 }
 
 if(x[i].style.display != "none")
 {
 rowCount++;
 var y = x[i].cells

 for (j = 0; j < y.length; j++)
 {

 xls.Cells( rowCount, j+1).Value = y[j].innerText
 }
 }

 }
}

function popup(url) {
	var newwindow;
	newwindow = window.open(url,'PopupWin',"resizable=no,status=no,menubar=no,scrollbars=no,toolbar=no,width=750, height=511")
}

function popup_window(url) {
 window.open(url,'_blank',"resizable=no,status=no,menubar=no,scrollbars=no,toolbar=no,width=400, height=350")
}

function popup_flex(height,url) {
 window.open(url,'_blank',"resizable=no,status=no,menubar=no,scrollbars=no,toolbar=no,width=400, height="+height)
}

function popup_superflex(width,height,url) {
 newWin = window.open(url,'_blank',"'resizable=no,status=no,menubar=no,scrollbars=yes,toolbar=no,width="+width+",height="+height)
 newWin.moveTo(0,0)
}


var tableFilterRow;
var globalTable;
function attachFilter(table, filterRow)
{
	table.filterRow = filterRow;
	globalTable = table;
	tableFilterRow = table.filterRow;
	// Check if the table has any rows. If not, do nothing
	if(table.rows.length > 0)
	{
		// Insert the filterrow and add cells whith drowdowns.
		var filterRow = table.insertRow(table.filterRow);
		for(var i = 0; i < table.rows[table.filterRow + 1].cells.length; i++)
		{
			var c = document.createElement("TH");
			table.rows[table.filterRow].appendChild(c);
			var opt = document.createElement("select");
			opt.onchange = filter;

			c.appendChild(opt);
		}
		// Set the functions
		table.fillFilters = fillFilters;
		table.inFilter = inFilter;
		table.buildFilter = buildFilter;
		table.showAll = showAll;
		table.detachFilter = detachFilter;
		table.filterElements = new Array();
		
		// Fill the filters
		table.fillFilters();
		table.filterEnabled = true;
	}
}

function showHideFilter()
{
	if( globalTable.rows[tableFilterRow].style.display == "none")
	{
		globalTable.rows[tableFilterRow].style.display = "";
	}
	else
	{
		globalTable.rows[tableFilterRow].style.display ="none";
	}
}


function detachFilter()
{
	if(this.filterEnabled)
	{
		// Remove the filter
		this.showAll();
		this.deleteRow(this.filterRow);
		this.filterEnabled = false;
	}
}

// Checks if a column is filtered
function inFilter(col)
{
	for(var i = 0; i < this.filterElements.length; i++)
	{
		if(this.filterElements[i].index == col)
			return true;
	}
	return false;
}

// Fills the filters for columns which are not fiiltered
function fillFilters()
{
	for(var col = 0; col < this.rows[this.filterRow].cells.length; col++)
	{
		if(!this.inFilter(col))
		{
			this.buildFilter(col, "All");
		}
	}
}

// Fills the columns dropdown box. 
// setValue is the value which the dropdownbox should have one filled. 
// If the value is not suplied, the first item is selected
function buildFilter(col, setValue)
{
	// Get a reference to the dropdownbox.
	var opt = this.rows[this.filterRow].cells[col].firstChild;
	
	// remove all existing items
	while(opt.length > 0)
		opt.remove(0);
	
	var values = new Array();
		
	// put all relevant strings in the values array.
	for(var i = this.filterRow + 1; i < this.rows.length; i++)
	{
		var row = this.rows[i];
		if(row.style.display != "none" && row.className != "noFilter")
		{
			values.push(row.cells[col].innerHTML);
		}
	}
	values.sort();
	
	//add each unique string to the dopdownbox
	var value;
	for(var i = 0; i < values.length; i++)
	{
		if(values[i] != value)
		{
			value = values[i];
			opt.options.add(new Option(values[i], value));
		}
	}

	opt.options.add(new Option("All", "All"), 0);

	if(setValue != undefined)
		opt.value = setValue;
	else
		opt.options[0].selected = true;
}

// This function is called when a dropdown box changes
function filter()
{
	var countOfRowsNotVisible = 0;
	var table = this; // 'this' is a reference to the dropdownbox which changed
	while(table.tagName.toUpperCase() != "TABLE")
		table = table.parentNode;

	var filterIndex = this.parentNode.cellIndex; // The column number of the column which should be filtered
	var filterText = table.rows[table.filterRow].cells[filterIndex].firstChild.value;
	
	// First check if the column is allready in the filter.
	var bFound = false;
	
	for(var i = 0; i < table.filterElements.length; i++)
	{
		if(table.filterElements[i].index == filterIndex)
		{
			bFound = true;
			// If the new value is '(all') this column is removed from the filter.
			if(filterText == "All")
			{
				table.filterElements.splice(i, 1);
			}
			else
			{
				table.filterElements[i].filter = filterText;
			}
			break;
		}
	}
	if(!bFound)
	{
		// the column is added to the filter
		var obj = new Object();
		obj.filter = filterText;
		obj.index = filterIndex;
		table.filterElements.push(obj);
	}
	
	// first set all rows to be displayed
	table.showAll();
	
	// the filter ou the right rows.
	for(var i = 0; i < table.filterElements.length; i++)
	{
		// First fill the dropdown box for this column
		table.buildFilter(table.filterElements[i].index, table.filterElements[i].filter);
		// Apply the filter
		for(var j = table.filterRow + 1; j < table.rows.length; j++)
		{
			var row = table.rows[j];
			
			if(table.style.display != "none" && row.className != "noFilter")
			{
				if(table.filterElements[i].filter != row.cells[table.filterElements[i].index].innerHTML)
				{
					row.style.display = "none";
				}
				else
				{
					
				}
			}
		}
	}
	// Fill the dropdownboxes for the remaining columns.
	table.fillFilters();
    var rowsvisible = table.rows.length-3;
    for ( var i = 3; i < table.rows.length; i++)
    {
      if ( table.rows[ i ].style.display == 'none' )
      {
        rowsvisible = rowsvisible - 1;
      }
    }
	
  document.getElementById("totrows_span_tb2").innerHTML = rowsvisible;
	//showTotal( );
	showSurveyScale( filterText );
}

function showSurveyScale( filterText )
{
   var s = document.getElementById('survey_scale');   
   if ( s != null ) 
   {
   
	   if ( filterText != null && filterText != 'All' && filterText.indexOf('|') <= 0 ) 
	   {
		new Ajax('/irj/servlet/prt/portal/prtroot/com.wyeth.vsb.training.VSBTrainingServlet?surveyName='+filterText,
		  {		
			method:'get',
			onComplete: function()
			{
			  var response = this.response.text || "no response text";		  
			  document.getElementById('survey_scale').innerHTML = '<img src='+response+'/>' + '<br/>';
			},
			onFailure: function(){ alert('Something went wrong...') }
		  }).request();   	
	   }
	   else
	   {
	   document.getElementById('survey_scale').innerHTML = '';
	   }
   }
   return false;
   
}


function showTotal( )
{
   	table = document.getElementById('tbl');
	selectedRow = 0;
	  var correctAnswers = 0;
	  var incorrectAnswers = 0;
	  var percentCorrect = 0;	
	  var totalResponse = 0;
	for(var j = table.filterRow + 1; j < table.rows.length; j++)
	{
		var row = table.rows[j];
		
		if(row.style.display !="none")
		{
		  selectedRow++;
		  
		  if ( document.getElementById("quizstatus") )
		  {
			  correctAnswers += ( row.cells[3].innerHTML ) * ( row.cells[4].innerHTML ) / ( 100 );
			  totalResponse += (row.cells[4].innerHTML * 1 );
		  }
		}
	}	
	correctAnswers = Math.round( correctAnswers );
	incorrectAnswers = totalResponse - correctAnswers;
	document.getElementById("rowcount").innerHTML = 'Total Rows : '+ selectedRow;
	if ( document.getElementById("quizstatus") )
	{
	  
	  var quiztext = '<br/> Correct Answers: ' + correctAnswers + '<br/> InCorrect Answers: ' + incorrectAnswers + '<br/> Percentage Correct: ' + Math.round( (correctAnswers/totalResponse)*100 );	
	  
	  document.getElementById("rowcount").innerHTML = 'Total Rows : '+ selectedRow + quiztext;
	}

}


function showAll()
{
	for(var i = this.filterRow + 1; i < this.rows.length; i++)
	{
		this.rows[i].style.display = "";
	}
}
/** Email Validation **/
function echeck(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    return false
		 }

 		 return true					
	}


/* Star Rating Code Begin */
var set=false;
loadStars();
var star1;
var star2;
var star3;
var star4;
var currentRating=0;
function loadStars()
{
star1 = new Image();
star1.src = "/resources/shared/images/socialize/article-star-off-left.gif";
star2 = new Image();
star2.src= "/resources/shared/images/socialize/article-star-off-right.gif";
star3 = new Image();
star3.src= "/resources/shared/images/socialize/article-star-on-left.gif";
star4 = new Image();
star4.src= "/resources/shared/images/socialize/article-star-on-right.gif";
}

function lightOn(x)
{
if (set==false)
    {
        for (i=1;i<=x;i++)
        {
            if ( i%2 == 0 )
            {

              document.getElementById(eval(i)).src= star4.src;
            }
            else
            {
              document.getElementById(eval(i)).src= star3.src;
            }
        }
    document.getElementById('vote').innerHTML= x/2 + ' stars';
    }

}
function lightOff(x)
{
if (set==false)
    {
    for (i=1;i<=x;i++)
        {
            if ( i%2 == 0 )
            {
              document.getElementById(eval(i)).src= star2.src;
            }
            else
            {
              document.getElementById(eval(i)).src= star1.src;
            }

        }
    }
    document.getElementById('vote').innerHTML= '';
}
function setStar(x)
{
if (set==false)
    {
        for (i=1;i<=x;i++)
        {
            if ( i%2 == 0 )
            {
              document.getElementById(i).src= star4.src;
            }
            else
            {
              document.getElementById(i).src= star3.src;
            }
        }
    set=true;
    document.getElementById('vote').innerHTML="Thank you for your vote! - " + x/2;
    updatePageRating( document.location.href, x )
    }
}

function displayStar(x)
{               
        for (i=1;i<=x;i++)
        {
            if ( i%2 == 0 )
            {
              document.getElementById( ''.concat('a').concat(i) ).src= star4.src;
            }
            else
            {
              document.getElementById( ''.concat('a').concat(i) ).src= star3.src;
            }
        }
}


function updatePageRating( pageUrl, x )
{
	var d = new Date();
    new Ajax('/irj/servlet/prt/portal/prtroot/com.wyeth.pagerating.ContentRatingServlet?pageUrl='+escape(pageUrl)+'&rating='+x/2+'&pageTitle='+document.title+'&rand='+d.getTime(),
      {
        method:'get',       
        onSuccess: function(transport){
          var response = transport || "no response text";         
        },
        onFailure: function(){
         }
      }).request( );
}

function getStarRating ( )
{
    var pageUrl = document.location.href;
    var d = new Date();
    
    new Ajax('/irj/servlet/prt/portal/prtroot/com.wyeth.pagerating.ContentRatingServlet?pageUrl='+pageUrl+'&action=rating&rand='+d.getTime(),
      {
        method:'get',       
        onSuccess: function(transport)
        {

 	  var a = transport.split(" "); 	  
          var rating = a[0];             
          currentRating = rating*2;          
          displayStar( rating*2 );
	  document.getElementById('reviews').innerHTML=a[1];
        },
        onFailure: function(){
         }
      }).request( );
    
}
/* Star Rating Code End */

function updatePageReadCount() {
    var d = new Date();
    pageUrl = document.location.href;
    new Ajax('/irj/servlet/prt/portal/prtroot/com.wyeth.pagerating.ContentRatingServlet?pageUrl='+escape(pageUrl)+'&action=readCount&pageTitle='+document.title+'&rand='+d.getTime(),
      {
        method:'get',       
        onSuccess: function(transport){
          var response = transport || "no response text";         
        },
        onFailure: function(){
         }
      }).request( );
}
