/**** [Begin : Global Vars ****/
var IMG_ESCONDER = "", IMG_EXPANDIR = "", STR_SITEDESCRIPTION = "", MAINIECLASS = "";

var windowLocation = ((window.location && window.location.href) ? window.location.href : "/");
// 
var isIBAQ = false, isIBPQ = false, isIBQ = false, isFMAQ = false, isFMPQ = false, isFMQ = false, isC8AQ = false, isC8PQ = false, isC8Q = false, isProdQ = false, isAuthQ = false;
isIBAQ = (windowLocation.search(/authoringib/i) >= 0);
isIBPQ = (windowLocation.search(/www.imperiobonanca.pt/i) >= 0);
isIBQ = (isIBAQ == true || isIBPQ == true);
// 
isFMAQ = (windowLocation.search(/authoringfm/i) >= 0);
isFMPQ = (windowLocation.search(/www.fidelidademundial.pt/i) >= 0);
isFMQ = (isFMAQ == true || isFMPQ == true);
// 
isC8AQ = (windowLocation.search(/authoringchiado8/i) >= 0);
isC8PQ = (windowLocation.search(/chiado8.fidelidademundial.pt/i) >= 0);
isFMQ = (isFMAQ == true || isFMPQ == true);
// 
isAuthQ = (isIBAQ == true || isFMAQ == true || isC8AQ == true);
isProdQ = (isIBPQ == true || isFMPQ == true || isC8PQ == true);

if (isFMQ) {
	IMG_ESCONDER = "/Style Library/Images/FMImages/img_esconder.gif",
	IMG_EXPANDIR = "/Style Library/Images/FMImages/img_expandir.gif",
	STR_SITEDESCRIPTION = "Fidelidade Mundial Seguros";
	STR_SITEPREFIX = "FM";
	MAINIECLASS = "";
}
else if (isIBQ) {
	IMG_ESCONDER = "/Style Library/Images/IBImages/img_esconder.gif",
	IMG_EXPANDIR = "/Style Library/Images/IBImages/img_expandir.gif",
	STR_SITEDESCRIPTION = "Império Bonança Seguros";
	STR_SITEPREFIX = "IB";
	MAINIECLASS = "";
}
else if (isC8Q) {
	IMG_ESCONDER = "/Style Library/Images/Chiado8Images/img_esconder.gif",
	IMG_EXPANDIR = "/Style Library/Images/Chiado8Images/img_expandir.gif",
	STR_SITEDESCRIPTION = "Chiado8 Arte Contemporânea";
	STR_SITEPREFIX = "Chiado8";
	MAINIECLASS = "";
}

var internalHostnames = []; // ['sdc6001spt05', 'sdc6001spt06', 'www.fidelidademundial.pt', 'www.imperiobonanca.pt', 'corporate.fidelidademundial.pt', 'www.medinet-seguros.pt', 'www.adn.imperiobonanca.pt'];
/**** Finish : Global Vars] ****/

/**** [Begin : Array Prototypes ****/
if (!Array.prototype.indexOf) {
	Array.prototype.indexOf = function(elt /*, from*/) {
		var len = this.length;
		var from = Number(arguments[1]) || 0;
		from = ((from < 0) ? Math.ceil(from) : Math.floor(from));
		if (from < 0) { from += len; }
		var ret = -1;
		for (; from < len && ret == -1; from++) {
			if (this[from].search(elt, "i") == 0) { ret = from; }
		}
		return ret;
	};
}
if (!Array.prototype.contains) {
	Array.prototype.contains = function (obj) { return (this.indexOf(obj) >= 0); };
}
/**** [Finish : Array Prototypes ****/

/**** [Begin : QueryString Access ****/
function Querystring(qs) { // optionally pass a querystring to parse
	this.params = {};
	
	if (qs == null) qs = location.search.substring(1, location.search.length);
	if (qs.length == 0) return;

	// Turn <plus> back to <space>
	// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ');
	var args = qs.split('&'); // parse out name/value pairs separated via &

	// split out each name=value pair
	for (var i = 0; i < args.length; i++) {
		var pair = args[i].split('=');
		var name = decodeURIComponent(pair[0]);
		var value = ((pair.length==2) ? decodeURIComponent(pair[1]) : name);
		this.params[name] = value;
	}
}
if (!Querystring.prototype.get) {
	Querystring.prototype.get = function(key, default_) {
		var value = this.params[key];
		return (value != null) ? value : default_;
	}
}
if (!Querystring.prototype.contains) {
	Querystring.prototype.contains = function(key) {
		var value = this.params[key];
		return (value != null);
	}
}
/**** [Finish: QueryString Access] ****/

/**** [Begin : Status Bar Message] ****	
function HideStatus() {
	window.status=STR_SITEDESCRIPTION;
	return true;
}
if (document.layers)document.captureEvents(Event.MOUSEOVER | Event.MOUSEOUT);
document.onmouseover=HideStatus;document.onmouseout=HideStatus;
*** [Finish: Status Bar Message] ****/

/**** [Begin : Cookies] ****/
function getCookie(name) {
	// cookies are separated by semicolons
	var aCookie = document.cookie.split("; ");
	if (aCookie && aCookie.length && aCookie.length > 0) {
		for (var i = 0; i < aCookie.length; i++) {
			// a name/value pair (a crumb) is separated by an equal sign
			var aCrumb = aCookie[i].split("=");
			if (aCrumb && aCrumb.length && aCrumb.length >= 2 && aCrumb[0] == name) { return unescape(aCrumb[1]); }
		}
	}
	// a cookie with the requested name does not exist
	return null;
}
function setCookie(name, val, domain) { document.cookie = name +'='+ val +';expires=Sun,1 Jan 2020 00:00:01 UTC;path=/'+(domain?'domain='+domain:''); }
function delCookie(name) { document.cookie = name +'=0;expires=Thu,1-Jan-1970 00:00:01 GMT;path=/'; }
/**** [Finish: Cookies] ****/

/**** [Begin : Show Formated Date] ****/
var m_names 	= new Array("Janeiro", "Fevereiro", "Mar&ccedil;o", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro");
var d 			= new Date();
var curr_date 	= d.getDate();
var curr_month 	= d.getMonth();
var curr_year 	= d.getFullYear();
var formateddate= curr_date + " de " + m_names[curr_month] + " de " + curr_year;
/**** [Finish: Show Formated Date] ****/

/**** [Begin : Shows One Specific DIV & Hide All Others] ****/
function hideAllExcept(elm) {
	for (var i = 0; i < FAQItems .length; i++) {
		var layer = document.getElementById("div_" + FAQItems [i]);
		layer.style.display = ((elm != "div_"+FAQItems[i]) ? "none" : "block");
	}
}
/**** [Finish: Shows One Specific DIV & Hides All Other DIV's] ****/

/**** [Begin : Shows All DIV's & Hides One Specific DIV] ****/
function ShowAllExcept(elm) {
	for (var i = 0; i < FAQItems .length; i++) {
		var layer = document.getElementById("div_" + FAQItems [i]);
		layer.style.display = ((elm != "div_"+FAQItems [i]) ? "block" : "none");
	}
}
/**** [Finish: Shows All DIV's & Hides One Specific DIV] ****/

/**** [Begin : Show All / Hide All Button Behavior] ****/
function ShowAll() {
	document.getElementById("ShowALL").style.display = "none";
	document.getElementById("HideALL").style.display = "block";
}
function HideAll() {
	document.getElementById("HideALL").style.display = "none";
	document.getElementById("ShowALL").style.display = "block";
}

/// <summary>
/// Hides all divs with a given prefix
/// </summary>
/// <param name="prefix">Spans ID prefix to hide</param>
function HideAllDivs(prefix) {
	try {
		var aDivs = document.getElementsByTagName("TABLE");
		for (var i = 0; i < aDivs.length; i++) {
			var div = aDivs[i];
			var id = div.id;
			if (id.indexOf(prefix) != -1) { HideDiv(id); }
		}
	}
	catch(e) { }
}
/// <summary>
/// Hides a div
/// </summary>
/// <param name="id">Div ID to hide</param>
function HideDiv(id) {
	try {
		elem = document.getElementById(id);
		elem.style.display = "none";
	}
	catch(e) { }
}
/// <summary>
/// Shows a span
/// </summary>
/// <param name="id">Div ID to show</param>
function ShowDiv(id) {	
	try {
		elem = document.getElementById(id);
		elem.style.display = "inline";
	}
	catch(e) { }
}	
/// <summary>
/// Toggles Span visibility
/// </summary>
/// <param name="id">Span ID to toggle visibility</param>
/// <param name="prefix">Spans ID prefix to hide</param>
function HideShowSpan (id,prefix) {
	try {
		var elem = document.getElementById(id);
		var display = elem.style.display;
		HideAllSpans(prefix);
		if (display == 'none') { ShowSpan(id); }
	}
	catch (e) { }
}
/// <summary>
/// Hides a span
/// </summary>
/// <param name="id">Span ID to hide</param>
function HideSpan(id) {
	try {
		var elem = document.getElementById(id);
		elem.style.display = "none";
	}
	catch(e) { }
}	
/// <summary>
/// Shows a span
/// </summary>
/// <param name="id">Span ID to show</param>
function ShowSpan(id) {
	try {
		elem = document.getElementById(id);
		elem.style.display = "inline";
	}
	catch(e) { }
}
/// <summary>
/// Hides all spans with a given prefix
/// </summary>
/// <param name="prefix">Spans ID prefix to hide</param>
function HideAllSpans(prefix) {
	try {
		var aSpans = document.getElementsByTagName("SPAN");
		for (var i = 0; i < aSpans.length; i++) {
			var span = aSpans[i];
			var id = span.id;
			if (id.indexOf(prefix) != -1) { HideSpan(id); }
		}
	}
	catch(e) { }	
}
/// <summary>
/// Shows all spans with a given prefix
/// </summary>
/// <param name="prefix">Spans ID prefix to show</param>
function ShowAllSpans(prefix) {
	try {
		var aSpans = document.getElementsByTagName("SPAN");
		for (var i = 0; i < aSpans.length; i++) {
			var span = aSpans[i];
			var id = span.id;
			if (id.indexOf(prefix) != -1) { ShowSpan(id); }
		}
	}
	catch(e) { }
}
/// <summary>
/// Toggles Visibility of FAQ Categories
/// </summary>
/// <param name="id">Category Span ID show</param>
/// <param name="CategotyPrefix">Category Spans ID prefix to hide</param>
/// <param name="FAQPrefix">FAQ Spans ID prefix to hide</param>
function ToggleFAQCategories(id, CategoryPrefix, FAQPrefix) {
	try {
		HideAllSpans(CategoryPrefix);
		ShowSpan(id);
		HideAllSpans(FAQPrefix);
	}
	catch(e) { }
}
/**** [Finish: Show All / Hide All Button Behavior] ****/

/**** [Begin : Scroll To Page Top] ****/
function GoToTop() {
	location.href = "#PageTop";
}
/**** [Finish: Scroll To Page Top] ****/

/**** [Begin : Show / Hide DIV's For Site Map] ****/
function HideDiv(divId) {
	divToHide 	= document.getElementById(divId);
	imgToChange = document.getElementById("IMG"+divId);
	if(divToHide.style.display == "none") {
		divToHide.style.display = "block";
		imgToChange.src = IMG_ESCONDER;
	}
	else {
		divToHide.style.display = "none";
		imgToChange.src = IMG_EXPANDIR;
	}
}
/**** [Finish: Show / Hide DIV's For Site Map] ****/

/**** [Begin : Redirect] ****/
function RedireccionarUrl(url, redirectUrl, descricao, target) {
	if(redirectUrl == "") { return; }
	if(target == 'Sml')	{
		NewWindow(url + "?Url=" + redirectUrl + "&Dc=" + descricao , 'Redireccionar', 790, 490, 'yes', 0, 0, 'no', 'no', 'yes', 'no', 'no');
	}
	else {
		document.frmPost.action = url + "?Url=" + redirectUrl + "&Dc=" + descricao;
		document.frmPost.target = "_blank";
		document.frmPost.submit();
	}
}
function NewWindow(mypage, myname, w, h, scroll, posX, posY, toolbar, menubar, resizable, location, status) {
	var win = null;

	LeftPosition = posX;
	TopPosition = posY;
	settings = 'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',toolbar='+toolbar+',menubar='+menubar+',resizable='+resizable+',location='+location+',status='+status;

	win = window.open(mypage,myname,settings);
	return win;
}
/**** [Finish: Redirect] ****/

/**** [Begin : Product Details] ****/
var itemsHidden = true;
function ShowAllDivs(n) {
	for(var j = 0; j < n; j ++) {
		if(itemsHidden) { ShowItem(j); }
		else { HideItem(j); }
	}
 	if(itemsHidden) {
		document.getElementById("btShowAll").style.display = "none";
		document.getElementById("btHideAll").style.display = "inline";
		document.getElementById("txShowAll").innerHTML = "Ocultar Todos";
 	}
	else {
		document.getElementById("btShowAll").style.display = "inline";
		document.getElementById("btHideAll").style.display = "none";
		document.getElementById("txShowAll").innerHTML = "Ver Todos";
	}
	itemsHidden = !itemsHidden;
}
function ShowDiv(i, n) {
	for(j = 0; j < n; j ++) {
		HideItem(j);
	}

	ShowItem(i);
}
function HideItem(i) {
	document.getElementById("div_" + i).style.display = "none";
}
function ShowItem(i) {
	document.getElementById("div_" + i).style.display = "block";
}
/**** [Finish: Product Details] ****/

/**** [Begin: Link Functions] ****/
function isLinkValid(url) {
	var pattern = new RegExp(
		'^(http[s]?:\/\/)?'+ // protocol
		'((([a-z\d]([a-z\d-]*[a-z\d])*)\.)+[a-z]{2,}|'+ // domain name
		'((\d{1,3}\.){3}\d{1,3}))'+ // OR ip (v4) address
		'(\:\d+)?(\/[-a-z\d%_.~+]*)*'+ // port and path
		'(\?[;&a-z\d%_.~+=-]*)?'+ // query string
		'(\#[-a-z\d_]*)?$' // fragment locater
		, "i"
	);
	// 
	var ret = (pattern.test(url) == true);
	//if(ret == false) { alert("Please enter a valid URL."); }
	return ret;
}
function isHostInternal(host) {
	host = host.replace(/:[0-9]+$/, ''); // remove port
	return (host && (host == document.location.hostname || internalHostnames.contains(host) == true));
}
function isLinkExternal(url) {
	var ret = false;
	// 
	var arr = url.split('/');
	if (arr && arr.length > 0) {
		if (arr[0]) { // doesn't start with '/xpto'
			var firstWord = arr[0];
			firstWord = firstWord.replace(/:[0-9]+$/, ''); // remove port
			if (firstWord.indexOf(':') >= 0) {
				var protocol = firstWord.split(':')[0];
				if (protocol.search(/^http[s]?$/i) == 0) {
					var hostname = '';
					for(var i = 2; i < arr.length; i++) { // find the word after the protocol 'http://xpto'
						hostname = arr[i];
						if (arr[i]) { break; }
					}
					ret = (hostname && isHostInternal(hostname) == false);
				}
				else if (protocol.search(/^javascript$/i) == 0) { ret = false; } // javascript: links are considered local
				else { ret = true; } // other protocols than http and javascript
			}
			else { // doesn't have a protocol (can be a hostname, or a page) (ex.: www.google.com, page.aspx)
				ret = (isHostInternal(firstWord) == false && firstWord.search(/.(com|org|net)+/i) > 1); // (consider that any non internal link that is dotcom is external)
			}
		}
		// else starts with '/'
	}
	// 
	return ret;
}
//function testLink(url){
//	if (isLinkExternal(url) == true) { window.alert(url +' is external'); } else { window.alert(url +' is LOCAL'); }
//}
//testLink('http://sdc6001spt05:9002/Pages/Home.aspx');
//testLink('http://www.teste.com');
//testLink('sdc6001spt05');
//testLink('sdc6001spt05:9002');
//testLink('www.google.com');
//testLink('/pagina.aspx');
//testLink('pagina.aspx');
//testLink('javascript:teste();');
//testLink('http://www.medinet-seguros.pt/');
//testLink('http://corporate.fidelidademundial.pt/');
/**** [Finish: Link Functions] ****/

function titleDDLChange(ddl) {
	for(var i = 0; i < ddl.length; i++) {
		if (ddl[i].selected) {
			var urlSite = ddl[i].value;
			if (urlSite != '') {
				// window.location = urlSite;
				window.open(urlSite, "_blank", "toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes");
			}
		}
	}
}

/// <summary>
/// Obtains the mask from the Best for me area
/// </summary>
function GetMask() {
	var strTempMask;
	var strMask = "";
	var aSpans = document.getElementsByTagName("SPAN");
	//Iterates spans - categories
	for (var cat_index = 0; cat_index < aSpans.length; cat_index++) { // for spans
		var strInputType = "";
		bFoundSelected = false;

		//Mask value before the inputs
		strTempMask = strMask;

		var aElems = document.getElementsByName(aSpans[cat_index].id + "_profile");
		if (aElems.length > 0) {
			strInputType = aElems[0].type;
		}

		//Iterates inputs - questions
		for (var index = 0; index < aElems.length; index++) { //for inputs
			strMask += ((aElems[index].checked) ? "1" : "0");
		}
	}

	return strMask;
}

/// <summary>
/// Returns a string padded with length characters
/// </summary>
function PadString(strExp, length) {
	var result = strExp;
	try {
		result = "";
		if (strExp.length < length) {
			for (index = strExp.length; index < length; index++) {
				result = "0" + result;
			}
		}
		result += strExp;
	}
	catch(e) { }

	return result;
}

/// <summary>
/// Performs a bitwise AND without carriage return
/// </summary>
function BinaryAnd(strPartA, strPartB) {
	var strLeftSideOperator, strRightSideOperator;
	var iOperatorLength;
	var index;
	var iSumPart;
	var result;

	result = strPartA;
	try {
		strLeftSideOperator = "";
		strRightSideOperator = "";
		result = "";
		if (strPartA.length > strPartB.length) {
			strLeftSideOperator = strPartA;
			strRightSideOperator = PadString(strPartB,strPartA.length);
		}
		else {
			strLeftSideOperator = PadString(strPartA,strPartB.length);
			strRightSideOperator = strPartB;
		}

		iOperatorLength = strPartA.length;
		for (index = iOperatorLength - 1; index >= 0; index--) {
			iSumPart = parseInt(strLeftSideOperator.substring(index,index+1)) * parseInt(strRightSideOperator.substring(index,index+1))
			result = iSumPart + result;
		}
	}
	catch(e) { }

	return result;	
}

/// <summary>
/// Applies the mask to the BestForMe User Control
/// </summary>
function ApplyMask() {
	var strMask;	
	var aSpans;
	var span;
	var i;
	var id;
	var product_profile_sep;
	var product_profile;
	var profileKeywork;

	profileKeywork = "PROFILE_"

	try {
		strMask = GetMask();
		// resets the product visibility
		HideAllSpans (profileKeywork);
		aSpans = document.getElementsByTagName("SPAN");

		for (i=0; i < aSpans.length; i++) {
			span = aSpans[i];
			id = span.id;
			product_profile_sep = id.indexOf(profileKeywork);
			if (product_profile_sep > 0) {
				product_profile = id.substring(product_profile_sep + profileKeywork.length,id.length);
				if (BinaryAnd(strMask,product_profile) == strMask) {
					ShowSpan(id);
				}
			}
		}
	}
	catch(e) { }
}

/// <summary>
/// Resets the inputs with a given prefix
/// </summary>
function ResetOptions(prefix) {
	var aElems;
	var elem;
	var id;
	try {
		aElems = document.getElementsByTagName("INPUT");
		for (i=0; i < aElems.length; i++) {
			elem = aElems[i];
			id = elem.id;

			if (id.indexOf(prefix) != -1) {
				elem.checked = false;
			}
		}
		ApplyMask();
	}
	catch(e) { }
}

/// <summary>
/// Changes a style class for an element
/// </summary>
function ChangeClass(id,ClassName) {
	var elem;
	try {
		elem = document.getElementById(id);
		elem.className = ClassName;
	}
	catch(e) { }
}

/// <summary>
/// Changes the visibilities of FAQs and Glossaries
/// </summary>
function ToggleFAQGlossary(SpanIDToShow,SpanPrefixToHide) {
	try {
		//Hide all spans
		HideAllSpans (SpanPrefixToHide);
		ShowSpan(SpanIDToShow);
	}
	catch(e) { }
}

/// Switches the DropDown Menus
/// Input: spanName: Parent Menu name being switch
function SwitchMenu(spanName) {
	var elems;
	var elem;
	var nameParts;
	var MainSplit;
	var MainSplitCount;
	var arDivs;
	var mainDiv;
	var arActiveElem;
	var activeElem;

	try {
		//Determines the start menu level
		MainSplit = spanName.split("_");
		MainSplitCount = MainSplit.length;

		//obtains all Divs from screen
		arDivs = document.getElementsByTagName("div");
		for (var i=0; i< arDivs.length; i++) {
			if (arDivs[i].id.indexOf("masterdiv") != -1) {
				mainDiv = arDivs[i];
				break;
			}
		}

		//obtains all inputs into an array
		arActiveElem = mainDiv.getElementsByTagName("input");
		for (var i=0; i< arActiveElem.length; i++) {
			activeElem = arActiveElem[i];

			//verifies if it's the Active menu Hidden input
			if (activeElem.id.indexOf("ActiveMenu") != -1) {
				activeElem.value = spanName;
				break;
			}
		}

		//Build the menu full path 
		//to build the breadcrumb
		BuildMenuPath();

		//obtains all spans into an array
		elems =	mainDiv.getElementsByTagName("span");
		for (var i=0; i< elems.length; i++) {
			elem = elems[i];
			//determines the level of menu item
			nameParts = elem.id.split("_");

			//Verifies if it's a sub-menu 
			//The "_" is inserted to prevent other menus with
			//similar names to be shown
			if (elem.id.indexOf(spanName + "_") != -1) {
				//verifies if it's a direct sub-menu
				if ((nameParts.length - 1 ) == MainSplitCount) {
					//switch menu visibility
					if (elem.style.display == "block") {
						elem.style.display = "none";
					}
					else {
						elem.style.display = "block";
					}
				}

				//if it's not a direct sub-menu hides it
				if ((nameParts.length - 1 ) > MainSplitCount) {
					elem.style.display = "none";
				}
			}
			else {
				//make sure the menu is not an ancester
				if (spanName.indexOf(elem.id) == -1) {
					if (nameParts.length > MainSplitCount) {
						elem.style.display = "none";
					}
				}
			}
		}
	}
	catch(e) {
		//alert(e.message);
	}
}

/// Function that reads from a hidden field and shows
/// the active field there indicated
function SetActiveMenuItem() {
	var elemActive;
	var arInputs;

	try {
		arInputs = document.getElementsByTagName("input");
		for (var i=0; i< arInputs.length; i++) {
			if (arInputs[i].id.indexOf("m_inActiveMenu") != -1) {
				elemActive = arInputs[i];
				break;
			}
		}
		if (elemActive.value != "") { ShowMenu(elemActive.value); }
	}
	catch(e) {
		//alert(e.message);
	}
}

/// Shows the indicated menu and all at the same level, sons of same menu or upper
function ShowMenu(menuName) {
	var elems;
	var arDivs;
	var mainDiv;
	var MainSplit;
	var MainSplitCount;
	var nameParts;
	var i;
	var bParentShown;
	var parentName;

	try {
		//Determines the start menu level
		MainSplit = menuName.split("_");
		MainSplitCount = MainSplit.length;

		//build the parent name
		parentName = '';
		for (var i=0; i < MainSplitCount - 1; i++) {
			parentName += MainSplit[i];
			if (i < MainSplitCount - 2)
				parentName += "_";
		}

		if (parentName != '' && parentName != 'menu') {
			//obtains all Divs from screen-Discover masterdiv
			arDivs = document.getElementsByTagName("div");
			for (i=0; i< arDivs.length; i++) {
				if (arDivs[i].id.indexOf("masterdiv") != -1) {
					mainDiv = arDivs[i];
					break;
				}
			}

			//obtains all spans in an array
			elems =	mainDiv.getElementsByTagName("span");
			for (var i=0; i< elems.length; i++) {
				elem = elems[i];

				//determines the level of menu item
				nameParts = elem.id.split("_");

				//It's an element of the same level...show
				//The "_" is inserted to prevent other menus with
				//similar names to be shown
				if (elem.id.indexOf(parentName + "_") != -1 && nameParts.length == MainSplitCount) {
					elem.style.display = "block";
				}
			}

			// show parents - recursive
			if (MainSplitCount > 3)	
				ShowMenu(parentName);
		}
	}
	catch(e) { }
}


/// Builds the menu path for the breadcrumb
function BuildMenuPath() {
	var activeElem;
	var ActiveName;
	var ActiveSplit;
	var ActiveSplitCount;
	var parentName;
	var parentElem;
	var FullMenuPath;

	try {
		FullMenuPath = LoadElementByPartialName("div","masterdiv","input","FullMenuPath");
		FullMenuPath.value = "";

		activeElem = LoadElementByPartialName("div","masterdiv","input","ActiveMenu");

		ActiveName = activeElem.value;

		//obtains the level of the active menu
		ActiveSplit = ActiveName.split("_");
		ActiveSplitCount = ActiveSplit.length;

		parentName = "menu";
		for (var i=1; i < ActiveSplitCount; i++) {
			parentName += "_" + ActiveSplit[i];
			//Load the menu Label element
			parentElem = LoadElementByPartialName("span",parentName,"a","_MenuLabel");

			//if it's the first time don't place the seperator
			if (FullMenuPath.value != "")
				FullMenuPath.value += "&nbsp;>&nbsp;";

			// childNodes instead of innerText for mozilla compatibility
			//FullMenuPath.value += parentElem.innerText;
			FullMenuPath.value += parentElem.childNodes[0].nodeValue;
		}
	}
	catch(e) {
		//alert(e.message);
	}
}


/// Builds the BreadCrumb based on the hidden values 
function BuildBreadCrumb(BreadCrumbPath) {
	var BeginCrumb;
	var AreaCrumb;
	var AreaCrumbLink;
	var MenuCrumb;
	var PageCrumb;
	var BreadCrumb;
	var Seperator;
	var BreadCrumbElement;

	BreadCrumb = "";
	Seperator = "&nbsp;>&nbsp;";

	try {
		//fixed crumb
		BeginCrumb = "<a href='../site/homepage.aspx'>In&iacute;cio</a>";

		//Load Area Description crumb
		AreaCrumb = LoadElementByPartialName("","","input","hdnAreaDescription");

		//Load Area Description crumb Link
		AreaCrumbLink = LoadElementByPartialName("","","input","hdnAreaDescriptionLink");

		//Load Menu crumb
		MenuCrumb = LoadElementByPartialName("div","masterdiv","input","FullMenuPath");

		//Load Page crumb
		PageCrumb = LoadElementByPartialName("","","input","hdnPageCrumb");

		//*** Begin building the output ***
		BreadCrumb = BeginCrumb;

		if (AreaCrumb != null && AreaCrumb.value != "") {
			if (AreaCrumbLink != null && AreaCrumbLink.value != "")
				BreadCrumb += Seperator + "<a href='" + AreaCrumbLink.value + "'>" + AreaCrumb.value + "</a>";
			else
				BreadCrumb += Seperator + AreaCrumb.value;
		}

		if (MenuCrumb != null && MenuCrumb.value != "")
			BreadCrumb += Seperator + MenuCrumb.value;

		if (PageCrumb != null && PageCrumb.value != "")
			BreadCrumb += Seperator + PageCrumb.value;

		BreadCrumbElement = LoadElementByPartialName("","","div",BreadCrumbPath);
		if (BreadCrumbElement != null & BreadCrumb != "")
			BreadCrumbElement.innerHTML = BreadCrumb;
	}
	catch(e) {
		//alert("ERRO:" + e.message);
	}
}

/// Loads an element from screen based on its partial name and TagName
/// It can narrow the search by provding a masterTag section
function LoadElementByPartialName(masterTag, masterName, tagName, elementName) {
	var arDivs;
	var mainDiv;
	var arElems;
	var elem;	
	var bFound;

	mainDiv = null;
	elem = null;	
	bFound = false;

	try {
		if (masterName != "" && masterTag != "") {	
			//obtains all Divs from screen
			arDivs = document.getElementsByTagName(masterTag);

			for (var i=0; i< arDivs.length; i++) {
				if (arDivs[i].id.indexOf(masterName) != -1) {
					mainDiv = arDivs[i];
					break;
				}
			}
		}

		if (mainDiv != null)
			//obtains all inputs into an array
			arElems = mainDiv.getElementsByTagName(tagName);
		else
			arElems = document.getElementsByTagName(tagName);

		for (var i=0; i< arElems.length; i++) {
			elem = arElems[i];

			//verifies if it's the Active menu Hidden input
			if (elem.id.indexOf(elementName) != -1) {
				//found
				bFound = true;
				break;
			}
		}

		if (!bFound)
			elem = null;
		return elem;
	}
	catch (e) {
		return null;
	}
}

/// Jumps to the url of the selected option in a dropdown box
function MM_jumpMenu(targ,selObj,restore){ //v3.0
	var jaRedireccionou = false;
	try {
		var optionValue = selObj.options[selObj.selectedIndex].value;	

		if (optionValue.length > 0) {
			// se a opcao for do tipo "abcdef;1", a opcao depois de ';' indica se e' 
			// para abrir numa nova janela ou nao

			var args = optionValue.split(";");
			if(args.length>1) {
				if(args[1] == "1") {
					targ = window.open();
					targ.location = args[0];
					jaRedireccionou = true;
				}
			}

			if(!jaRedireccionou) {
				eval(targ+".location='"+args[0]+"'");
			}
			if (restore) selObj.selectedIndex=0;
		}
	}
	catch(e) { }
}

/// Performs the contact search with full text
function SearchContact() {
	try {
		var searchInput = "SearchString";		
		var searchStringElem = document.getElementById(searchInput);
		location.href = '../Site/WhereWeAre.aspx?TotalText=' + searchStringElem.value;
	}
	catch(e) {
		//alert(e.message);
	}
}
function SearchSite() {
	try {
		var searchInput = "SiteSearch";
		var searchStringElem = document.getElementById(searchInput);
		location.href = '../Site/Search.aspx?all=True&query=' + searchStringElem.value;
	}
	catch(e) {
		//alert(e.message);
	}
}

// Sets default buttons.
// Compatibilidade: -Mozilla, IE...
function fnTrapKD(btn, event) {
	try {
		if (document.all) {
			if (event.keyCode == 13) {
				event.returnValue=false;
				event.cancel = true;
				btn.click();
			}
		}
		else if (document.getElementById || document.layers) {
			if (event.which == 13) {
				event.returnValue=false;
				event.cancel = true;
				btn.onclick();
			}
		}
	}
	catch(e) {
		//alert(e.message);
	}
}

// Validate BirthDay field - current age must be between 18 and 45
// The age is calculated only using the years, as in the BSG service
function ValidateBirthdate( object, args ) {
	var birthDateString;
	var birthYearString = new String();
	var birthYearInt;
	var yearNow = new Date();
	var age;
	
	try {
		args.IsValid = true;

		birthDateString = String(args.Value);
		
		// gets the year from date. The format validator does not allow a date in another format
		birthYearString = birthDateString.substring(6, 10);
		
		// year not well formed - The format validator will give the error message,
		// this validator doesn't need to show its own
		if (birthYearString.length != 4) {
			args.IsValid = false;
			return;
		}
		
		// trick to convert a string to int	
		birthYearInt = birthYearString * 1;
		age = yearNow.getYear() - birthYearInt;

		if (age < 18 || age > 45) {
			args.IsValid = false;
		}
		else {
			args.IsValid = true;
		}
	}
	catch(e) {
		// there was an error getting the year. The format validator will give the error message,
		// this validator doesn't need to show its own
		args.IsValid = true;
	}
}


var dtCh= "-";
var minYear=1800;
var maxYear=2100;

function isInteger(s){
	var i;
	for (i = 0; i < s.length; i++){	 
		// Check that current character is number.
		var c = s.charAt(i);
		if (((c < "0") || (c > "9"))) return false;
	}
	// All characters are numbers.
	return true;
}

function stripCharsInBag(s, bag){
	var i;
	var returnString = "";
	// Search through string's characters one by one.
	// If character is not in bag, append to returnString.
	for (i = 0; i < s.length; i++){	 
		var c = s.charAt(i);
		if (bag.indexOf(c) == -1) returnString += c;
	}
	return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
	// EXCEPT for centurial years which are not also divisible by 400.
	return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
	 } 
	 return this
}

function isDate(dtStr) {
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		//alert("O formato da data deverá ser: dd-mm-aaaa")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		//alert("Por favor, indique um mês válido.")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		//alert("Por favor, indique um dia válido.")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		//alert("Por favor, indique um ano válido (entre"+minYear+" e "+ maxYear + ")")
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		//alert("Por favor, indique uma data válida.")
		return false
	}
	return true
}

function ValidaData(source) {
	var dt= document.getElementById(source.id);
	if (isDate(dt.value) == false) {
		dt.focus();
		return false;
	}
	return true;
}

function SetValueToTextInputs(prefix, value) {
	try {
		var aTextInputs = document.getElementsByTagName("INPUT");
		for (var i = 0; i < aTextInputs.length; i++) {
			var textInput = aTextInputs[i];
			if (textInput.id.indexOf(prefix) != -1) {
				textInput.value = value;
			}
		}
	}
	catch(e) { }
}

function trim(stringToTrim) {
    return stringToTrim.replace(/^\s+|\s+$/g, "");
}

/**** [Begin: Browser detection] ****/

var isBrowserIEQ = false, isBrowserIE5Q = false, isBrowserIE6Q = false, isBrowserIE7Q = false, isBrowserIE8Q = false,
    isBrowserMozillaQ = false, isBrowserFF1Q = false, isBrowserFF2Q = false, isBrowserFF3Q = false,
    isBrowserOperaQ = false, isBrowserOP10Q = false, isBrowserOP9Q = false, isBrowserOP8Q = false, isBrowserOP7Q = false,
    isBrowserOtherQ = false;
function detectBrowser() {
    isBrowserIEQ = false; isBrowserIE5Q = false; isBrowserIE6Q = false; isBrowserIE7Q = false; isBrowserIE8Q = false;
    isBrowserMozillaQ = false; isBrowserFF1Q = false; isBrowserFF2Q = false; isBrowserFF3Q = false;
    isBrowserOperaQ = false; isBrowserOP10Q = false; isBrowserOP9Q = false; isBrowserOP8Q = false; isBrowserOP7Q = false;
    isBrowserOtherQ = false;
    //
    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { //test for MSIE x.x;
        isBrowserIEQ = true;
        //
        var ieversion = new Number(RegExp.$1) // capture x.x portion and store as a number
        if (ieversion >= 8) {isBrowserIE8Q = true; }
        else if (ieversion >= 7) { isBrowserIE7Q = true; }
        else if (ieversion >= 6) { isBrowserIE6Q = true; }
        else if (ieversion >= 5) { isBrowserIE5Q = true; }
    }
    else if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)) { //test for Firefox/x.x or Firefox x.x (ignoring remaining digits);
        isBrowserMozillaQ = true;
        // 
        var ffversion = new Number(RegExp.$1) // capture x.x portion and store as a number
        if (ffversion >= 3) { isBrowserFF3Q = true; }
        else if (ffversion >= 2) { isBrowserFF2Q = true; }
        else if (ffversion >= 1) { isBrowserFF1Q = true; }
    }
    else if (/Opera[\/\s](\d+\.\d+)/.test(navigator.userAgent)){ //test for Opera/x.x or Opera x.x (ignoring remaining decimal places);
        isBrowserOperaQ = true;
        // 
        var oprversion = new Number(RegExp.$1) // capture x.x portion and store as a number
        if (oprversion >= 10) { isBrowserOP10Q = true; }
        else if (oprversion >= 9) { isBrowserOP9Q = true; }
        else if (oprversion >= 8) { isBrowserOP8Q = true; }
        else if (oprversion >= 7) { isBrowserOP7Q = true; }
    }
    else { isBrowserOtherQ = true; }
}

/**** [Finish: Browser detection] ****/


/**** [Begin : IE and Mozilla handles] ****/
/**** [Begin : Shows DIV With Info And Sets The Active Tabbed Menu Item] ****/
function selectCurrentRelatedPage() {
    detectBrowser();
    //
    if (isBrowserIEQ == true) {
        var qs = new Querystring();
        var divs = document.getElementsByTagName("div");
        var tables = document.getElementsByTagName("table");
        for (var X = 0; X < tables.length; X++) {
            if (tables[X].className.indexOf("history") >= 0) {
                document.getElementById(tables[X].id).style.display = "none";
                if (qs.get('company') == undefined) {
                    document.getElementById(MAINIECLASS).style.display = "block";

                    for (a = 0; a < divs.length; a++) {
                        if (divs[a].className.indexOf("relatedpage") != -1) {
                            divs[a].children[0].className = "lkgeralon";
                            break;
                        }
                    }
                }
            }
        }
        for (i = 0; i < divs.length; i++) {
            if (divs[i].className.indexOf("relatedpage") != -1 && divs[i].children[0].href == window.location.href) {
                divs[i].children[0].className = "lkgeralon";
                document.getElementById(qs.get('company')).style.display = "block";
            }
        }
    }
    else if (isBrowserMozillaQ == true) {
        var qs = new Querystring();
        var divs = document.getElementsByTagName("div");
        var tables = document.getElementsByTagName("table");
        for (var X = 0; X < tables.length; X++) {
            if (tables[X].className.indexOf("history") >= 0) {
                document.getElementById(tables[X].id).style.display = "none";
                if (qs.get('company') == undefined) {
                    document.getElementById("FidelidadeMundial").style.display = "block";
                    for (a = 0; a < divs.length; a++) {
                        if (divs[a].className.indexOf("relatedpage") != -1) {
                            divs[a].childNodes[0].className = "lkgeralon";
                            break;
                        }
                    }
                }
            }
        }
        for (i = 0; i < divs.length; i++) {
            if (divs[i].className.indexOf("relatedpage") != -1 && divs[i].childNodes[0].href == window.location.href) {
                divs[i].childNodes[0].className = "lkgeralon";
                document.getElementById(qs.get('company')).style.display = "block";
            }
        }
    }
}
/**** [Finish: Shows DIV With Info And Sets The Active Tabbed Menu Item] ****/

/**** [Begin : Sets The Active Tabbed Menu Item On Financial Reports Page] ****/
function selectCurrentFinancialReportYear() {
    detectBrowser();
    //
    if (isBrowserIEQ == true) {
        var qs = new Querystring();
        var divs = document.getElementsByTagName("div");

        for (i = 0; i < divs.length; i++) {
            if (divs[i].className.indexOf("reportyear") != -1 && divs[i].children[0].href == window.location.href) {
                divs[i].children[0].className = "lkgeralon";
            }
            else if (qs.get('QFN') == undefined) {
                for (ii = 0; ii < divs.length; ii++) {
                    if (divs[ii].className.indexOf("reportyear") != -1) {
                        divs[ii].children[0].className = "lkgeralon";
                        break;
                    }
                }
            }
        }
    }
    else if (isBrowserMozillaQ == true) {
        
    }
}
/**** [Finish: Sets The Active Tabbed Menu Item On Financial Reports Page] ****/

/**** [Begin : Attach Events To Left Navigation Menu] ****/
function attachLeftMenuEvents() {
    detectBrowser();
    //
    if (isBrowserIEQ == true) {
        var navigation = document.getElementById("zz1_CurrentNav");
        var nav = navigation.childNodes[0].childNodes;
        var menuExpandTitle = "";

        if (menuUnhideTitle != null && menuUnhideTitle != undefined) {
            switch (menuUnhideTitle) {
                case "Product":
                    menuExpandTitle = document.getElementById("txttituloparticularesTitleDIV").innerText;
                    //menuExpandTitle = menuExpandTitle.substring(0, menuExpandTitle.length-2);
                    var stringparts = menuExpandTitle.split(" ");
                    var i;
                    menuExpandTitle = "";
                    for (i = 0; i < stringparts.length; i++) {
                        if (stringparts[i].length > 0) {
                            menuExpandTitle = menuExpandTitle + " " + stringparts[i];
                        }
                    }
                    menuExpandTitle = menuExpandTitle.substring(1, menuExpandTitle.length);
                    break;
                case "News":
                    menuExpandTitle = "Eventos e Notícias";
                    break;
                case "PercursoHist":
                    menuExpandTitle = "Percurso Histórico";
                    break;
            }
        }
        for (i = 0; i < nav.length; i++) {
            if (nav[i].id.length > 0) {
                var a = nav[i].getElementsByTagName("A");
                if (a[0].href.length == 0) {
                    nav[i].onclick = function() {
                        var nav = this.parentNode.children;
                        var trs;
                        for (i = 0; i < nav.length; i++) {
                            if (this.id == nav[i].id) {
                                i++;
                                if (nav[i].style.display == "block") {
                                    nav[i].style.display = "none";
                                    var table = nav[i - 1].getElementsByTagName("table");
                                    table[0].setAttribute("className", "leftNav1");
                                }
                                else {
                                    nav[i].style.display = "block";
                                    var table = nav[i - 1].getElementsByTagName("table");
                                    table[0].setAttribute("className", "leftNav1Active");
                                }
                            }
                            else if (nav[i].id.length == 0) {
                                nav[i].style.display = "none";
                                var table = nav[i - 1].getElementsByTagName("table");
                                table[0].setAttribute("className", "leftNav1");
                            }
                        }
                    }
                }
            }
            else {
                nav[i].style.display = "none";
                submenu = nav[i].getElementsByTagName("table");
                for (j = 0; j < submenu.length; j++) {
                    if ((submenu[j].getAttribute("className") != null
					    && submenu[j].getAttribute("className").match("leftNavSelected") != null)
					    || (menuExpandTitle.length > 0 && submenu[j].innerText == menuExpandTitle)) {
                        nav[i].style.display = "block";
                        var table = nav[i - 1].getElementsByTagName("table");
                        table[0].setAttribute("className", "leftNav1Active");
                        submenu[j].className += " leftNavSelected";
                        var submenuAnc = submenu[j].getElementsByTagName("A");
                        submenuAnc[0].className += " leftNavSelected";
                    }
                }
            }
        }
        navigation.style.display = "block";
    }
    else if (isBrowserMozillaQ == true) {
        var nav = document.getElementById("zz1_CurrentNav").childNodes[1].childNodes;
        var menuExpandTitle = "";
        if (menuUnhideTitle != null && menuUnhideTitle != undefined) {
            switch (menuUnhideTitle) {
                case "Product":
                    menuExpandTitle = document.getElementById("txttituloparticularesTitleDIV").textContent;
                    menuExpandTitle = trim(menuExpandTitle);
                    break;
                case "News":
                    menuExpandTitle = "Eventos e Notícias";
                    break;
                case "PercursoHist":
                    menuExpandTitle = "Percurso Histórico";
                    break;
            }
        }

        for (var i = 0; i < nav.length - 1; i++) {
            if (nav[i].id != "") {
                var a = nav[i].getElementsByTagName("A");
                if (a[0].href.length == 0) {
                    nav[i].onclick = actionOnClick;
                }
            }
            else {
                nav[i].style.display = "none";
                var submenu = nav[i].getElementsByTagName("table");
                for (var j = 0; j < submenu.length; j++) {
                    var tmpStr = trim(submenu[j].textContent);
                    if (submenu[j].className.match("leftNavSelected") != null || (menuExpandTitle.length > 0 && tmpStr == menuExpandTitle)) {
                        nav[i].style.display = "block";
                        var table = nav[i - 1].getElementsByTagName("table");
                        table[0].className = "leftNav1Active";
                        var submenuAnc = submenu[j].getElementsByTagName("A");
                        submenuAnc[0].className += " leftNavSelected";
                    }
                }
            }
        }
        var hideNav = document.getElementById("zz1_CurrentNav");
        hideNav.style.display = "block";
    }
}
function actionOnClick() {
    var nav = this.parentNode.childNodes;
    var trs;
    for (i = 0; i < nav.length; i++) {
        if (this.id == nav[i].id) {
            i++;
            if (nav[i].style.display == "block") {
                nav[i].style.display = "none";
                var table = nav[i - 1].getElementsByTagName("table");
                table[0].className = "leftNav1";
            }
            else {
                nav[i].style.display = "block";
                var table = nav[i - 1].getElementsByTagName("table");
                table[0].className = "leftNav1Active";
            }
        }
        else if (nav[i].id.length == 0) {
            nav[i].style.display = "none";
            var table = nav[i - 1].getElementsByTagName("table");
            table[0].className = "leftNav1";
        }
    }
}
/**** [Finish: Attach Events To Left Navigation Menu] ****/
/**** [Finish: IE and Mozilla handles] ****/


// ********************* **************** ** JAVASCRIPT HTML ENCODER ** ****************** ********************* //
Encoder = {
	// When encoding do we convert characters into html or numerical entities
	EncodeType:"entity",  // entity OR numerical
	isEmpty:function (val) {
		if (val) { return ((val === null) || val.length == 0 || /^\s+$/.test(val)); }
		else { return true; }
	},
	// Convert HTML entities into numerical entities
	HTML2Numerical: function (s) {
		var arr1 = new Array('&nbsp;', '&iexcl;', '&cent;', '&pound;', '&curren;', '&yen;', '&brvbar;', '&sect;', '&uml;', '&copy;', '&ordf;', '&laquo;', '&not;', '&shy;', '&reg;', '&macr;', '&deg;', '&plusmn;', '&sup2;', '&sup3;', '&acute;', '&micro;', '&para;', '&middot;', '&cedil;', '&sup1;', '&ordm;', '&raquo;', '&frac14;', '&frac12;', '&frac34;', '&iquest;', '&agrave;', '&aacute;', '&acirc;', '&atilde;', '&Auml;', '&aring;', '&aelig;', '&ccedil;', '&egrave;', '&eacute;', '&ecirc;', '&euml;', '&igrave;', '&iacute;', '&icirc;', '&iuml;', '&eth;', '&ntilde;', '&ograve;', '&oacute;', '&ocirc;', '&otilde;', '&Ouml;', '&times;', '&oslash;', '&ugrave;', '&uacute;', '&ucirc;', '&Uuml;', '&yacute;', '&thorn;', '&szlig;', '&agrave;', '&aacute;', '&acirc;', '&atilde;', '&auml;', '&aring;', '&aelig;', '&ccedil;', '&egrave;', '&eacute;', '&ecirc;', '&euml;', '&igrave;', '&iacute;', '&icirc;', '&iuml;', '&eth;', '&ntilde;', '&ograve;', '&oacute;', '&ocirc;', '&otilde;', '&ouml;', '&divide;', '&Oslash;', '&ugrave;', '&uacute;', '&ucirc;', '&uuml;', '&yacute;', '&thorn;', '&yuml;', '&quot;', '&amp;', '&lt;', '&gt;', '&oelig;', '&oelig;', '&scaron;', '&scaron;', '&yuml;', '&circ;', '&tilde;', '&ensp;', '&emsp;', '&thinsp;', '&zwnj;', '&zwj;', '&lrm;', '&rlm;', '&ndash;', '&mdash;', '&lsquo;', '&rsquo;', '&sbquo;', '&ldquo;', '&rdquo;', '&bdquo;', '&dagger;', '&dagger;', '&permil;', '&lsaquo;', '&rsaquo;', '&euro;', '&fnof;', '&alpha;', '&beta;', '&gamma;', '&delta;', '&epsilon;', '&zeta;', '&eta;', '&theta;', '&iota;', '&kappa;', '&lambda;', '&mu;', '&nu;', '&xi;', '&omicron;', '&pi;', '&rho;', '&sigma;', '&tau;', '&upsilon;', '&phi;', '&chi;', '&psi;', '&omega;', '&alpha;', '&beta;', '&gamma;', '&delta;', '&epsilon;', '&zeta;', '&eta;', '&theta;', '&iota;', '&kappa;', '&lambda;', '&mu;', '&nu;', '&xi;', '&omicron;', '&pi;', '&rho;', '&sigmaf;', '&sigma;', '&tau;', '&upsilon;', '&phi;', '&chi;', '&psi;', '&omega;', '&thetasym;', '&upsih;', '&piv;', '&bull;', '&hellip;', '&prime;', '&prime;', '&oline;', '&frasl;', '&weierp;', '&image;', '&real;', '&trade;', '&alefsym;', '&larr;', '&uarr;', '&rarr;', '&darr;', '&harr;', '&crarr;', '&larr;', '&uarr;', '&rarr;', '&darr;', '&harr;', '&forall;', '&part;', '&exist;', '&empty;', '&nabla;', '&isin;', '&notin;', '&ni;', '&prod;', '&sum;', '&minus;', '&lowast;', '&radic;', '&prop;', '&infin;', '&ang;', '&and;', '&or;', '&cap;', '&cup;', '&int;', '&there4;', '&sim;', '&cong;', '&asymp;', '&ne;', '&equiv;', '&le;', '&ge;', '&sub;', '&sup;', '&nsub;', '&sube;', '&supe;', '&oplus;', '&otimes;', '&perp;', '&sdot;', '&lceil;', '&rceil;', '&lfloor;', '&rfloor;', '&lang;', '&rang;', '&loz;', '&spades;', '&clubs;', '&hearts;', '&diams;');
		var arr2 = new Array('&#160;', '&#161;', '&#162;', '&#163;', '&#164;', '&#165;', '&#166;', '&#167;', '&#168;', '&#169;', '&#170;', '&#171;', '&#172;', '&#173;', '&#174;', '&#175;', '&#176;', '&#177;', '&#178;', '&#179;', '&#180;', '&#181;', '&#182;', '&#183;', '&#184;', '&#185;', '&#186;', '&#187;', '&#188;', '&#189;', '&#190;', '&#191;', '&#192;', '&#193;', '&#194;', '&#195;', '&#196;', '&#197;', '&#198;', '&#199;', '&#200;', '&#201;', '&#202;', '&#203;', '&#204;', '&#205;', '&#206;', '&#207;', '&#208;', '&#209;', '&#210;', '&#211;', '&#212;', '&#213;', '&#214;', '&#215;', '&#216;', '&#217;', '&#218;', '&#219;', '&#220;', '&#221;', '&#222;', '&#223;', '&#224;', '&#225;', '&#226;', '&#227;', '&#228;', '&#229;', '&#230;', '&#231;', '&#232;', '&#233;', '&#234;', '&#235;', '&#236;', '&#237;', '&#238;', '&#239;', '&#240;', '&#241;', '&#242;', '&#243;', '&#244;', '&#245;', '&#246;', '&#247;', '&#248;', '&#249;', '&#250;', '&#251;', '&#252;', '&#253;', '&#254;', '&#255;', '&#34;', '&#38;', '&#60;', '&#62;', '&#338;', '&#339;', '&#352;', '&#353;', '&#376;', '&#710;', '&#732;', '&#8194;', '&#8195;', '&#8201;', '&#8204;', '&#8205;', '&#8206;', '&#8207;', '&#8211;', '&#8212;', '&#8216;', '&#8217;', '&#8218;', '&#8220;', '&#8221;', '&#8222;', '&#8224;', '&#8225;', '&#8240;', '&#8249;', '&#8250;', '&#8364;', '&#402;', '&#913;', '&#914;', '&#915;', '&#916;', '&#917;', '&#918;', '&#919;', '&#920;', '&#921;', '&#922;', '&#923;', '&#924;', '&#925;', '&#926;', '&#927;', '&#928;', '&#929;', '&#931;', '&#932;', '&#933;', '&#934;', '&#935;', '&#936;', '&#937;', '&#945;', '&#946;', '&#947;', '&#948;', '&#949;', '&#950;', '&#951;', '&#952;', '&#953;', '&#954;', '&#955;', '&#956;', '&#957;', '&#958;', '&#959;', '&#960;', '&#961;', '&#962;', '&#963;', '&#964;', '&#965;', '&#966;', '&#967;', '&#968;', '&#969;', '&#977;', '&#978;', '&#982;', '&#8226;', '&#8230;', '&#8242;', '&#8243;', '&#8254;', '&#8260;', '&#8472;', '&#8465;', '&#8476;', '&#8482;', '&#8501;', '&#8592;', '&#8593;', '&#8594;', '&#8595;', '&#8596;', '&#8629;', '&#8656;', '&#8657;', '&#8658;', '&#8659;', '&#8660;', '&#8704;', '&#8706;', '&#8707;', '&#8709;', '&#8711;', '&#8712;', '&#8713;', '&#8715;', '&#8719;', '&#8721;', '&#8722;', '&#8727;', '&#8730;', '&#8733;', '&#8734;', '&#8736;', '&#8743;', '&#8744;', '&#8745;', '&#8746;', '&#8747;', '&#8756;', '&#8764;', '&#8773;', '&#8776;', '&#8800;', '&#8801;', '&#8804;', '&#8805;', '&#8834;', '&#8835;', '&#8836;', '&#8838;', '&#8839;', '&#8853;', '&#8855;', '&#8869;', '&#8901;', '&#8968;', '&#8969;', '&#8970;', '&#8971;', '&#9001;', '&#9002;', '&#9674;', '&#9824;', '&#9827;', '&#9829;', '&#9830;');
		return this.swapArrayVals(s, arr1, arr2);
	},
	// Convert Numerical entities into HTML entities
	NumericalToHTML: function (s) {
		var arr1 = new Array('&#160;', '&#161;', '&#162;', '&#163;', '&#164;', '&#165;', '&#166;', '&#167;', '&#168;', '&#169;', '&#170;', '&#171;', '&#172;', '&#173;', '&#174;', '&#175;', '&#176;', '&#177;', '&#178;', '&#179;', '&#180;', '&#181;', '&#182;', '&#183;', '&#184;', '&#185;', '&#186;', '&#187;', '&#188;', '&#189;', '&#190;', '&#191;', '&#192;', '&#193;', '&#194;', '&#195;', '&#196;', '&#197;', '&#198;', '&#199;', '&#200;', '&#201;', '&#202;', '&#203;', '&#204;', '&#205;', '&#206;', '&#207;', '&#208;', '&#209;', '&#210;', '&#211;', '&#212;', '&#213;', '&#214;', '&#215;', '&#216;', '&#217;', '&#218;', '&#219;', '&#220;', '&#221;', '&#222;', '&#223;', '&#224;', '&#225;', '&#226;', '&#227;', '&#228;', '&#229;', '&#230;', '&#231;', '&#232;', '&#233;', '&#234;', '&#235;', '&#236;', '&#237;', '&#238;', '&#239;', '&#240;', '&#241;', '&#242;', '&#243;', '&#244;', '&#245;', '&#246;', '&#247;', '&#248;', '&#249;', '&#250;', '&#251;', '&#252;', '&#253;', '&#254;', '&#255;', '&#34;', '&#38;', '&#60;', '&#62;', '&#338;', '&#339;', '&#352;', '&#353;', '&#376;', '&#710;', '&#732;', '&#8194;', '&#8195;', '&#8201;', '&#8204;', '&#8205;', '&#8206;', '&#8207;', '&#8211;', '&#8212;', '&#8216;', '&#8217;', '&#8218;', '&#8220;', '&#8221;', '&#8222;', '&#8224;', '&#8225;', '&#8240;', '&#8249;', '&#8250;', '&#8364;', '&#402;', '&#913;', '&#914;', '&#915;', '&#916;', '&#917;', '&#918;', '&#919;', '&#920;', '&#921;', '&#922;', '&#923;', '&#924;', '&#925;', '&#926;', '&#927;', '&#928;', '&#929;', '&#931;', '&#932;', '&#933;', '&#934;', '&#935;', '&#936;', '&#937;', '&#945;', '&#946;', '&#947;', '&#948;', '&#949;', '&#950;', '&#951;', '&#952;', '&#953;', '&#954;', '&#955;', '&#956;', '&#957;', '&#958;', '&#959;', '&#960;', '&#961;', '&#962;', '&#963;', '&#964;', '&#965;', '&#966;', '&#967;', '&#968;', '&#969;', '&#977;', '&#978;', '&#982;', '&#8226;', '&#8230;', '&#8242;', '&#8243;', '&#8254;', '&#8260;', '&#8472;', '&#8465;', '&#8476;', '&#8482;', '&#8501;', '&#8592;', '&#8593;', '&#8594;', '&#8595;', '&#8596;', '&#8629;', '&#8656;', '&#8657;', '&#8658;', '&#8659;', '&#8660;', '&#8704;', '&#8706;', '&#8707;', '&#8709;', '&#8711;', '&#8712;', '&#8713;', '&#8715;', '&#8719;', '&#8721;', '&#8722;', '&#8727;', '&#8730;', '&#8733;', '&#8734;', '&#8736;', '&#8743;', '&#8744;', '&#8745;', '&#8746;', '&#8747;', '&#8756;', '&#8764;', '&#8773;', '&#8776;', '&#8800;', '&#8801;', '&#8804;', '&#8805;', '&#8834;', '&#8835;', '&#8836;', '&#8838;', '&#8839;', '&#8853;', '&#8855;', '&#8869;', '&#8901;', '&#8968;', '&#8969;', '&#8970;', '&#8971;', '&#9001;', '&#9002;', '&#9674;', '&#9824;', '&#9827;', '&#9829;', '&#9830;');
		var arr2 = new Array('&nbsp;', '&iexcl;', '&cent;', '&pound;', '&curren;', '&yen;', '&brvbar;', '&sect;', '&uml;', '&copy;', '&ordf;', '&laquo;', '&not;', '&shy;', '&reg;', '&macr;', '&deg;', '&plusmn;', '&sup2;', '&sup3;', '&acute;', '&micro;', '&para;', '&middot;', '&cedil;', '&sup1;', '&ordm;', '&raquo;', '&frac14;', '&frac12;', '&frac34;', '&iquest;', '&agrave;', '&aacute;', '&acirc;', '&atilde;', '&Auml;', '&aring;', '&aelig;', '&ccedil;', '&egrave;', '&eacute;', '&ecirc;', '&euml;', '&igrave;', '&iacute;', '&icirc;', '&iuml;', '&eth;', '&ntilde;', '&ograve;', '&oacute;', '&ocirc;', '&otilde;', '&Ouml;', '&times;', '&oslash;', '&ugrave;', '&uacute;', '&ucirc;', '&Uuml;', '&yacute;', '&thorn;', '&szlig;', '&agrave;', '&aacute;', '&acirc;', '&atilde;', '&auml;', '&aring;', '&aelig;', '&ccedil;', '&egrave;', '&eacute;', '&ecirc;', '&euml;', '&igrave;', '&iacute;', '&icirc;', '&iuml;', '&eth;', '&ntilde;', '&ograve;', '&oacute;', '&ocirc;', '&otilde;', '&ouml;', '&divide;', '&Oslash;', '&ugrave;', '&uacute;', '&ucirc;', '&uuml;', '&yacute;', '&thorn;', '&yuml;', '&quot;', '&amp;', '&lt;', '&gt;', '&oelig;', '&oelig;', '&scaron;', '&scaron;', '&yuml;', '&circ;', '&tilde;', '&ensp;', '&emsp;', '&thinsp;', '&zwnj;', '&zwj;', '&lrm;', '&rlm;', '&ndash;', '&mdash;', '&lsquo;', '&rsquo;', '&sbquo;', '&ldquo;', '&rdquo;', '&bdquo;', '&dagger;', '&dagger;', '&permil;', '&lsaquo;', '&rsaquo;', '&euro;', '&fnof;', '&alpha;', '&beta;', '&gamma;', '&delta;', '&epsilon;', '&zeta;', '&eta;', '&theta;', '&iota;', '&kappa;', '&lambda;', '&mu;', '&nu;', '&xi;', '&omicron;', '&pi;', '&rho;', '&sigma;', '&tau;', '&upsilon;', '&phi;', '&chi;', '&psi;', '&omega;', '&alpha;', '&beta;', '&gamma;', '&delta;', '&epsilon;', '&zeta;', '&eta;', '&theta;', '&iota;', '&kappa;', '&lambda;', '&mu;', '&nu;', '&xi;', '&omicron;', '&pi;', '&rho;', '&sigmaf;', '&sigma;', '&tau;', '&upsilon;', '&phi;', '&chi;', '&psi;', '&omega;', '&thetasym;', '&upsih;', '&piv;', '&bull;', '&hellip;', '&prime;', '&prime;', '&oline;', '&frasl;', '&weierp;', '&image;', '&real;', '&trade;', '&alefsym;', '&larr;', '&uarr;', '&rarr;', '&darr;', '&harr;', '&crarr;', '&larr;', '&uarr;', '&rarr;', '&darr;', '&harr;', '&forall;', '&part;', '&exist;', '&empty;', '&nabla;', '&isin;', '&notin;', '&ni;', '&prod;', '&sum;', '&minus;', '&lowast;', '&radic;', '&prop;', '&infin;', '&ang;', '&and;', '&or;', '&cap;', '&cup;', '&int;', '&there4;', '&sim;', '&cong;', '&asymp;', '&ne;', '&equiv;', '&le;', '&ge;', '&sub;', '&sup;', '&nsub;', '&sube;', '&supe;', '&oplus;', '&otimes;', '&perp;', '&sdot;', '&lceil;', '&rceil;', '&lfloor;', '&rfloor;', '&lang;', '&rang;', '&loz;', '&spades;', '&clubs;', '&hearts;', '&diams;');
		return this.swapArrayVals(s, arr1, arr2);
	},
	// Numerically encodes all unicode characters
	numEncode: function (s) {
		if (this.isEmpty(s)) return "";
		var e = "";
		for (var i = 0; i < s.length; i++) {
			var c = s.charAt(i);
			if (c < " " || c > "~") {
				c = "&#" + c.charCodeAt() + ";";
			}
			e += c;
		}
		return e;
	},
	// HTML Decode numerical and HTML entities back to original values
	htmlDecode: function (s) {
		var c, m, d = s;
		if (this.isEmpty(d)) return "";
		// convert HTML entites back to numerical entites first
		d = this.HTML2Numerical(d);
		// look for numerical entities &#34;
		arr = d.match(/&#[0-9]{1,5};/g);
		// if no matches found in string then skip
		if (arr != null) {
			for (var x = 0; x < arr.length; x++) {
				m = arr[x];
				c = m.substring(2, m.length - 1); //get numeric part which is refernce to unicode character
				// if its a valid number we can decode
				if (c >= -32768 && c <= 65535) {
					// decode every single match within string
					d = d.replace(m, String.fromCharCode(c));
				} else {
					d = d.replace(m, ""); //invalid so replace with nada
				}
			}
		}
		return d;
	},
	// encode an input string into either numerical or HTML entities
	htmlEncode: function (s, dbl) {
		if (this.isEmpty(s)) return "";
		// do we allow double encoding? E.g will &amp; be turned into &amp;amp;
		dbl = dbl || false; //default to prevent double encoding
		// if allowing double encoding we do ampersands first
		if (dbl) {
			if (this.EncodeType == "numerical") { s = s.replace(/&/g, "&#38;"); }
			else { s = s.replace(/&/g, "&amp;"); }
		}
		// convert the xss chars to numerical entities ' " < >
		s = this.XSSEncode(s, false);
		if (this.EncodeType == "numerical" || !dbl) {
			// Now call function that will convert any HTML entities to numerical codes
			s = this.HTML2Numerical(s);
		}
		// Now encode all chars above 127 e.g unicode
		s = this.numEncode(s);
		// now we know anything that needs to be encoded has been converted to numerical entities we
		// can encode any ampersands & that are not part of encoded entities
		// to handle the fact that I need to do a negative check and handle multiple ampersands &&&
		// I am going to use a placeholder
		// if we don't want double encoded entities we ignore the & in existing entities
		if (!dbl) {
			s = s.replace(/&#/g, "##AMPHASH##");
			if (this.EncodeType == "numerical") { s = s.replace(/&/g, "&#38;"); }
			else { s = s.replace(/&/g, "&amp;"); }
			s = s.replace(/##AMPHASH##/g, "&#");
		}
		// replace any malformed entities
		s = s.replace(/&#\d*([^\d;]|$)/g, "$1");
		if (!dbl) {
			// safety check to correct any double encoded &amp;
			s = this.correctEncoding(s);
		}
		// now do we need to convert our numerical encoded string into entities
		if (this.EncodeType == "entity") {
			s = this.NumericalToHTML(s);
		}
		return s;
	},
	// Encodes the basic 4 characters used to malform HTML in XSS hacks
	XSSEncode: function (s, en) {
		if (!this.isEmpty(s)) {
			en = en || true;
			// do we convert to numerical or html entity?
			if (en) {
				s = s.replace(/\'/g, "&#39;"); //no HTML equivalent as &apos is not cross browser supported
				s = s.replace(/\"/g, "&quot;");
				s = s.replace(/</g, "&lt;");
				s = s.replace(/>/g, "&gt;");
			} else {
				s = s.replace(/\'/g, "&#39;"); //no HTML equivalent as &apos is not cross browser supported
				s = s.replace(/\"/g, "&#34;");
				s = s.replace(/</g, "&#60;");
				s = s.replace(/>/g, "&#62;");
			}
			return s;
		}
		else { return ""; }
	},
	// returns true if a string contains html or numerical encoded entities
	hasEncoded: function (s) {
		if (/&#[0-9]{1,5};/g.test(s)) { return true; }
		else if (/&[A-Z]{2,6};/gi.test(s)) { return true; }
		else { return false; }
	},
	// will remove any unicode characters
	stripUnicode: function (s) {
		return s.replace(/[^\x20-\x7E]/g, "");
	},
	// corrects any double encoded &amp; entities e.g &amp;amp;
	correctEncoding: function (s) {
		return s.replace(/(&amp;)(amp;)+/, "$1");
	},
	// Function to loop through an array swaping each item with the value from another array e.g swap HTML entities with Numericals
	swapArrayVals: function (s, arr1, arr2) {
		if (this.isEmpty(s)) return "";
		var re;
		if (arr1 && arr2) {
			//ShowDebug("in swapArrayVals arr1.length = " + arr1.length + " arr2.length = " + arr2.length)
			// array lengths must match
			if (arr1.length == arr2.length) {
				for (var x = 0, i = arr1.length; x < i; x++) {
					re = new RegExp(arr1[x], 'g');
					s = s.replace(re, arr2[x]); //swap arr1 item with matching item from arr2	
				}
			}
		}
		return s;
	},
	inArray: function (item, arr) {
		for (var i = 0, x = arr.length; i < x; i++) {
			if (arr[i] === item) {
				return i;
			}
		}
		return -1;
	}
}

