/*** Graceful degrade for non-javascript users & some event capture for livesearch ***/

window.onload = addscript; // Graceful degrade stuff for non-javascript users
document.onclick = hidelivesearch; // Onclick capturing for closing live search box

function addscript() {
	// check to see that the browser supports the getElementById method
	if (!document.getElementById) {
		return false; 
	} else {
	  if (document.getElementById('countriesanchor')) { document.getElementById('countriesanchor').href = "#"; }  // Replace conventional url in countries footer link
		if (document.getElementById('searchfield')) { document.getElementById('searchfield').value= " Search"; }
		if (document.getElementById('popupclose')) { document.getElementById('popupclose').innerHTML = "<a href='#' target='_self' onclick='window.close();'>close window <img src='images/login/ajaxclose.gif' border='0' alt='close window' /></a>"; } //Add close window link for popup template
	}
}
	
function openpopup() {
	//window.open(linkURL,'popup','width=' + w +',height=' + h);
	window.open('popup.html','popup','width=500,height=500');
}


/*** START Primary nav hover function for IE ***/

sfHover = function() {
	var sfEls = document.getElementById("nav").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);

/*** START Countries selector ***/

// Preload the AJAX loading gif
ajaxgif=new Image();
ajaxgif.src="images/login/ajaxload.gif";

function countriesreveal() { // Show, hide or add to territory selector box
	document.getElementById('countriesbox').style.visibility = 'visible';
	
  // Set the static lists (no longer ajax)
	document.getElementById('countriesboxhead').innerHTML = "";
	var countriesheader="<div id='countriestitle'>Commonly visited PwC sites</div><br clear='all' />";

	document.getElementById('countriescontents').innerHTML = "";
  var countriesoutput="<table id='countriestable' border='0'><tbody><tr><td><ul class='countrylist'><li><a href='http://www.pwc.com/gx/en/index.jhtml?ld=no'>Global</a></li><li><a href='http://www.pwc.com/au/en'>Australia</a></li> <li><a href='http://www.pwc.com/br/pt'>Brazil</a></li> <li><a href='http://www.pwc.com/ca/en'>Canada</a></li> <li><a href='http://www.pwccn.com'>China</a>&nbsp;/&nbsp;<a href='http://www.pwchk.com'>Hong Kong</a></li> <li><a href='http://www.pwc.fr'>France</a></li> <li><a href='http://www.pwc.de'>Germany</a></li> <li><a href='http://www.pwc.com/in/en'>India</a></li></ul></td><td><ul class='countrylist'><li><a href='http://www.pwc.com/it/it'>Italy</a></li> <li><a href='http://www.pwcjp.com/e/index.html'>Japan</a></li> <li><a href='http://www.pwc.com/mx/es'>Mexico</a></li><li><a href='http://www.pwc.com/m1/en'>Middle East</a></li> <li><a href='http://www.pwc.com/nl/nl'>Netherlands</a></li> <li><a href='http://www.pwc.com/ru/ru'>Russia</a></li> <li><a href='http://www.pwc.com/sg/en'>Singapore</a></li> <li><a href='http://www.pwc.com/za/en'>South Africa</a></li></ul></td><td valign='top'><ul class='countrylist'><li><a href='http://www.pwc.com/kr/ko'>South Korea</a></li> <li><a href='http://www.pwc.com/es/es'>Spain</a></li> <li><a href='http://www.pwc.com/se/sv'>Sweden</a></li> <li><a href='http://www.pwc.ch'>Switzerland</a></li> <li><a href='http://www.pwc.co.uk'>United Kingdom</a></li> <li><a href='http://www.pwc.com/us/en'>United States</a></li> </ul> </td></tr></tbody></table><br clear='all'> <p style='text-align: right; font-weight: bold;'><a href='http://www.pwc.com/gx/en/site-index.jhtml'>Complete list of PwC territory sites</a></p><br clear='all' />";
	
	// Finally write the output; close button, header & contents.
	document.getElementById('countriesboxclose').innerHTML = "<a href='#' onClick='countrieshide(); return false;'><img src='images/login/ajaxclose.gif' alt='Close' border='0' id='countriesclosebutton' /></a>"
	document.getElementById('countriesboxhead').innerHTML = countriesheader;
	document.getElementById('countriescontents').innerHTML = countriesoutput;
}


function countrieshide() { 	// Clear the contents of the box and hide the div
	document.getElementById('countriescontents').innerHTML = "";  
	document.getElementById('countriesbox').style.visibility = 'hidden';  
}

/*** START Live search ***/

var xmlHttp
	
function showResult(str) {
	// Clear the suggestions box when no chars
	if (str.length<=minchars) {
		document.getElementById("livesearch").innerHTML="";
		document.getElementById("livesearch").style.visibility="hidden";
		return
	}
	if (livesearchon!="true") {
		return
	}
	
	// Place the AJAX loading gif. Replaced with the clear icon after the request is complete (below)
	document.getElementById("livesearchbutton").src="images/login/ajaxload.gif";
	document.getElementById("livesearchbutton").className="";
	
	xmlhttp=null;
	url = suggestionsfile; // Suggestions xml file taken from local.js

	if (window.XMLHttpRequest) {// code for IE7, Firefox, Mozilla, etc.
		xmlhttp=new XMLHttpRequest();
	}
	else if (window.ActiveXObject) {// code for IE5, IE6
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	if (xmlhttp!=null) {
		xmlhttp.onreadystatechange=processsearch;
		xmlhttp.open("GET",url,true);
		xmlhttp.send(null);
	}
	else {
		//alert("Your browser does not support XMLHTTP.");
		clearlivesearch();
		return;
	}
}

function processsearch() { // Check if file is valid & if so do something with its contents

	// Take the current search string
	var str = document.getElementById("searchfield").value.toLowerCase();

	// Break the loop when http call is complete or there's an error
	if(xmlhttp.readyState!=4) return;
	if(xmlhttp.status!=200) {
		//alert("Problem retrieving XML data");
		clearlivesearch();
		return;
	}

	// Locate the link element to traverse
	x=xmlhttp.responseXML.documentElement.getElementsByTagName("link");
	var searchoutput = "";
	var searchoutputheader = "<div id='livesearchheader'>Recommended results</div>";
	var searchoutputfooter = "<div id='livesearchfooter'><a href='#'>View all results >></a></div>"; 
	if (str.length > minchars) {

		// Loop through all link elements
		for (i=0;i<x.length;i++) {

			xtitles=x[i].getElementsByTagName("title");
			xurls=x[i].getElementsByTagName("url"); {
			try {
				// The magic of string matching (must be lowercare)
				var testquery = xtitles[0].firstChild.nodeValue.toLowerCase();
				if (testquery.indexOf(str) !=-1) {
					searchoutput = searchoutput + "<a href='" + xurls[0].firstChild.nodeValue + "'>" + xtitles[0].firstChild.nodeValue + "</a><br />";
				} else {
					searchoutput = searchoutput + "";
				}
			}
				catch (er) { searchoutput = searchoutput + ""; }
			}				
		}

	}

	if (searchoutput=="") { 
		// Collapse the suggestions box when no matches & halt the ajax loading gif
		document.getElementById("livesearch").style.visibility="hidden";
		document.getElementById("livesearchbutton").src="images/login/ajaxclose.gif"; // Show the close button, replacing the ajax gif
		document.getElementById("livesearchbutton").className="livesearchclose";
	} else {
		// Return the response, only when xml http call is done. Show the close button, replacing the ajax gif
		if (xmlhttp.readyState==4 || xmlhttp.readyState=="complete") { 
			document.getElementById("livesearch").style.visibility="visible";
			document.getElementById("livesearch").innerHTML=searchoutputheader + searchoutput + searchoutputfooter;
			document.getElementById("livesearchbutton").src="images/login/ajaxclose.gif";
			document.getElementById("livesearchbutton").className="livesearchclose";
		} 
	}

}

function clearsearch() { //Clear from initial focus
	document.getElementById("searchfield").value="";
}

function clearlivesearch() { // Clear from the button & also hide the button
	document.getElementById("searchfield").value=" Search";
	document.getElementById("livesearch").innerHTML="";
	document.getElementById("livesearch").style.visibility="hidden";
	document.getElementById("livesearchbutton").src="/images/login/tran.gif";
	document.getElementById("livesearchbutton").className="";
}

// Hide the livesearch box on a click outside its div
function hidelivesearch(evt) {
    try {
        evt = evt || window.event;
        var targ = evt.target || evt.srcElement;

	    // If the livesearch box is open, clear it
	    if (targ.id=="livesearch" || targ.id=="livesearchheader" || targ.id=="livesearchfooter" || targ.id=="searchsubmit") {
		    return;
	    } else {
	        if (document.getElementById("livesearch") != null) {
		        if (document.getElementById("livesearch").style.visibility=="visible") {
			        clearlivesearch();
		        }
		    }
	    }
	}
    catch (e) { }
}

/** TCS from prod, dated 12/15/2009 	**/
/** 					**/

/*** START Send & share global defaults ***/

	function writesharelink() {
		document.write("<li><a href='#' target='_self' class='shareicon' onclick='shareboxreveal(); return false;'><img src='/images/login/share.gif' alt='' border='0'>Share</a></li>");
	}

	// Icon, Pre-URL, Post-URL, Description/alt tag, Onlick. Only declare them if they don't already exist from local.js

	if (arr_ss [0] === undefined) {
		// Linkedin
		arr_ss [0] = new Array()
		arr_ss [0][0] = "/en_GX/webadmin/assets/image/share_linked.gif";
		arr_ss [0][1] = "http://www.linkedin.com/shareArticle?mini=true&url=" + escape(window.location);
		arr_ss [0][2] = ""; // E.G. arr_ss [0][2] = "&param=something";
		arr_ss [0][3] = "Linkedin";
		arr_ss [0][4] = "";
	}

	if (arr_ss [1] === undefined) {
		// Facebook
		arr_ss [1] = new Array()
		arr_ss [1][0] = "/en_GX/webadmin/assets/image/share_facebook.gif";
		arr_ss [1][1] = "http://www.facebook.com/share.php?u=" + escape(window.location);
		arr_ss [1][2] = "";
		arr_ss [1][3] = "Facebook";
		arr_ss [1][4] = "";
	}
	
	if (arr_ss [2] === undefined) {
		// Mixx
		arr_ss [2] = new Array()
		arr_ss [2][0] = "/en_GX/webadmin/assets/image/share_mixx.gif";
		arr_ss [2][1] = "http://www.mixx.com/submit?page_url=" + escape(window.location);
		arr_ss [2][2] = "";
		arr_ss [2][3] = "Mixx";
		arr_ss [2][4] = "";
	}

	if (arr_ss [3] === undefined) {
		// Digg
		arr_ss [3] = new Array()
		arr_ss [3][0] = "/en_GX/webadmin/assets/image/share_digg.gif";
		arr_ss [3][1] = "http://digg.com/submit?phase=2&url=" + escape(window.location);
		arr_ss [3][2] = "";
		arr_ss [3][3] = "Digg";
		arr_ss [3][4] = "";
	}

	if (arr_ss [4] === undefined) {
		// Yahoo! Buzz
		arr_ss [4] = new Array()
		arr_ss [4][0] = "/en_GX/webadmin/assets/image/share_yahoobuzz.gif";
		arr_ss [4][1] = "http://buzz.yahoo.com/buzz?targetUrl=" + escape(window.location);
		arr_ss [4][2] = "";
		arr_ss [4][3] = "Yahoo! Buzz";
		arr_ss [4][4] = "";
	}

	function shareboxreveal() { // Show, hide or add to territory selector box
		document.getElementById('sharebox').style.display = 'block';
	}

	function shareboxhide() { 	// Clear the contents of the box and hide the div
		document.getElementById('sharebox').style.display = 'none';  
	}

  // Default R2 forms validation message (translatable))
  if (formvalidationmsg === undefined) { var formvalidationmsg = "Please complete the highlighted fields"; }
  
/*** START Lightweight browser detection ***/

//alert(BrowserDetect.browser + ' ' + BrowserDetect.version + ' on ' + BrowserDetect.OS);

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

// ############### START EMAIL A COLLEAGE FUNCTIONS #######################
// Name -- emailpage
//Author: Roger Darus/E Solutions
//Additional Editors: Roger Darus/E Solutions
//Additional Editors: Sirnjeet Kalwan
// Description of code -- Form input validation and window opener
function inputValidation(form){
	var errorText;
	// Valid friends email
	errorText = form.ValidationField1.value;
	 if ( !validEmailMulti( form.friendsEmail.value ) ){
		alert(errorText);
		form.friendsEmail.focus();
		return;
	}
	//Validate name
	errorText = form.ValidationField2.value;
	if (form.name.value == ""){
		alert(errorText);
		form.name.focus();
		return;
	}
	//Validate users email address
	errorText = form.ValidationField3.value;
	 if ( !validEmail( form.yourEmail.value ) ){
		alert(errorText);
		form.yourEmail.focus();
		return;
	}
	form.submit();
}
function validEmail( email ){
	var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
	var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,6}|[0-9]{1,3})(\]?)$/; // valid
	return ( !reg1.test( email )  && reg2.test( email ));
}
function removeSpaces(string) {
	var tstring = "";
	string = '' + string;
	splitstring = string.split(" ");
	for(i = 0; i < splitstring.length; i++)
	tstring += splitstring[i];
	return tstring;
}
function validEmailMulti( email ){
	email = removeSpaces(email);
	var final = 0;
	while (final == 0) {
		comma = email.indexOf(",");
		if (comma == -1) {
			final = 1;
			currentemail = email
		} else {
			currentemail = email.substring(0, comma);
			email = email.substring(comma + 1, email.length);
		}
		returncode = validEmail( currentemail );
		if (!returncode) {
			return false;
		}
		if (final == 1) {
			return true;
		}
	}
}
// ############### END EMAIL A COLLEAGE FUNCTIONS #######################

// START RVP JS

// This function replaces characters to be displayed back to the browser with xss safe characters
function removeSpecialChars(input) {
var output = "";
var char="";
for (count = 0 ; count < input.length ; count ++) {
	switch (input.charAt(count)) {
		case "<":
			output = output + "&#60";
			break;
		case ">":
			output = output + "&#62";
			break;
		case '"':
			output = output + "&#34";
			break;
		case "'":
			output = output + "&#39";
			break;
		case ")":
			output = output + "&#41";
			break;
		case "(":
			output = output + "&#40";
			break;
		case "+":
			output = output + "&#43";
			break;
		case "&":
			output = output + "&#38";
			break;
		case ";":
			output = output + "&#59";
			break;
		default:
			output = output + input.charAt(count);
			break;
	}
}
return output;
} // End removeSpecialChars(input)
var aRVP  = new Array();
var sRVPBoxTitle =  '<span class="RVPTitle">Recently Visited Pages</span>';
var sRVPCookieText = '<div class="RVPOffMessage">Please enable cookies on your browser to activate this functionality.</div><ul><li><a href="/gx/en/main/privacy/index.html" target="_self" title="Privacy">Privacy</a></li></ul>';
var cookieDomain = "";
if( window.location.host.indexOf(".pwc.com") == -1 ){
	cookieDomain = "";
} else {
	cookieDomain = "; domain=pwc.com";
}
document.cookie = "PwC=PwC; path=/" + cookieDomain;
var cookieenabled = (document.cookie.indexOf("PwC=") != -1) ? true : false
//checks if current page needs to be recorded in the cookie
function processRVP()
{
     var pos;
  
  // checks if cookies are enabled
  if (!(cookieenabled)) {return;}
 
 //read cookie and load global array
  readRVPCookie();
   
   //check for the indicator to record this url
   // 0 = not to record; any value = record
   if (readMetaTag("RVPFlag") == "0")  return; 
  
   // check for # sign followed by any
       var tUrl = document.location.href;
       if (tUrl.indexOf('#') != -1) {tUrl = tUrl.substring(0,tUrl.indexOf('#')); }
        
   if (!(recentRVP(tUrl)))
   {
     
       // get link description
      var sRVPTitle = readMetaTag("RVPTitle");
      if (sRVPTitle == "") 
      {  
          //get title from <title> tag
         sRVPTitle = document.title;
          if (typeof sRVPTitle != "undefined")
          {
	             // searches for something like "..& PricewaterhouseCoopers:!## Test "
	             var mt = new RegExp(/^([^a-zA-Z0-9]*)PricewaterhouseCoopers([^a-zA-Z0-9]*)\s/i);
	             sRVPTitle = sRVPTitle.replace(mt,"");
           }
          else {sRVPTitle = "";}
      }
         
      //record values in the cookie 
     if ((sRVPTitle != "") && (typeof sRVPTitle != "undefined") && (sRVPTitle != "undefined"))
     { 
       var pageInfo = escape(tUrl) + "~~" + escape(sRVPTitle) + "~~_self~~0~~~" ;
        recordRVP(pageInfo);
       //repoopulate global array
       readRVPCookie();
     }
  
    }
 
}
  
// record in the cookie as requested
function processbyreqRVP(title,url,target)
{  
   // checks if cookies are enabled
   if (!(cookieenabled)) {return;}
  
   // checks if title and url are provided
   if ((title == "") || (url == "")) {return;}
  
   // check for # sign followed by any
       var tUrl = url;
       if (tUrl.indexOf('#') != -1) {tUrl = tUrl.substring(0,tUrl.indexOf('#')); }
        
   if (!(recentRVP(tUrl)))
   { 
     //record values in the cookie 
      if  ( (!(target)) || (target == '')) var pageInfo = escape(tUrl) + "~~" + escape(title) + "~~_blank~~1~~~" ;
      else var pageInfo = escape(tUrl) + "~~" + escape(title) + "~~" + target + "~~1~~~" ;
      recordRVP(pageInfo);
    
    //repoopulate global array
    readRVPCookie();
   }
   
 }
// record URL as most RVP in the cookie
function recordRVP(pageInfo)
{
   // checks if cookies are enabled
   if (!(cookieenabled)) {return;}
 
   var cookieSTR =  "RVPLinks=" + pageInfo;
   for (var i=0; i < aRVP.length; i++)
    { 
        if ((aRVP[i]) && (aRVP[i]  != "")) cookieSTR =  cookieSTR + aRVP[i] + "~~~";
        if (i >= 4) break; 
     }
   document.cookie = cookieSTR + ";path=/" + cookieDomain;
 }
// checks if URL is recorded as the most recent RVP
function recentRVP(url)
{
if ( (!(aRVP[0])) || (aRVP[0] == "") ) {return false;}
//checks first entry
var tRVP = aRVP[0].split("~~");
if (tRVP[0] == escape(url)) {return true;}
           
return false;
 }
// populate links for RVP box using cookie
function displayRVP()
{
 // checks if cookies are enabled and display appropriate message if cookies are disabled
 if (!(cookieenabled)) 
  {
document.write(sRVPCookieText);
return;
   }
   
 //display  links
    var parmArray = new Array();
    var hdr = 0;
    var j = 0;
    var urlStr;
    var tUrl;
   
    //display cookie contents
    if ((aRVP[0]) && (aRVP[0] != "") )
    {
       for (var i=0; i < aRVP.length; i++)
      {  
         if (aRVP[i])
        { 
            parmArray = aRVP[i].split("~~");
            if (i == 0) {
		           // check for # sign followed by any
		           tUrl = document.location.href;
		           if (tUrl.indexOf('#') != -1) {tUrl = tUrl.substring(0,tUrl.indexOf('#')); }
            }
            if ( (parmArray[1]) && (parmArray[0]) && ( (i > 0) || ( (i == 0)  && (!recentRVP(tUrl))) ))
            {
                // write header
                if (hdr == 0) {hdr = 1; document.write('<ul>');}
        
//	         urlStr = '<li><a href="' + unescape(parmArray[0]) + '"'; 
	         urlStr = '<li><a href="' + removeSpecialChars(unescape(parmArray[0])) + '"'; 
	                
		         // window target 
		         if ((parmArray[2]) && (parmArray[2] != 0))   {urlStr = urlStr + ' target="' + parmArray[2]  + '"';} 
		          
		        //check to see if this needs to be tagged to record in RVP 
		        if ((parmArray[3]) && (parmArray[3] == 1))  
		              {urlStr = urlStr + ' onClick="processbyreqRVP(\'' + unescape(parmArray[1]) + '\',\'' + unescape(parmArray[0]) + '\',\'' + parmArray[2] + '\');"';} 
		        tUrl = unescape(parmArray[1]).replace("<","&lt;"); 
                      tUrl = tUrl.replace(">","&gt;");
		        urlStr = urlStr + ' title="' + unescape(parmArray[1]) + '">' + tUrl +  '</a></li>';
		        document.write(urlStr);
		              
                 j = j + 1;
             }
             if (j >= 5) break;
          }
        }  //  end of for loop
if (hdr == 1) {document.write('</ul>');}
     }  
 
 }
// read cookie contents
function readRVPCookie()
{
var lnkStr = document.cookie;
var pos = lnkStr.indexOf("RVPLinks=");
if (pos == -1) return; 
// eliminate the text "PwC=PwC;RVPLinks=" from the string
lnkStr = lnkStr.substring(pos+9);
if (lnkStr.indexOf(";") > -1) {lnkStr = lnkStr.substring(0,lnkStr.indexOf(";"));}
//load  links in global array
aRVP = lnkStr.split("~~~");
}
// read meta tag for value
function readMetaTag(tagName)
{
  
  var content = "";
   
  // check for various browsers and versions  
 
  if (document.getElementById)   {  
        if (document.getElementById(tagName))  content = document.getElementById(tagName).content; 
     }
 else if (document.all) { 
        if (document.all[tagName])  content = document.all[tagName].content; 
     }  
 else if (document.layers) { 
        if (document.layers[tagName])  content = document.layers[tagName].content; 
     }
  
  return content;
  
}
//form validation
function ValidateandSubmit(){

var msgtxt = "";
var frmName = "";
var frm;

  if (document.getElementById)   {  
        frm = document.getElementById("_Notes");
     }
 else if (document.all) { 
         frm = document.all["_Notes"];
     }  
 else if (document.layers) { 
        frm = document.layers["_Notes"];
     }

if (frm != null)
{
	frmName = "_Notes";
}
else
{
	frmName = "_onlineForm";
}

var reqflds = document[frmName].ReqFields.value;
reqflds = reqflds.split(";");

var valType = document[frmName].ValidationType.value;
valType = valType.split(";");

var alrtVals = document[frmName].AlertValue.value;
alrtVals = alrtVals.split("@@");

var firstFocus;
var success = true;
var focusSet = 0;
var noOfLines = 0;
var fldval = "";


for(i=0;i<reqflds.length;i++)
{
  reqflds[i] = "document." + frmName + "." + reqflds[i];
}

for(i=0;i<reqflds.length;i++){
     
	if (valType[i] == "Text"){
		
		var fldval = eval(reqflds[i]).value;
		if(fldval == ""){
			msgtxt = msgtxt+"\n"+alrtVals[i];
			if (focusSet == 0) {firstFocus = eval(reqflds[i]); focusSet = 1; success = false;}
			}
	}

	else if(valType[i] == "Email"){
		var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
		var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,6}|[0-9]{1,3})(\]?)$/; // valid
		var fldval = eval(reqflds[i]).value;
		
		 if ( !reg1.test( fldval )  && reg2.test( fldval )) {
			}
		else{msgtxt = msgtxt+"\n"+alrtVals[i];}
									if (focusSet == 0) {firstFocus = eval(reqflds[i]); focusSet = 1; success = false};
	}

	else if(valType[i] == "Check/Radio"){
		var x = "";
		
		if (isNaN(eval(reqflds[i]).length)) {
		// Checkbox contains only one choice.
		if (eval(reqflds[i]).checked) {
			x = "pass";
		}
		}
		else{
		for (var r=0; r < eval(reqflds[i]).length; r++){
			if ( eval(reqflds[i])[r].checked){
				x = "pass";
			}
		}
		}
		if(x==""){
			msgtxt = msgtxt+"\n"+alrtVals[i];
			if (focusSet == 0) {firstFocus = eval(reqflds[i])[0]; focusSet = 1; success = false};
			}
	}

	else if(valType[i] == "Option"){
	
		var selection = "";
		var list = eval(reqflds[i]);
		selection = list.selectedIndex;
		
		if(selection ==0){
			msgtxt = msgtxt+"\n"+alrtVals[i];
			if (focusSet == 0) {firstFocus = eval(reqflds[i]); focusSet = 1; success = false};
			}
	}

	else if(valType[i] == "Option-Multi"){
	
		var selection = "";
		var list = eval(reqflds[i]);
		selection = list.selectedIndex;
		
		if(selection ==-1){
			msgtxt = msgtxt+"\n"+alrtVals[i];
			if (focusSet == 0) {firstFocus = eval(reqflds[i]); focusSet = 1; success = false};
			}
	}
}

if( msgtxt == ""){
document[frmName].submit();
}
else{
	alert(msgtxt);
	if(focusSet == 1) {
		firstFocus.focus();
	}
	}
}

processRVP();

// END RVP JS

// -----------------------------------------------------
// SAVE FORM FIELD SELECTIONS IN COOKIES                         
// @author: nerlijman001                           
// -----------------------------------------------------

var ONLINE_FORM_FIELD_SEPARATOR = '!@@';
var ONLINE_FORM_SEPARATOR = '\|@\|';
var ONLINE_FORM_MULTIVALUED_SEPARATOR = ';@';

//var ONLINE_FORM_FIELD_SEPARATOR = ';';
//var ONLINE_FORM_SEPARATOR = '\|';
//var ONLINE_FORM_MULTIVALUED_SEPARATOR = ',';

var EXPIRATION_DAYS = 365;
var MULTI_PREFIX = "_m_";

String.prototype.startsWith = function(s) {
	return (this.match("^"+s)==s);
}

//----------------------------
//TCS-R2
function getLotusForm() {
	var frmName = "";
	var frm;

	if (document._Notes) {
		frm = document._Notes;
	}
	if (document.forms) {
		frm = document.forms["_Notes"];
	}
	
	if (!frm) {
		if (document.all) { 
			frm = document.all["_Notes"];
		}
	}
	
	if (!frm) {	
		if (document.layers) {
			frm = document.layers["_Notes"];
		}	
	}

	if (!frm) {		
		if (document.getElementById) {
			frm = document.getElementById("_Notes");
		}
	}
	 
	if (frm != null) {
		return frm;
	}
	return document.getElementById('_onlineForm');
}

//TCS-R2
function getOnlineForm() {
    return getLotusForm();
}

//----------------------------
/*function getOnlineForm() {
	var o = document.getElementById('_onlineForm');
	return o;
}*/

function saveOnlineFormSelections() {
	var f = getOnlineForm();
	if (f) {
		saveSelections(f);
	}

}

function loadOnlineFormSelections() {
	var f = getOnlineForm();
	if (f) {
		if (f.name = '_Notes') {
			f.id = f.name;
		}
		loadSelections(f);
	}
}

function getExpirationDate() {
	var today = new Date();
	return new Date(today.getTime()+EXPIRATION_DAYS*24*60*60*1000);
}

// input1,value2
function saveSelections(frm) {
	var setvalue;
	var fieldType;
	var formname = frm.name;
	var items = new Array();

	var exp   = getExpirationDate();

	//var string = "formname=" + formname + ONLINE_FORM_SEPARATOR;
	var string = "";
	var cookieName = formname;

	var n = frm.length;
	for (i = 0; i < n; i++) {
		if (frm[i].name != '' && !items[frm[i].name]) {
			string+= getFieldStringValue(frm, frm[i].name, frm[i].type);
			items[frm[i].name] = frm[i].name;
		}
	}
	string=string.substring(0, string.length-ONLINE_FORM_SEPARATOR.length);
	setCookie(cookieName, string, exp); 
}

function removeLastSeparator(r, sep) {
	
}

function getFieldStringValue(frm, e, fieldType) {
    var index;
	var string = "";
	
	// RADIO BUTTON
	if (fieldType == "radio") {
		for (x=0; x < frm.elements[e].length; x++) {
			if (frm.elements[e][x].checked) {
				index = x;
			}
		}
		string+= e + ONLINE_FORM_FIELD_SEPARATOR + index + ONLINE_FORM_SEPARATOR;
	}

	// TEXT, TEXTAREA, and DROPDOWN
	if ((fieldType == "text") ||
		(fieldType == "textarea") ||
		(fieldType == "select-one")) {
		string+= e + ONLINE_FORM_FIELD_SEPARATOR + frm.elements[e].value + ONLINE_FORM_SEPARATOR;
	}

	// CHECKBOX o LIST
	if (fieldType == "checkbox" || fieldType == "select-multiple") {
		var setvalue = '';	
		if (frm.elements[e].length) {
			// is an array, save as multi valuated
			for (x=0; x < frm.elements[e].length; x++) {
				if (frm.elements[e][x].checked || frm.elements[e][x].selected) {
					setvalue+= "1"+ONLINE_FORM_MULTIVALUED_SEPARATOR;
				} else {
					setvalue+= "0"+ONLINE_FORM_MULTIVALUED_SEPARATOR;
				}
			}
			setvalue=setvalue.substring(0, setvalue.length-ONLINE_FORM_MULTIVALUED_SEPARATOR.length);
			string+=MULTI_PREFIX+e+ONLINE_FORM_FIELD_SEPARATOR+ setvalue + ONLINE_FORM_SEPARATOR;		
		} else {
			// Is not an array
			if (frm.elements[e].checked) {
				setvalue = "1";
			}
			if (!frm.elements[e].checked) {
				setvalue = "0";
			}
			string+= e + ONLINE_FORM_FIELD_SEPARATOR + setvalue + ONLINE_FORM_SEPARATOR;
		}
	}

	// HIDDEN field
	if (fieldType == "hidden") {
		string+= e + ONLINE_FORM_FIELD_SEPARATOR + frm.elements[e].value + ONLINE_FORM_SEPARATOR;
	}
	return string;
}

function saveField(o) {
	var cookieString = "";
	var frm = getOnlineForm();
	var e;
	var x;
	var cookieName;
	var fieldValues;

	var formname = frm.id;
	cookieName  = formname;
	fieldValues = getCookie(cookieName);

	if (!fieldValues) {
		cookieString+=getFieldStringValue(frm, o.name, o.type);
	} else {
		var fieldArray  = fieldValues.split(ONLINE_FORM_SEPARATOR);

		for (i = 0; i < fieldArray.length; i++) {
			var f = fieldArray[i];
			var values = f.split(ONLINE_FORM_FIELD_SEPARATOR);
			var fieldName  = values[0];
			var fieldValue = values[1];
			if (fieldName != o.name) {
				cookieString+=f+ONLINE_FORM_SEPARATOR;
			}
		}
		cookieString+=getFieldStringValue(frm, o.name, o.type);
	}
	cookieString=cookieString.substring(0, cookieString.length-ONLINE_FORM_SEPARATOR.length);	
	var exp   = getExpirationDate();
	setCookie(cookieName, cookieString, exp); 
}

//
// LOAD FORM FIELD SELECTIONS FROM SAVED COOKIES
//
function loadSelections(frm) {
	var e;
	var x;
	var cookieName;
	var fieldArray;
	var fieldValues;
	var fieldValue;

	var formname = frm.id;
	cookieName  = formname;
	fieldValues = getCookie(cookieName);

	if (!fieldValues) return;

	fieldArray  = fieldValues.split(ONLINE_FORM_SEPARATOR);

        var n = frm.length;
        for (i = 0; i < n; i++) {
            e = frm[i].name;
            var fieldType  = frm[i].type;
			
			if (e == '' || fieldType == "reset") continue;
		
			var fieldObject;
			var fieldValue = '';
			multivalued = false;
			
			// Search for the value
			for (j=0; j<fieldArray.length; j++) {
				var f = fieldArray[j];
				var values = f.split(ONLINE_FORM_FIELD_SEPARATOR);
				fieldName = values[0];
				if (fieldName == e) {
					fieldValue = values[1];				
					break;
				} else {
					if (fieldName.startsWith(MULTI_PREFIX+e)) {
						multivalued = true;
						fieldValue = values[1];
						var arrayValues = fieldValue.split(ONLINE_FORM_MULTIVALUED_SEPARATOR);
						for (k=0; k<arrayValues.length; k++) {
							var arrayValue = arrayValues[k];
							if (frm[i].multiple) {
								frm.elements[e][k].selected = (arrayValue=='1');
							} else {
								frm.elements[e][k].checked = (arrayValue=='1');
							}
							
						}
						break;
					}
				}
			}
			
			if (multivalued) {
				continue;
			}

            //
            // TEXT, TEXTAREA, and DROPDOWN
            if ((fieldType == "text") ||
                (fieldType == "textarea") ||
                (fieldType == "select-one")) {
                frm.elements[e].value = fieldValue;
            }

            // CHECKBOX
            if (fieldType == "checkbox") {
                fld_checkbox = fieldValue;
                if (fld_checkbox == "1") {
                    frm.elements[e].checked = true;
                }
            }

            // RADIO BUTTON
            //
            if (fieldType == "radio") {
                x = fieldValue;
                frm.elements[e][x].checked = true;
            }

            //
            // HIDDEN field
            //
            if (fieldType == "hidden") {
                frm.elements[e].value = fieldValue;
            }
        }
}

function setCookie(name, value, expires, path, domain, secure) {
	var c = name + "=" + escape(value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
 document.cookie = c;
}

function getCookie(name) {
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) 
			return null;
	} else {
		begin += 2;
	}
	var end = document.cookie.indexOf(";", begin);
	if (end == -1) {
		end = dc.length;
	}
	return unescape(dc.substring(begin + prefix.length, end));
}

function resetOnlineFormSelections() {
	var frm = getOnlineForm();
	var formname = frm.name;
	var exp   = getExpirationDate();
	var string = "";
	var cookieName = formname;
	setCookie(cookieName, string, exp); 
}
//END COOKIES SUPPORT