// 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.
*/

//This function submits the Login form by updating the Hidden values.
function submitLoginForm(form) {
	form.action=authenticationURL;
	form.successurl.value=authenticationSucessURL;
	form.failureurl.value=authenticationFailureURL;
	form.submit();
}

function forgotPassword() {
	window.open(forgotPasswordURL,'_blank');
}



    
    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();
        //invokeLogOff( );
        //document.location.href='/irj/servlet/prt/portal/prtroot/com.wyeth.security.auth.HCPLogoff?v='+random
        document.location.href=logoffUrl+'&rand='+random;

    }

    function invokeLogOff()
    {
        var date = new Date();
        var random  = ''+date.getDate()+date.getHours()+''+date.getMinutes()+''+date.getSeconds();    
    new Request(
      {       
        url :logoffUrl+'&rand='+random,
        method:'get',
        onComplete: function(){               
        },
        onFailure: function(){  }
      }).send();                
    }

//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 Request(
  {    
    url :'/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(){  }
  }).send();
 
  
}

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;
}














/*    
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 Request(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(){  }
  }).send( ); 

return false;
}

function loadSiteMap( )
{
  
  new Request(
  {
    url:'/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(){  }
  }).send( ); 
}

function loadContactUs()

{

  new Request(
  {
    url:'/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(){  }
  }).send( ); 


}

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 Request(
      {
        url:'/irj/servlet/prt/portal/prtroot/com.wyeth.lookup.DataSet?name='+lookupName,
        method:'get',
        onSuccess: function(responseText, responseXML) {
          var response = responseText;
          //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++;
          }
        }
        
      }).send();
     
     
}

function displayExitPage( target )
{
  var mainContent = document.getElementById( 'content_area' );
  mainContent.innerHTML = '<div id="sub_content"><h1>You Are Now Leaving PfizerPro.com</h1>' +
                        '<div class="clear"></div><p>You are leaving <a href="http://www.pfizerpro.com/">www.PfizerPro.com</a>. Links to all outside sites are provided as a resource to our visitors.  Pfizer 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 Request('/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...') }
          }).send();     
       }
       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 Request(
      {
        url:'/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(){
         }
      }).send( );
}

function getStarRating ( )
{
    var pageUrl = document.location.href;
    var d = new Date();
    
    new Request(
      {
        url:'/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(){
         }
      }).send( );
    
}
/* Star Rating Code End */

function updatePageReadCount() {
    window.addEvent('domready',function(){
    pageUrl = document.location.href;
    
    new Request(
      {
      	url:'/irj/servlet/prt/portal/prtroot/com.wyeth.pagerating.ContentRatingServlet?pageUrl='+escape(pageUrl)+'&action=readCount&pageTitle='+document.title,
        method:'get'       
      }).send( );
      });
}



//To change the target of the Left Hand Nav for tradePolicy
if(document.location.href.match("/prescription$") || document.location.href.match("/authorized_distributors$") ||
	document.location.href.match("/prescription_hcp$") || document.location.href.match("/authorized_distributors_hcp$")) {
    window.addEvent('domready', function() {
    $$('div$ter_nav li a[href$=/products/prescription/tradepolicy]')[0].set('target','_blank');
    })
}


function generateNavigationTabs(tabs, activeTab){
	if(activeTab == undefined){
		activeTab = 1;
	}
	
	tabUL = new Element('ul');
	if(tabs){
		//  Create an LI element for each tab
		tabs.each(function(tab, index){
			tabLI = new Element('li');
			tabLink = new Element('a', {
				'href' : tab[1],
				'html' : tab[0]  
			});
			tabLI.adopt(tabLink);

			if(index == activeTab){
				tabLI.addClass('active');
			}
			
			tabUL.adopt(tabLI);
		});
		
		$('tabbedNavigation').adopt(tabUL);
	}
}

function generateProductNavigationTabs(productDirectory, activeTabs, currentTab){
	//  This was causing the 10th tab to be displayed first
	//	activeTabs.sort();

	productTabs = [
		['Indication &amp; Important<br/>Safety Information', 'indication.html'],
		['Scientific<br/>Literature', 'scientific-resources.html'],
		['Professional<br/>Resources', 'professional-resources.html'],
		['Patient<br/>Education', 'patient-resources.html'],
		['Condition<br/>Information', 'condition-information.html'],
		['Product<br/>Summary', 'additional-information.html'],
		['Product<br/>Overview', productDirectory+'_overview.html'],
		['Prescribing<br/>Information', 'prescribing-information.html'],
		['Patient<br/>Information', 'patient-information.html'],
		['Patient<br/>Support', 'patient-support.html'],
		['Important Safety<br/>Information', 'important-safety-information.html'],
		['Reimbursement<br/>Support', 'reimbursment-support-program.html']
	];

	tabs = [];
	for(i = 0; i < activeTabs.length; i++){
		tabNumber = activeTabs[i];
		
		if(tabNumber == currentTab){
			currentTab = i;
		}
		
		tab = [];
		tab[0] = productTabs[tabNumber][0];
		tab[1] = '?product=/wyeth_html/home/products/prescription/'+productDirectory+'/'+productTabs[tabNumber][1];
		
		tabs.push(tab);
	}

	generateNavigationTabs(tabs, currentTab);
}

window.addEvent('domready', function(){

//This is a fix to remove all the (Customize) Links that appear next to the PDFs as was transported by the 
//Old .net PfizerPro application
$$('a[href$="Default.aspx"]').each(
	function(item) {
		if(item.innerHTML.trim() == '(Customize)')
		{
			item.setStyle('display','none')	
		}
	})
	

//Other Dom Ready events can be added here.	
});

//This function is used for Content Filtering
function filterBySection (section) {
		fx = new Fx.Slide($('items_list'));
		
		fx.hide();
		$$('.pi_box_content_bullet_title').setStyle('display','none');	
		$$('.'+section).each(function(item) {
			item.setStyle('display','block');
		});		
		fx.slideIn().show();
		
}


function popup_window(url) {
	window.open(url,'_blank',"resizable=no,status=no,menubar=no,scrollbars=no,toolbar=no,width=425, 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)
}
function popup_flash(width,height,url) {
	var x = 0, y = 0; // default values

	if (document.all) {
		x = window.screenTop + 10;
		y = window.screenLeft + 10;
	} else if (document.layers) {
		x = window.screenX + 10;
		y = window.screenY + 10;
	}

	var popup = window.open(url,'_blank',"'resizable=no,status=no,menubar=no,scrollbars=yes,toolbar=no,width="+width+",height="+height+"top="+y+",screenY="+y+",left="+x+",screenX="+x);
	popup.moveTo(0,0);
}
function TrimString(sInString)
{
	sInString = sInString.replace( /^\s+/g, ""); // strip leading
	return sInString.replace( /\s+$/g, ""); // strip trailing
}

//session timeout
var sessionTimeout = function()
{  
	var date = new Date();
	var random  = ''+date.getDate()+date.getHours()+''+date.getMinutes()+''+date.getSeconds();
	removeLitRequestCookies();	
	new Request(
	  {    
	    url :'/irj/servlet/prt/portal/prtroot/com.wyeth.security.auth.HCPLogoff?v='+random,
	    method:'get',
	    onComplete: function(){	      	      
	    },
	    onFailure: function(){  }
	  }).send();        
}



window.addEvent('domready',function(){
  sessionTimeout.delay(1800000); //delay seconds in milli
});

//empty impl
function hideAutoExpandedDiv()
{
}