if (!window.console) {
	window.console = {
		log : function(){},
		info : function(){},
		warn : function(){},
		error : function(){},
		debug : function(){},
		group : function(){},
		groupEnd : function(){}
	};
}
String.prototype.trim = function () {
	return this.replace(/^\s+|\s+$/g, "");
}
String.prototype.capitalize = function () {
	return this.substr(0,1).toUpperCase() + this.substr(1).toLowerCase();
}
function getElementsByClassName(parentNode, className, limitToTheseTags) {
	if (undefined == className && typeof parentNode == "string") {
		className = parentNode;
		parentNode = document;
	}
	var aResult = [];
	var c = parentNode.getElementsByTagName("*");
	for (var i = 0, ii = c.length; i < ii; i++) {
		if (c[i].className.match( new RegExp("\\b" + className + "\\b") ) ) {
			
			if ("undefined" === typeof limitToTheseTags ||
				("undefined" !== typeof limitToTheseTags && c[i].nodeName.match( new RegExp(limitToTheseTags, "i") ))
				)
			{
				aResult.push(c[i]);
			}
		}
	}
	return aResult;
}
function addEvent(o, sEvent, fFunc) {
	if (window.attachEvent) {
		o.attachEvent("on" + sEvent, fFunc);
	} else if (window.addEventListener) {
		o.addEventListener(sEvent, fFunc, false);
	}
}
function addLoadEvent(fFunc) {
	addEvent(window, "load", fFunc);
}
function addDOMLoadEvent(func) {
   if (!window.__load_events) {
      var init = function () {
          // quit if this function has already been called
          if (arguments.callee.done) return;
      
          // flag this function so we don't do the same thing twice
          arguments.callee.done = true;
      
          // kill the timer
          if (window.__load_timer) {
              clearInterval(window.__load_timer);
              window.__load_timer = null;
          }
          
          // execute each function in the stack in the order they were added
          for (var i=0;i < window.__load_events.length;i++) {
              window.__load_events[i]();
          }
          window.__load_events = null;
      };
   
      // for Mozilla/Opera9
      if (document.addEventListener) {
          document.addEventListener("DOMContentLoaded", init, false);
      }
      
      // for Internet Explorer
      /*@cc_on @*/
      /*@if (@_win32)
          document.write("<scr"+"ipt id=__ie_onload defer src=//0><\/scr"+"ipt>");
          var script = document.getElementById("__ie_onload");
          script.onreadystatechange = function() {
              if (this.readyState == "complete") {
                  init(); // call the onload handler
              }
          };
      /*@end @*/
      
      // for Safari
      if (/WebKit/i.test(navigator.userAgent)) { // sniff
          window.__load_timer = setInterval(function() {
              if (/loaded|complete/.test(document.readyState)) {
                  init(); // call the onload handler
              }
          }, 10);
      }
      
      // for other browsers
      window.onload = init;
      
      // create event function stack
      window.__load_events = [];
   }
   
   // add function to event stack
   window.__load_events.push(func);
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft, curtop];
}

function createXMLHttpObject() {
	var XMLHttpFactories = [
		function () {return new XMLHttpRequest()},
		function () {return new ActiveXObject("Msxml2.XMLHTTP")},
		function () {return new ActiveXObject("Msxml3.XMLHTTP")},
		function () {return new ActiveXObject("Microsoft.XMLHTTP")}
	];
	var xmlhttp = false;
	for (var i = 0; i < XMLHttpFactories.length; i++) {
		try {
			xmlhttp = XMLHttpFactories[i]();
		} catch (ex) {continue;}
		break;
	}
	return xmlhttp;
}

var checkNameTimeout;
function checkIfThisNameIsAvailable(oInputText){
	var delay = 500;

	if (!oInputText.value.length) {
		return;
	}
	if (!window._currentDisneyId) {
		window._currentDisneyId = oInputText.value;
	} else if (window._currentDisneyId == oInputText.value) {
		return;
	}
	window._currentDisneyId = oInputText.value;

	
	var setNameAvailabilityIndicator = function (state) {

		var msg = TextRegistry.find("errStr", oInputText.id, oInputText.form.id, "taken");
		
		var id = "disneyIdAlreadyTaken";
		var oMessage = document.getElementById(id);
		
		switch (state) {
			case "true" :
				if (!oMessage) {
					var Div = document.createElement("div");
					Div.className = "error";
					Div.id = id;
					Div.appendChild( document.createTextNode(msg) );
					oMessage = oInputText.parentNode.appendChild(Div);
				}
				oMessage.style.display = "block";
				break;
				
			default:
				if (oMessage) {
					oMessage.style.display = "none";
				}
		}
	}

	if (checkNameTimeout) {
		clearTimeout(checkNameTimeout);
	}
	
	checkNameTimeout = setTimeout(function () {

		var Gif = document.getElementById("loadInfoGif");
		if (!Gif) {
			var loadInfoGif = document.createElement("img");
			loadInfoGif.alt = "";
			loadInfoGif.src = "images/loadinfo.net.gif";
			loadInfoGif.width = 16;
			loadInfoGif.height = 16;
			loadInfoGif.id = "loadInfoGif";
			Gif = oInputText.parentNode.insertBefore(loadInfoGif, oInputText.nextSibling);
		}
		Gif.style.display = "inline";
	
		var Ajax = new createXMLHttpObject();
		Ajax.open("GET", "checkMembername.xml?membername=" + escape(oInputText.value), true);
		Ajax.setRequestHeader("User-Agent", "XMLHTTP");
		try {
			Ajax.send("checkMembername.xml?membername=" + escape(oInputText.value));
			Ajax.onreadystatechange = function(){
				if (Ajax.readyState != 4) 
					return;
				
				var aResp = Ajax.responseText.match(/<result>(.*?)<\/result>/);
				if (aResp && (typeof aResp == "object") && aResp[1]) {
					var Gif = document.getElementById("loadInfoGif");
					Gif.style.display = "none";
					setNameAvailabilityIndicator(aResp[1]);
				}
			}
		} 
		catch (ex) {
			console.error(ex);
		}
	}, delay);
} 

function getStyle(el, styleProp) {
	var o = typeof el == "String" ? document.getElementById(el) : el;
	var s;
	if (o.currentStyle)	s = o.currentStyle[styleProp];
	else if (window.getComputedStyle) s = document.defaultView.getComputedStyle(o, null).getPropertyValue(styleProp);
	return s;
}
function getFirstTag(o, tagName) {
	var tag = o.firstChild;
	if (tag && tag.nodeType && 3 == tag.nodeType) {// skip whitespace nodes
		tag = tag.nextSibling;
	}
	if (tagName && tag && (tag.nodeName != tagName.toUpperCase())) {
		tag = getNextTag(tag, tagName);
	}
	return tag;
}
function getNextTag(o, tagName) {
	var tag = o.nextSibling;
	if (tag && tag.nodeType && 3 == tag.nodeType) {// skip whitespace nodes
		tag = tag.nextSibling;
	}
	if (tagName && (tag.nodeName != tagName.toUpperCase())) {
		tag = getNextTag(tag, tagName);
	}
	return tag;
}
function getPreviousTag(o, tagName) {
	var tag = o.previousSibling;
	if (tag && tag.nodeType && 3 == tag.nodeType) {// skip whitespace nodes
		tag = tag.previousSibling;
	}
	if (tagName && (tag.nodeName != tagName.toUpperCase())) {
		tag = getPreviousTag(tag, tagName);
	}
	return tag;
}
function getParentTag(o, tagName, rxClassName) {
	while (o) {
		if (o.parentNode && o.parentNode.tagName && o.parentNode.tagName.toLowerCase() == tagName.toLowerCase()) {

			if (rxClassName && !o.parentNode.className.match(new RegExp(rxClassName))) {
				o = o.parentNode;
				continue;
			}
			
			return o.parentNode;
		}
		o = o.parentNode;
	}
	return null;
}

/*
 * Wrapper for HitBox logging.
 */
function hitMe(pageName) {
	if (!window._hbflash || !window._mlc) return; // The page is probably still loading.
	_hbflash(pageName, _mlc, "n", "n");
}




function showdetails(o, t) {
	var aD = ["credit", "bt", "paypal", "wallie"];
	for (var i = 0; i < aD.length; i++)	{
		if (document.getElementById("detail_" + aD[i])) {
			document.getElementById("detail_" + aD[i]).style.display = (t == aD[i] && o.checked)
				? "block"
				: "none";
		}
	}
}

function initPaymentTools() {
	var oCardRadio = document.getElementById("paymentToolCard"); 
	if (!oCardRadio) {
		return false;// page has no payment tool - nothing to do
	}
	var currentValue = oCardRadio.form.elements.length;
	for (var i = 0, ii = currentValue; i < ii; i++) {
		if (!oCardRadio.form.elements[i].name
			|| oCardRadio.form.elements[i].name != "newPaymentToolType"
			|| !oCardRadio.form.elements[i].checked) {
			continue;
		}
		oCardRadio.form.elements[i].click();
	}
}
//addLoadEvent(initPaymentTools);



function copyMyPostalAddress(f) {
	while (f.nodeName.toUpperCase() != "FORM") {
		f = getParentTag(f, "form");
	}

	f.cardAddress1.value = f.addressLine1.value;
	f.cardAddress2.value = f.addressLine2.value;
	f.cardAddress3.value = f.addressLine3.value;
	f.cardTown.value = 	f.town.value;
	f.cardPostCode.value = f.postCode.value;
	f.cardCountry.selectedIndex = f.countryCode.selectedIndex;
}




/**
 * Adds skin to the <button> tags
 */
function initButtons() {
	var aConfAvailableButtonStyles = ["mini", "small", "big", "iur", "red"];

	var msieVersion = navigator.appVersion.match(/MSIE (\d+\.?\d*)/);
	
	var classNameRegEx = new RegExp("\\b(" + aConfAvailableButtonStyles.join("|") + ")\\b", "i");
	var d, s1, s2;
	var cButtons = document.getElementsByTagName("button");
	for (var i = 0, ii = cButtons.length; i < ii; i++) {
		if (classNameRegEx.test(cButtons[i].className) && !cButtons[i].initialized) {
			
			if (!cButtons[i].getAttribute("type")) cButtons[i].setAttribute("type", "button");

			d = document.createElement("div");
			d.innerHTML = cButtons[i].innerHTML;
			
			cButtons[i].innerHTML = "";
			
			s1 = document.createElement("span");
			s1.className = "left";
			s2 = document.createElement("span");
			s2.className = "right";
			
			if (document.all && msieVersion && msieVersion.length && msieVersion[1] && parseFloat(msieVersion[1]) < 7) {
				cButtons[i].appendChild(s1);
				cButtons[i].appendChild(s2);
				cButtons[i].appendChild(d);
			} else {
				d.appendChild(s1);
				d.appendChild(s2);
				cButtons[i].appendChild(d);
			}

			cButtons[i].onmousedown = function () {
				var oDiv = this.getElementsByTagName("div")[0];
				oDiv.className = oDiv.className.replace(/\bmousedown\b/gi, "") + " mousedown";
			};
			cButtons[i].onmouseup = function () {
				var oDiv = this.getElementsByTagName("div")[0];
				oDiv.className = oDiv.className.replace(/\bmousedown\b/gi, "");
				if (this.firstChild
					&& this.firstChild.nextSibling
					&& this.firstChild.nextSibling.nextSibling
					&& this.firstChild.nextSibling.nextSibling.firstChild
					&& this.firstChild.nextSibling.nextSibling.firstChild.nodeName == "A"
					&& this.firstChild.nextSibling.nextSibling.firstChild.href)
				{
					location = this.firstChild.nextSibling.nextSibling.firstChild.href; 
				}
			};
			
			cButtons[i].initialized = true;
		}
	}
}
/*
if (!document.all) addDOMLoadEvent(initButtons);// Unfortunately this doesn't work in MSIE
else
*/ 
addLoadEvent(initButtons);



/**
 * Used in the new launcher pages.
 */
function initOutageBar() {
	var OutageBar = getElementsByClassName(document, "outagebar", "div");
	if (!OutageBar || !OutageBar.length) {
		return;
	}
	OutageBar = OutageBar[0];
	
	var T = document.createElement("table");
	T.className = "outagebar";
	var Tb = document.createElement("tbody");

	var Tr1 = document.createElement("tr");
	var TdNw = document.createElement("td");
	TdNw.className = "nw";
	var TdN = document.createElement("td");
	TdN.className = "n";
	var TdNe = document.createElement("td");
	TdNe.className = "ne";
	Tr1.appendChild(TdNw);
	Tr1.appendChild(TdN);
	Tr1.appendChild(TdNe);
	Tb.appendChild(Tr1);

	var Tr2 = document.createElement("tr");
	var TdW = document.createElement("td");
	TdW.className = "w";
	var TdContent = document.createElement("td");
	TdContent.className = "content";
		TdContent.innerHTML = OutageBar.innerHTML; 
	var TdE = document.createElement("td");
	TdE.className = "e";
	Tr2.appendChild(TdW);
	Tr2.appendChild(TdContent);
	Tr2.appendChild(TdE);
	Tb.appendChild(Tr2);

	var Tr3 = document.createElement("tr");
	var TdSw = document.createElement("td");
	TdSw.className = "sw";
	var TdS = document.createElement("td");
	TdS.className = "s";
	var TdSe = document.createElement("td");
	TdSe.className = "se";
	Tr3.appendChild(TdSw);
	Tr3.appendChild(TdS);
	Tr3.appendChild(TdSe);
	Tb.appendChild(Tr3);
	
	T.appendChild(Tb);
	
	OutageBar.parentNode.replaceChild(T, OutageBar);
}
addLoadEvent(initOutageBar);


/**
 * Create navigation groups by giving them the following CSS classname pattern:
 * navigroup-[unique group name]
 * 
 * <button> and/or <a> tags.
 * 
 * ex.: <a href="#" class="something navigroup-cancelregistration">Cancel</a> <button class="big navigroup-cancelregistration">Next</button>  <button class="big navigroup-cancelregistration">Cancel</button>
 */
function initNaviGroups() {
	window.__aNaviGroups = [];
	
	function iterate(cObj) {
		for (var i = 0, ii = cObj.length; i < ii; i++) {
			if (!cObj[i].className.match(/\bnavigroup-/)) continue;// Skip the irrelevant elements.
			
			var groupname = cObj[i].className.match(/\bnavigroup-([\S]+)/)[1];
			if (!window.__aNaviGroups[groupname]) window.__aNaviGroups[groupname] = [];
			window.__aNaviGroups[groupname].push(cObj[i]);
	
			cObj[i].naviGroupName = groupname;
			addEvent(cObj[i], "click", function (e) {
				e = e || window.event;
				var o = e.target || e.srcElement;
				var groupname = o.naviGroupName;
				
				if (o.disabled) {// We have to manually disable the <a> tag.
					if (e.preventDefault) e.preventDefault();// FF
					return false;// MSIE
				}
				
				for (var i in window.__aNaviGroups[groupname]) {
					window.__aNaviGroups[groupname][i].disabled = true;
					window.__aNaviGroups[groupname][i].className += " disabled";
					if (window.__aNaviGroups[groupname][i].tagName == "A") {
						window.__aNaviGroups[groupname][i].onclick = function () {return false};
					}
				}
			});
		}
	}
	iterate(document.getElementsByTagName("button"));
	iterate(document.getElementsByTagName("a"));
}
addLoadEvent(initNaviGroups);



var ELEM_WIDTHS = 1;
var ELEM_HEIGHTS = 2;
/**
* Array([ELEM_WIDTHS | ELEM_HEIGHTS | ELEM_WIDTHS + ELEM_HEIGHTS], Array(String elementId, String elementId,...)) Element dimension(s) and elements to be equalized.
*/
var aEqElems = []; //comment
function equalizeElementDimensions()
{
	for (var i = 0; i < aEqElems.length; i++)
	{
		var maxWidth = 0;
		var maxHeight = 0;
		for (var j = 0; j < aEqElems[i][1].length; j++)
		{
			var o = document.getElementById(aEqElems[i][1][j]);
			if (!o) continue;
			
			if (o.tagName == "BUTTON") {
				o = getFirstTag(o, "div");
			}
			if (o)
			{
				maxWidth = Math.max(
									maxWidth,
									o.offsetWidth
									);
				maxHeight = Math.max(
									maxHeight,
									o.offsetHeight
									);
			}
		}
		for (var j = 0; j < aEqElems[i][1].length; j++)
		{
			if (document.getElementById(aEqElems[i][1][j]))
			{
				o = document.getElementById(aEqElems[i][1][j]);
				if (!o) continue;
				
				if (aEqElems[i][0] == 3 || aEqElems[i][0] == 1)
				{
					if (o.tagName == "BUTTON") {
						o = getFirstTag(o, "div");
						if (o) o.style.width = maxWidth + "px";
						else setTimeout(equalizeElementDimensions, 250);// MSIE bugfix, of course
					} else {
						o.style.width = maxWidth + "px";
					}
				}
				if (aEqElems[i][0] == 3 || aEqElems[i][0] == 2)
				{
					if (o.tagName == "BUTTON") {
						o = getFirstTag(o, "div");
						if (o) o.style.height = maxHeight + "px";
						else setTimeout(equalizeElementDimensions, 250);// MSIE bugfix, of course
					} else {
						o.style.height = maxHeight + "px";
					}
				}
			}
		}
	}
}
//addDOMLoadEvent(equalizeElementDimensions);
addLoadEvent(equalizeElementDimensions);// To fine-adjust after the images are loaded.



function initFaqTree()
{
	if (!document.getElementById("faqTree")) return;
	
	document.getElementById("faqTree").onclick = function (e) {
		e = e || window.event;
		var oClicked = e.target || e.srcElement;
		var oClickedParent = oClicked.parentNode;
		
		if (oClickedParent.className.match(/\bleaf\b/)) return;
		if (oClicked.nodeName != "A" || oClickedParent.nodeName != "LI") return;
		
		oClicked.href = "javascript:;";
		
		if (oClickedParent.className.match(/list_item_closed/)) {
			oClickedParent.className = "list_item_open";
		} else {
			oClickedParent.className = "list_item_closed";
		}
		var aCookieData = [];
		if (readCookie("faq")) {
			aCookieData = readCookie("faq").split(",");
		}
		aCookieData[ oClickedParent.id.substr(2) ] = oClickedParent.className.match(/list_item_closed/) ? "f" : "t";
		
		createCookie("faq", aCookieData.join(), 0);
		faqToggleExpandAllIfNeeded();
	}
	
	var aCookieData = [];
	if (readCookie("faq")) {
		aCookieData = readCookie("faq").split(",");
	}

	var liCounter = 0;
	var cUl = document.getElementById("faqTree").getElementsByTagName("li");
	for (var i = 0, ii = cUl.length; i < ii; i++) {
		if (cUl[i].className.indexOf("list_item_") > -1) {
			if (!location.search.match(/[?&]cat=/)) {// The categories were opened/closed by server side code, no need to touch them.
				cUl[i].className = ("t" == aCookieData[liCounter])
					? "list_item_open"
					: "list_item_closed";
			}
			aCookieData[liCounter] = (cUl[i].className == "list_item_closed")
				? "f"
				: "t";
			
			cUl[i].id = "LI" + liCounter;
			liCounter++;
		}
	}
	createCookie("faq", aCookieData.join(), 0);
	faqToggleExpandAllIfNeeded();
}
function toggleFaqCategories() {
	var aCookieData = readCookie("faq").split(",");
	
	var cUl = document.getElementById("faqTree").getElementsByTagName("li");
	
	for (var i = 0, ii = cUl.length; i < ii; i++) {
		if (cUl[i].className.indexOf("list_item_") > -1) {
			var thisId = cUl[i].getAttribute("id").substr(2);
			if (faqButtonState == "Close") {
				cUl[i].className = "list_item_closed";
				aCookieData[thisId] = "f";
			} else {
				if (cUl[i].getElementsByTagName("LI").length && cUl[i].getElementsByTagName("LI")[0].className.match(/^list_/)) {
					cUl[i].className = "list_item_open";
					aCookieData[thisId] = "t";
				} else {
					cUl[i].className = "list_item_closed";
					aCookieData[thisId] = "f";
				}
			}
		}
	}
	
	createCookie("faq", aCookieData.join(), 0);
	faqToggleExpandAllIfNeeded()
}
addLoadEvent(initFaqTree);

var faqCloseAllLabel  = null;
var faqExpandAllLabel = null;
var faqButtonState = null;
function faqToggleExpandAllIfNeeded() {
	if (faqCloseAllLabel == null) {
		faqCloseAllLabel  = document.getElementById("faqButtonLabel").innerHTML;
		faqExpandAllLabel = document.getElementById("faqButtonLabel2").innerHTML;
	}
	
	var shouldTransform = false;

	var a = document.getElementById("faqTree").firstChild;
	var len = 0, cnt = 0;
	while (a) {
		if (a.nodeName == "UL") {
			len++;
			
			if (a.getElementsByTagName("LI")[0].className == "list_item_open") {
				shouldTransform = true;
				faqButtonState = "Close";
				break;
			}
			if (a.getElementsByTagName("LI")[0].className == "list_item_closed") {
				cnt++;
			}
		}
		a = a.nextSibling;
	}
	if (!shouldTransform && len == cnt) {
		shouldTransform = true;
		faqButtonState = "Expand";
	}
	
	if (shouldTransform) {
		document.getElementById("faqButtonLabel").innerHTML = (faqButtonState == "Close")
			? faqCloseAllLabel
			: faqExpandAllLabel;
	}
}



function toggleSection(sId, e) {
	if (!document.getElementById(sId)) return;
	
	var newState = ("block" == document.getElementById(sId).style.display)
		? "none"
		: "block";
	document.getElementById(sId).style.display = newState;
	
	if (newState == "none") {
		e.parentNode.className = e.parentNode.className.replace(/sectionOpen/, "") + " sectionClosed";
	} else {
		e.parentNode.className = e.parentNode.className.replace(/sectionClosed/, "") + " sectionOpen";
	}
}
function autoOpenSections() {// For myAccount pages. Opens those sections which has error (server-side) messages.
	var h2;
	var cErrorFields = document.getElementsByTagName("*");
	for (var i = 0, ii = cErrorFields.length; i < ii; i++) {
		if (cErrorFields[i].className.match(/\berrormsg\b/)) {
			if (cErrorFields[i].innerHTML.trim().length
				&&
				cErrorFields[i].parentNode.className.match(/\bformSection\b/i)
				) {
				cErrorFields[i].style.display = "block";
				cErrorFields[i].parentNode.style.display = "block";
					
				h2 = document.getElementById("header" + cErrorFields[i].parentNode.id.replace(/^section/, ""));
				if (h2) h2.className = h2.className.replace(/\bsectionClosed\b/, "sectionOpen");
			}
		}
	}
}
addLoadEvent(autoOpenSections);








function createCookie(name,value,days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}






/**
* Validator attributes:
*
* datatype = {string|int|float|email|month|day|year}
* mandatory = {true|false}
* ifchecked = {ID of a checkbox or a radio} If it is checked, then this attribute is mandatory
* ifselected = {ID of a drop-down combo box} If it is set to the index or value defined by the selectedIndexes or selectedValues, then this attribute is mandatory
*	selectedIndexes | selectedValues
* mandatoryradiogroup = {true|false} One of them must be checked
* minlength = {int}
* maxlength = {int}
* minvalue = {int}
* maxvalue = {int}
* pattern = {regular expression}
* equalsto = {ID of an other element} The value of this element must equal to the value of the target element.
* filextension = valid extensions separated by spaces or commas. Case insensitive.
*
* Additional attributes:
*
* label = {string} When the target <label> is not set by the element's ID.
* errormsg = {string} To override the errormessage for the element.
*            If it is not present, the error message's key would be the
*            name of the validator attribute, then a hyphen, then the ID
*            of the element, eg: "mandatory-firstName" or "minlength-firstName")
* errorbox {string} The ID of the HTML element which will display the error messages.
* onerrorshow {string} The ID of the HTML element which is to be displayed
*                      (via document.getElementById({string}).style.display="block")
*/
var disableUnloadWarning = false;
var aValidatedRadioGroups = [];
function validate(f, funcBeforeSubmit, notForSubmission)
{
	if (f.alreadySubmitted) {
		//alert("TempMessage: Already submitted.");
		return true;
	}
	
	var isValid = true;
	var oCurrElem, validatorValue, modFunc, elemLabel, tmp, errMsg;
	var forAttrName = (document.all) ? "htmlFor" : "for";
	var classAttrName = (document.all) ? "className" : "class";
	aValidatedRadioGroups = [];
	
	// Preparing for new validator
	var aIdMap = {
		dayStr : "day",
		disneyId : "membername",
		addressLine1 : "address_line1",
		country : "card_country",
		nameOnCard : "nameoncard",
		cardNumber : "cardnumber",
		cardPostCode : "card_post_code",
		cardAddress1 : "card_address1",
		cardTown : "card_town",
		expMonth : "expirymonth",
		expYear : "expiryyear",
		firstName : "firstname",
		surName : "surname",
		parentEmail : "parentemail",
		havePermissionToRegister : "ihavepermission",
		newPassword : "pwd1",
		confirmNewPassword : "pwd2",
		newPasswordHint : "hint",
		postCode : "postcode",
		securityCode : "securitycode",
		iAcceptTC : "iaccepttc",
		birthYear : "birthyear"
	};
	
	// Validation order
	var aAttrs = [
		"datatype",
		"mandatory",
		"ifchecked",
		"ifselected",
		"mandatoryradiogroup",
		"minlength",
		"maxlength",
		"minvalue",
		"maxvalue",
		"pattern",
		"equalsto",
		"fileextension"
	];

	// Reset the errorboxes
	var aErrorBoxes = [];
	for (var i = 0, j = f.elements.length; i < j; i++)
	{
		if (f.elements[i].getAttribute("errorbox"))
		{
			aErrorBoxes[f.elements[i].getAttribute("errorbox")] = [];// messages in this box
		}
	}
	for (var i in aErrorBoxes)
	{
		if (typeof(aErrorBoxes[i]) == "function") continue;
		
		if (document.getElementById(i))
		{
			document.getElementById(i).innerHTML = "";
			document.getElementById(i).style.visibility = "hidden";
			
			// Reset the section texts as well (remove the error CSS class)
			if (document.getElementById( i + "_text" ))
			{
				o = document.getElementById( i + "_text" );
				tmp = o.getAttribute(classAttrName);
				o.setAttribute(classAttrName, tmp.replace(/\berror\b/g));
			}
		}
	}
	
	// Reset the labels
	var oLabels = f.getElementsByTagName("label");
	for (var k = 0, kk = oLabels.length; k < kk; k++)
	{
		tmp = oLabels[k].getAttribute(classAttrName);
		tmp = ("string" != typeof(tmp) ? "" : tmp)
		
		oLabels[k].setAttribute(classAttrName, tmp.replace(/\berror\b/, ""));
	}

	for (var i = 0, ii = f.elements.length; i < ii; i++)
	{
		oCurrElem = f.elements[i];
		
		for (j in aAttrs)
		{
			validatorValue = oCurrElem.getAttribute(aAttrs[j]);
			
			// If we have to validate against this attribute...
			if (null != validatorValue)
			{
				modFunc = "validate" + aAttrs[j].capitalize();
				
				// If we have this validator function...
				if (window[modFunc])
				{
					// To which label this element refers to?
					elemLabel = oCurrElem.id;
					tmp = oCurrElem.getAttribute("label");
					if (null != tmp)
					{
						elemLabel = tmp;
					}
					
					var oLabels = f.getElementsByTagName("label");
					for (var k = 0, kk = oLabels.length; k <= kk; k++)
					{
						// k == kk -> When there is no label for the element.
						if (k == kk || elemLabel == oLabels[k].getAttribute(forAttrName))
						{
							// Failed to validate, mark the label
							if (!window[modFunc](oCurrElem, validatorValue))
							{
								isValid = false;
								
									
								// Mark the section text as error
								o = document.getElementById( oCurrElem.getAttribute("errorbox") + '_text' );
								if (o)
								{
									tmp = o.getAttribute(classAttrName);
									tmp = ("string" != typeof(tmp) ? "" : tmp);
									o.setAttribute(classAttrName, tmp.replace(/\berror\b/g) + " error");
								}
								if (oLabels[k])
								{
									tmp = oLabels[k].getAttribute(classAttrName);
									tmp = ("string" != typeof(tmp) ? "" : tmp);
									oLabels[k].setAttribute(classAttrName, tmp.replace(/\berror\b/g) + " error");
								}
								
								// Add the appropriate error message
								if (oCurrElem.getAttribute("errorbox"))
								{
									if (null != oCurrElem.getAttribute("errormsg"))
									{
										if ("undefined" != typeof(aMsg[oCurrElem.getAttribute("errormsg").toLowerCase()]))
										{
											
											errMsg = aMsg[oCurrElem.getAttribute("errormsg").toLowerCase()];
										}
										else
										{
											errMsg = "::: {" + oCurrElem.getAttribute("errormsg") + "}";
										}
									}
									else if ("undefined" != typeof(aMsg[(aAttrs[j] + "-" + oCurrElem.id).toLowerCase()]))
									{
										errMsg = aMsg[(aAttrs[j] + "-" + oCurrElem.id).toLowerCase()]
									}
									else if ("undefined" != typeof(aMsg[(aAttrs[j] + "-" + aIdMap[oCurrElem.id]).toLowerCase()]))
									{
										errMsg = aMsg[(aAttrs[j] + "-" + aIdMap[oCurrElem.id]).toLowerCase()]
									}
									else
									{
										errMsg = "::: {" + aAttrs[j] + '-' + oCurrElem.id + "}"
									}
									
									aErrorBoxes[oCurrElem.getAttribute("errorbox")][errMsg] = errMsg;
										
									document.getElementById(oCurrElem.getAttribute("errorbox")).style.display = "block"
									document.getElementById(oCurrElem.getAttribute("errorbox")).style.visibility = "visible"
								}
								
								// Display the section if needed
								if (oCurrElem.getAttribute("onerrorshow"))
								{
									o = document.getElementById(oCurrElem.getAttribute("onerrorshow"));
									o.style.display = "block";
									
									// We have to change the CSS class for the <h2> tag before this <div>
									// sectionClosed -> sectionOpen
									var h2 = document.getElementById(oCurrElem.getAttribute("onerrorshow").replace(/^section/, "header"));
									if (h2)
									{
										h2.setAttribute(classAttrName, h2.getAttribute(classAttrName).replace("sectionClosed", "sectionOpen"));
									}
								}
							}
							break;
						}
					}
				}
			}
		}
	}
	
	if (isValid)
	{
		disableUnloadWarning = true;
		if (funcBeforeSubmit && typeof(funcBeforeSubmit) == "function")
		{
			funcBeforeSubmit();
		}
		
		// Let's shield the whole page so the user cannot click on anything.
		var oShield = document.createElement("div");
		oShield.id = "oSubmitShield";
		oShield.style.position = "absolute";
		oShield.style.zIndex = "123456";
		oShield.style.width = "100%";
		oShield.style.height = document.body.clientHeight + "px";
		oShield.style.top = "0";
		oShield.style.left = "0";
		oShield.style.background = "url(images/_blank.gif)";
		oShield = document.getElementsByTagName("body")[0].appendChild(oShield);
		// After a while remove the shield:
		setTimeout("var oShield = document.getElementById('oSubmitShield'); oShield.parentNode.removeChild(oShield)"
			, 60000);// 60000 = 1 minute
		
		f.alreadySubmitted = true;
		setReadOnly(f);
		
		//only submit the form if the form submission was not disabled
		if (!notForSubmission) {
			f.submit();
		}
		window.onbeforeunload = null;
		return true;
	}
	for (var i in aErrorBoxes)
	{
		if (typeof(aErrorBoxes[i]) == "function") continue;
		
		for (var j in aErrorBoxes[i])
		{
			if (typeof(aErrorBoxes[i][j]) == "function") continue;
			
			if (aErrorBoxes[i] && aErrorBoxes[i][j] && document.getElementById(i))
			{
				var o = document.createElement("div");
				o.innerHTML = j;
				document.getElementById(i).appendChild(o);
			}
		}
	}
	
	alert(aMsg["formErrorAlert"]);
	return false;
}

function setReadOnly (oForm, oButton) {
	var oHidden, oSelect;
	
	if (oButton && oForm.isReadOnly) {
		return;
	}
	oForm.isReadOnly = true;
	var buttons = oForm.getElementsByTagName("button");
	for (var i = 0, ii = buttons.length; i < ii; i++) {
		buttons[i].onclick = null;
	}
	
	for (var i = 0; i < oForm.elements.length; i++) {
		oForm.elements[i].readOnly = "readOnly";// camelCase because of MSIE
		oForm.elements[i].setAttribute("readonly", "readonly");
		if (oForm.elements[i].className != "hiddenSubmit" && oForm.elements[i].type != "file") {
			oForm.elements[i].style.opacity = "0.4";
			oForm.elements[i].style.filter = "alpha(opacity=40)";
		}
		
		if (oForm.elements[i].nodeName.toLowerCase() == "select") {
			oForm.elements[i].disabled = "disabled";
			oHidden = document.createElement("input");
			oHidden.type = "hidden";
			oHidden.name = oForm.elements[i].name;
			oHidden.value = oForm.elements[i].value;
		}
		if (oForm.elements[i].type && (oForm.elements[i].type.toLowerCase() == "checkbox" || oForm.elements[i].type.toLowerCase() == "radio")) {
			oForm.elements[i].disabled = "disabled";
			if (oForm.elements[i].checked) {
				oHidden = document.createElement("input");
				oHidden.type = "hidden";
				oHidden.name = oForm.elements[i].name;
				oHidden.value = oForm.elements[i].value;
			}
		}

		if (oHidden) {
			if (oForm.elements[i].nextSibling) {
				oForm.elements[i].parentNode.insertBefore(oHidden, oForm.elements[i].nextSibling);
			} else {
				oForm.appendChild(oHidden, oForm.elements[i]);
			}
			oHidden = null;
		}
	}
}

/**
* @param Object
* @param String {string|int|float?|email|month|day|year}
*/
function validateDatatype(oCurrElem, validatorValue)
{
	if (oCurrElem.value.length)
	{
		switch (validatorValue)
		{
			case "string":
				return true;
				break;
			
			case "int":
				return oCurrElem.value.match(/^-?[0-9]+$/);
				break;
			
			case "float":
				return oCurrElem.value.match(/^-?[0-9]+(\.[0-9]+)?$/);
				break;
			
			case "email":
				return oCurrElem.value.match(/^\S+@\S+\.\S+$/);
				break;
			
			case "month":
				return (!isNaN(oCurrElem.value)
							   && 1 <= oCurrElem.value
							   && 12 >= oCurrElem.value);
				break;
			
			case "day":
				return (!isNaN(oCurrElem.value)
							   && 1 <= oCurrElem.value
							   && 31 >= oCurrElem.value);
				break;
			
			case "year":
				return oCurrElem.value.match(/^[0-9]{4}$/);
				break;
		}
	}
	return true;
}

/**
* @param Object
* @param String {true|false}
*/
function validateMandatory(oCurrElem, validatorValue)
{
	if ("true" == validatorValue)
	{
		if ("input" == oCurrElem.tagName.toLowerCase())
		{
			if (
				"checkbox" == oCurrElem.getAttribute("type").toLowerCase()
				|| "radio" == oCurrElem.getAttribute("type").toLowerCase()
				)
			{
				return oCurrElem.checked;
			}
			else
			{
				return (oCurrElem.value.length > 0);
			}
		}
		if ("textarea" == oCurrElem.tagName.toLowerCase())
		{
			return (oCurrElem.value.length > 0);
		}
		if ("select" == oCurrElem.tagName.toLowerCase())
		{
			return oCurrElem.selectedIndex > 0
		}
	}
	return true;
}

/**
* @param Object
* @param String List of IDs, separated by comma and/or white-space.
*/
function validateIfchecked(oCurrElem, validatorValue)
{
	var aIdList = validatorValue.split(/[,\s]+/);
	var oRef;
	for (var i = 0, ii = aIdList.length; i < ii; i++) {
		oRef = document.getElementById(aIdList[i]);
		if (
				(
					oRef.nodeName.toLowerCase() == "input"
						&&
					(oRef.type == "text" || oRef.type == "password")
						&&
					!oRef.value.length
				)
					||
				(
					oRef.nodeName.toLowerCase() == "textarea"
						&&
					!oRef.value.length
				)
					||
				(
					oRef.nodeName.toLowerCase() == "input"
						&&
					(oRef.type == "checkbox" || oRef.type == "radio")
						&&
					!oRef.checked
				)
			)
		{
			return true;
		}
	}
	if ("input" == oCurrElem.tagName.toLowerCase())
	{
		if (
			"checkbox" == oCurrElem.getAttribute("type").toLowerCase()
			|| "radio" == oCurrElem.getAttribute("type").toLowerCase()
			)
		{
			return oCurrElem.checked;
		}
		else
		{
			return (oCurrElem.value.length > 0);
		}
	}
	if ("textarea" == oCurrElem.tagName.toLowerCase())
	{
		return (oCurrElem.value.length > 0);
	}
	if ("select" == oCurrElem.tagName.toLowerCase())
	{
		return oCurrElem.selectedIndex > 0
	}
	
	return true;
}

/**
* @param Object
* @param String {true|false}
*/
function validateMandatoryradiogroup(oCurrElem, validatorValue)
{
	var currentName = oCurrElem.getAttribute("name");
	
//	if ("true" == validatorValue && !aValidatedRadioGroups.contains(currentName))
	if ("true" == validatorValue)
	{
		aValidatedRadioGroups.push(currentName);
		
		// Remove the "mandatoryradiogroup", "errorbox" and "errormsg" attribute from all but one radio.
		var cRadios = oCurrElem.form.getElementsByTagName("INPUT");
		var foundTheGroup = false; 
		for (var i = 0, ii = cRadios.length; i < ii; i++)
		{
			if (cRadios[i].getAttribute("type").toLowerCase() == "radio" && cRadios[i].getAttribute("name") == currentName)
			{
				if (!foundTheGroup)
				{
					foundTheGroup = true;
					continue;
				}
				cRadios[i].removeAttribute("mandatoryradiogroup");
				cRadios[i].removeAttribute("errorbox");
				cRadios[i].removeAttribute("errormsg");
			}
		}
		
		var oFormElems = oCurrElem.form.elements;
		
		for (var i = 0, ii = oFormElems.length; i < ii; i++)
		{
			if (oFormElems[i].tagName.toLowerCase() == "input"
					&& "radio" == oFormElems[i].getAttribute("type")
					&& currentName == oFormElems[i].getAttribute("name")
					&& oFormElems[i].checked
				)
			{
				return true;
			}
		}
 		return false;
	}
	return true;
}

/**
* @param Object
* @param Int
*/
function validateMinlength(oCurrElem, validatorValue)
{
	if (oCurrElem.value.length)
	{
		return oCurrElem.value.toString().length >= parseInt(validatorValue,10);
	}
	return true;
}

/**
* @param Object
* @param Int
*/
function validateMaxlength(oCurrElem, validatorValue)
{
	if (oCurrElem.value.length)
	{
		return oCurrElem.value.toString().length <= parseInt(validatorValue,10);
	}
	return true;
}

/**
* @param Object
* @param Int
*/
function validateMinvalue(oCurrElem, validatorValue)
{
	if (oCurrElem.value.length)
	{
		return parseInt(oCurrElem.value,10) >= parseInt(validatorValue,10);
	}
	return true;
}

/**
* @param Object
* @param Int
*/
function validateMaxvalue(oCurrElem, validatorValue)
{
	if (oCurrElem.value.length)
	{
		return parseInt(oCurrElem.value,10) <= parseInt(validatorValue,10);
	}
	return true;
}

/**
* @param Object
* @param String (regular expression)
*/
function validatePattern(oCurrElem, validatorValue)
{
	if (oCurrElem.value.length)
	{
		return RegExp(validatorValue).test(oCurrElem.value);
	}
	return true;
}

function validateEqualsto(oCurrElem, validatorValue)
{
	if (document.getElementById(validatorValue) && oCurrElem.value == document.getElementById(validatorValue).value)
	{
		return true;
	}
	return false;
}

function validateIfselected(oCurrElem, validatorValue)
{
	var checkItem = document.getElementById(validatorValue);
	if (checkItem) {
		var selectedIndexes = oCurrElem.getAttribute("selectedIndexes");
		var selectedValues = oCurrElem.getAttribute("selectedValues");
		if (selectedIndexes != "") {
			var selectedIndexArray = selectedIndexes.split(" ");
			for (i = 0; i < selectedIndexArray.length; i++) {
				if (oCurrElem.value == "" && selectedIndexArray[i] == checkItem.selectedIndex) {
					return false;
				}
			}
		} else if (selectedValues != "") {
			var selectedValuesArray = selecteValues.split(" ");
			for (i=0; i<selectedValuesArray.length; i++) {
				if (oCurrElem.value == "" && selectedValuesArray[i] == checkItem.value) {
					return false;
				}
			}
		}
	}
	return true;
}

/**
* @param Object
* @param String (regular expression)
*/
function validateFileextension(oCurrElem, validatorValue)
{
	if (!oCurrElem.value.length)
	{
		return true;
	}
	
	var aExtensions = validatorValue.split(/[\s,]/);
	
	var currExtension = oCurrElem.value.match(/\.[^.]+$/)[0].substr(1).toLowerCase();
	for (var i in aExtensions)
	{
		if (currExtension == String(aExtensions[i]).toLowerCase())
		{
			return true;
		}
	}
	
	return false;
}



var unsavedCheckFormId = null;
var aDefaultFormValues = new Array();
var shouldAlertOnUnloadWhenAbandonsChanges = true;
var abandonUrl = null;
// Returns true if the form was modified since the last submit.
function unsavedCheck()
{
	for (var i in aDefaultFormValues)
	{
		switch (aDefaultFormValues[i]["type"])
		{
			case "text":
			case "password":
				if (aDefaultFormValues[i]["value"] != aDefaultFormValues[i]["o"].value)
				{
					return true;
				}
				break;
			case "checkbox":
				if (aDefaultFormValues[i]["checked"] != aDefaultFormValues[i]["o"].checked)
				{
					return true;
				}
				break;
			case "select":
				if (aDefaultFormValues[i]["selectedIndex"] != aDefaultFormValues[i]["o"].selectedIndex)
				{
					return true;
				}
				break;
		}
	}
	return false;
}
// Call it like this: <a href="the url" onclick="return checkIfFormWasModified(this.href)">...</a>
function checkIfFormWasModified(href)
{
	if (unsavedCheck())
	{
		// Display "confirm div".
		document.getElementById("wantToLoseChanges").style.display = "block";
		abandonUrl = href;
		return false;
	}
	else
	{
		return true;
	}
}
function userWantsToAbandonChanges(bDecision)
{
	document.getElementById("wantToLoseChanges").style.display = "none";
	if (bDecision)
	{
		shouldAlertOnUnloadWhenAbandonsChanges = false;
		window.location = abandonUrl;
	}
}
function formModifiedunloadListener(url, name)
{
	if (!disableUnloadWarning && unsavedCheck() && shouldAlertOnUnloadWhenAbandonsChanges)
	{
		alert(document.getElementsByTagName("body")[0].txtWarnUnsavedChangesLost);
	}
}
function registerUnsavedCheckOnUnload(sFormId)
{
	unsavedCheckFormId = sFormId;
	
	// Store the default values/states of the form
	for (var i = 0, ii = document.forms[unsavedCheckFormId].length; i < ii; i++)
	{
		var o = document.forms[unsavedCheckFormId][i];
				
		switch (o.tagName.toLowerCase())
		{
			case "input":
				switch (o.getAttribute("type").toLowerCase())
				{
					case "text":
					case "password":
						var aFormElem = new Array();
						aFormElem["o"] = o;
						aFormElem["type"] = o.getAttribute("type").toLowerCase();
						aFormElem["value"] = o.value;
						break;
						
					case "checkbox":
						var aFormElem = new Array();
						aFormElem["o"] = o;
						aFormElem["type"] = "checkbox";
						aFormElem["checked"] = o.checked;
						break;
				}
				
				break;
			
			case "select":
				var aFormElem = new Array();
				aFormElem["o"] = o;
				aFormElem["type"] = "select";
				aFormElem["selectedIndex"] = o.selectedIndex;
				break;
		}
		if (aFormElem)
		{
			aDefaultFormValues.push(aFormElem);
		}
	}
	
	// Move the page-shield and the warning div to the top of the HTML structure
	var oS = document.getElementById("wantToLoseChanges");
	if (oS)
	{
		var oTemp = oS.cloneNode(true);
		oS.parentNode.removeChild(oS);
		document.getElementsByTagName("body")[0].insertBefore(oTemp, document.getElementsByTagName("body")[0].firstChild);
	}

	// Register the unload event listener
	document.getElementsByTagName("body")[0].txtWarnUnsavedChangesLost = TextRegistry.find("warnUnsavedChangesLost", sFormId);
	window.onunload = formModifiedunloadListener;
}




function myAccountSectionOpener() {
	// Is there a "section" or "s" query param?
	var sectionArg = location.search.match(/[?&]s(?:ection)?=([^&]*)/i);
	if (!sectionArg || !sectionArg[1]) {
		return;
	}
	
	var aSectionMap = new Array();
	aSectionMap["personal"] = "sectionPersonalDetails";
	aSectionMap["disney"]   = "sectionMyDisneyID";
	aSectionMap["ttprefs"]  = "sectionMyToontownPreferences";
	aSectionMap["ptools"]   = "sectionPaymentTools";
	aSectionMap["subs"]     = "sectionMySubscriptionsAndPayments";
	
	// If you want to open more than one section, just list their names separated by space or comma.
	sectionArg[1] = sectionArg[1].replace(/%20/g, " ");// urldecode
	var aSectionsToOpen = sectionArg[1].split(/[,\s]/);
	var currId = "";
	var oDiv = null;
	var oDivPrev = null;
	var oH2 = null;
	
	for (var i = 0, ii = aSectionsToOpen.length; i < ii; i++) {
		currId = aSectionMap[aSectionsToOpen[i]];
		if (!currId || !document.getElementById(currId)) {
			continue;
		}
		
		oDiv = document.getElementById(currId);
		// Show the section.
		oDiv.style.display = "block";
		
		// Find its title <h2> tag, and mark that open by setting the correct CSS class.
		// It should be its second previous sibling in DOM.
		oDivPrev = oDiv.previousSibling;
		while (oDivPrev && !oH2)
		{
			if (oDivPrev.nodeType == 1)
			{
				if (oDivPrev.tagName == "H2" && oDivPrev.className.match(/\ssection/))
				{
					oH2 = oDivPrev;
				}
			}
			oDivPrev = oDivPrev.previousSibling;
		}
		
		if (oH2) {
			oH2.className = oH2.className.replace(/ sectionClosed| sectionOpen/g, "");
			oH2.className += " sectionOpen";
			oH2 = null;
		}
	}
}
addLoadEvent(myAccountSectionOpener);



function addHiddenSubmitButtons()
{
	var oSubmit;
	/*
	var aFormExceptions = ["forgotPasswordForm"];// These <form>s should not get an automatic & hidden submit button.
	*/
	
	for (var f = 0, ff = document.forms.length; f < ff; f++)
	{
		if (document.forms[f].className.match(/no-hidden-submit/)) {// These forms do not require automatic hidden submit buttons.
			continue;
		}
		/*
		if (aFormExceptions.contains(document.forms[f].id)) {
			continue;
		}
		*/
		
		oSubmit = document.createElement("INPUT");
		oSubmit.type = "submit";
		oSubmit.value = "SUBMIT";
		oSubmit.onclick = function () {
			// Check the form to decide which validation method [validate() or validate2()] should we use.
			var cButtons = this.form.getElementsByTagName("button");
			var func;
			for (var i = 0, ii = cButtons.length; i < ii; i++) {
				if (String(cButtons[i].getAttribute("onclick")).match(/\bvalidate2\(/)) {
					func = validate2;
					break;
				}
				if (String(cButtons[i].getAttribute("onclick")).match(/\bvalidate\(/)) {
					func = validate;
					break;
				}
			}
			func(this.form); return false
		};
		oSubmit.className = "hiddenSubmit";
		
		document.forms[f].appendChild(oSubmit);
	}
}
addLoadEvent(addHiddenSubmitButtons);



function fixOutageBar() {
	if (document.all && document.getElementById("outagebar") && !document.getElementById("loginbarForm")) {
		document.getElementById("outagebar").style.top = "-5px";
	}
	if (document.getElementById("outagebar") && document.getElementById("main_content") && document.getElementById("main_content").className.match(/fullPageOtherBorderWithoutAdBanners/)) {
		document.getElementById("outagebar").style.top = "-6px";
	}
}
addLoadEvent(fixOutageBar);




var oFileUploadAttrs = {};
function fileUploader() {
	var oFileUploader = document.getElementById("screenshotfile");
	if (!oFileUploader) return;
	
	// Make a copy the attributes of <input type="file">
	for (var i = 0, ii = oFileUploader.attributes.length; i < ii; i++) {
		if (oFileUploader.attributes[i].specified) {
			oFileUploadAttrs[oFileUploader.attributes[i].nodeName] = oFileUploader.attributes[i].nodeValue;
		}
	}
	oFileUploader.onchange = fileUploaderChangeListener;
}
addLoadEvent(fileUploader);
function fileUploaderChangeListener() {
	if (this.value.length) {
		var oDiv = document.getElementById("selectedFile");
		oDiv.innerHTML = this.value;
		
		if (document.getElementById("cancelUploadButton")) return;
		
		var oUploadButton = document.getElementById("uploadButton");
		var button = oUploadButton.cloneNode(true);
		button.id = "cancelUploadButton";
		
		var buttonText = button.className.match(/TextRegistry\.(\S+)/);
		if (buttonText instanceof Array && buttonText[1]) {
			buttonText = TextRegistry.get(buttonText[1]);
		} else {
			buttonText = TextRegistry.get("ContactUsForm.RemoveFile.button.text");
		}
		
		var spans;
		if (oUploadButton.getElementsByTagName("DIV")[0].lastChild.tagName == "SPAN") {
			spans = oUploadButton.getElementsByTagName("span");
		}
		button.getElementsByTagName("DIV")[0].innerHTML = buttonText;
		if (spans) {
			for (var j = 0, jj = spans.length; j < jj; j++) {
				button.getElementsByTagName("div")[0].appendChild(spans[j].cloneNode(true));
			}
		}
		oUploadButton.parentNode.insertBefore(button, oUploadButton.nextSibling);
		
		document.getElementById("cancelUploadButton").onclick = function () {
			var oInputFile = document.createElement("input");
			for (var i in oFileUploadAttrs) {
				oInputFile.setAttribute(i, oFileUploadAttrs[i]);
			}
			oInputFile.onchange = fileUploaderChangeListener;
			document.getElementById("uploadWrapper").innerHTML = "";
			document.getElementById("uploadWrapper").appendChild(oInputFile);
			document.getElementById("selectedFile").innerHTML = "";
			
			this.parentNode.removeChild(this);
		};
		
		if (window.isIE6) pngfix();
	}
}



function _wrapInPopupDesign(oContentElement, bCloseButton, bForDoodle) {
	var Table, TBody, Tr, Td, Img, WrapperDivForCloseButton;
	Table = document.createElement("table");
		Table.className = "popuptable";
	TBody = document.createElement("tbody");
	Tr = document.createElement("tr");
	Td = document.createElement("td");
		Td.className = "nw";
	Img = document.createElement("img");
		Img.src = "images/popup-help/border-nw.png";
		Td.appendChild(Img);
		Tr.appendChild(Td);
	Td = document.createElement("td");
		Td.className = "n"
	Img = document.createElement("img");
		Img.src = "images/_blank.gif";
		Td.appendChild(Img);
		Tr.appendChild(Td);
	Td = document.createElement("td");
		Td.className = "ne";
	Img = document.createElement("img");
		Img.src = "images/popup-help/border-ne.png";
		Td.appendChild(Img);
		Tr.appendChild(Td);
	TBody.appendChild(Tr);
	//
	Tr = document.createElement("tr");
	Td = document.createElement("td");
		Td.className = "w";
	Img = document.createElement("img");
		Img.src = "images/_blank.gif";
		Td.appendChild(Img);
		Tr.appendChild(Td);
	Td = document.createElement("td");
		Td.className = "content";
		
		if (bForDoodle) {
			Doodle = document.createElement("span");
				Doodle.className = "doodle-hint";
			Td.appendChild(Doodle);
		}
		if (bCloseButton) {
			WrapperDivForCloseButton = document.createElement("div");
			WrapperDivForCloseButton.className = "wrapper-for-close-button";
			Img = document.createElement("img");
				Img.src = "images/popup-help/close-button.png";
				Img.alt = "";
				Img.className = "close-button";
				Img.setAttribute("onclick", "this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.style.display = 'none';");
			WrapperDivForCloseButton.appendChild(Img);
			Td.insertBefore(WrapperDivForCloseButton, Td.firstChild);
		}
		Td.innerHTML += oContentElement.innerHTML;
		Tr.appendChild(Td);
	Td = document.createElement("td");
		Td.className = "e";
	Img = document.createElement("img");
		Img.src = "images/_blank.gif";
		Td.appendChild(Img);
		Tr.appendChild(Td);
	TBody.appendChild(Tr);
	//
	Tr = document.createElement("tr");
	Td = document.createElement("td");
		Td.className = "sw";
	Img = document.createElement("img");
		Img.src = "images/popup-help/border-sw.png";
		Td.appendChild(Img);
		Tr.appendChild(Td);
	Td = document.createElement("td");
		Td.className = "s";
	Img = document.createElement("img");
		Img.src = "images/_blank.gif";
		Td.appendChild(Img);
		Tr.appendChild(Td);
	Td = document.createElement("td");
		Td.className = "se";
	Img = document.createElement("img");
		Img.src = "images/popup-help/border-se.png";
		Td.appendChild(Img);
		Tr.appendChild(Td);
	TBody.appendChild(Tr);
	
	Table.appendChild(TBody);
				
	oContentElement.innerHTML = "";
	oContentElement.appendChild(Table);
}

function activatePopupControllers() {
	var oE = document.getElementsByTagName("*");
	
	for (var i = 0, ii = oE.length; i < ii; i++) {
		if (!oE[i] || !oE[i].className) continue;
		
		if (oE[i].className.match(/\bpopupinfoController\b/)) {
			addEvent(oE[i], "click", function (e) {
				e = e || window.event;
				var o = e.target || e.srcElement;
				getNextTag(getFirstTag(o.parentNode)).style.display = "block";
				e.cancelBubble = true;
				if (e.stopPropagation) e.stopPropagation();
			});
			
			addEvent(document, "click", function (e) {
				e = e || window.event;
				var o = e.target || e.srcElement;
				if (o.nodeName == "A") return;
				
				while (o && o.parentNode) {// The popup table itself is not destroyed when we click on it.
					if (o.className.match(/\bpopuptable\b/)) {
						return false;
					}
					o = o.parentNode;
				}
				
				var cAllDivs = document.getElementsByTagName("div");
				for (var i = 0, ii = cAllDivs.length; i < ii; i++) {
					if (cAllDivs[i].className.match(/\bpopupinfo\b/) && cAllDivs[i].style.display == "block") {
						cAllDivs[i].style.display = "none";
					}
				}
			});
		}
		else if (oE[i].className.match(/\bpopupinfo\b/)) {
			_wrapInPopupDesign(oE[i], true);
		}
	}
}
//addDOMLoadEvent(activatePopupControllers);
addLoadEvent(activatePopupControllers);


function _checkPassword(e) {
	e = e || window.event;
	var o;
	if (e && e.nodeName) {
		o = e;
	} else {
		o = e.target || e.srcElement;
	}
	
	var minLength, maxLength, pattern, equalsSto;
	
	// Clear the assist div.
	o.assistDiv.innerHTML = "";
	o.assistDiv.style.display = "none";
	
	if (!o.value.length) return;
	
	var lengthProblem = false;
	minLength = (o.className.match(/\bv:minlength:\d+/))
			? parseInt(o.className.match(/\bv:minlength:(\d+)/)[1], 10)
			: (o.getAttribute("minlength") && parseInt(o.getAttribute("minlength"), 10) > -1)
				? o.getAttribute("minlength")
				: null;
	if (!minLength && ValidatorData["field-based"][o.id] && ValidatorData["field-based"][o.id]["minLength"]) {
		// inherit the default value from ValidatorData
		minLength = ValidatorData["field-based"][o.id]["minLength"];
	}
	maxLength = (o.className.match(/\bv:maxlength:\d+/))
			? parseInt(o.className.match(/\bv:maxlength:(\d+)/)[1], 10)
			: (o.getAttribute("maxlength") && parseInt(o.getAttribute("maxlength"), 10) > -1)
				? o.getAttribute("maxlength")
				: null;
	if (!maxLength && ValidatorData["field-based"][o.id] && ValidatorData["field-based"][o.id]["maxLength"]) {
		// inherit the default value from ValidatorData
		maxLength = ValidatorData["field-based"][o.id]["maxLength"];
	}
	
	if ((!minLength || !maxLength) && ValidatorData["field-based"][o.id] && ValidatorData["field-based"][o.id]["equalsTo"]) {
		// Inherit the min/maxLength values from the reference field.
		var oRef = ValidatorData["field-based"][o.id]["equalsTo"];
		minLength = ValidatorData["field-based"][oRef]["minLength"];
		maxLength = ValidatorData["field-based"][oRef]["maxLength"];
	}
	
	if (minLength && minLength > o.value.length) lengthProblem = true;
	if (maxLength && maxLength < o.value.length) lengthProblem = true;
	var DivLength = document.createElement("div");
	if (lengthProblem) {
		DivLength.className = "warning";
		if (minLength && minLength > o.value.length) {
			DivLength.innerHTML = TextRegistry.get("warnPwLengthFailed." + o.form.id);
		}
	} else {
		DivLength.className = "ok";
		DivLength.innerHTML = TextRegistry.get("warnPwLengthOK." + o.form.id);
	}
	if (!o.isConfirmField && (minLength !== null || maxLength !== null)) {// Only show the length check when it is explicitly invoked (minlength, maxlength), but never for a confirm password field.
		o.assistDiv.appendChild(DivLength);
	}
	
	pattern = (o.className.match(/\bv:pattern:\S+/))
			? o.className.match(/\bv:pattern:(\S+)/)[1]
			: (o.getAttribute("pattern"))
				? o.getAttribute("pattern")
				: null;
	if (!pattern && ValidatorData["field-based"][o.id] && ValidatorData["field-based"][o.id]["pattern"]) {
		// inherit the default value from ValidatorData
		pattern = document.getElementById(ValidatorData["field-based"][o.id]["pattern"]);
	}
	if (pattern) {
		var DivPattern = document.createElement("div");
		var result = new RegExp(pattern).test(o.value);
		if (result) {
			DivPattern.className = "ok";
			DivPattern.innerHTML = TextRegistry.get("warnPwPatternOK." + o.form.id);
		} else {
			DivPattern.className = "warning";
			DivPattern.innerHTML = TextRegistry.get("warnPwPatternFailed." + o.form.id);
		}
		o.assistDiv.appendChild(DivPattern);
	}
	
	equalsTo = (o.className.match(/\bv:equalsto:\S+/))
			? document.getElementById(o.className.match(/\bv:equalsto:(\S+)/)[1])
			: (o.getAttribute("equalsto"))
				? document.getElementById(o.getAttribute("equalsto"))
				: null;
	if (!equalsTo && ValidatorData["field-based"][o.id] && ValidatorData["field-based"][o.id]["equalsTo"]) {
		// inherit the default value from ValidatorData
		equalsTo = document.getElementById(ValidatorData["field-based"][o.id]["equalsTo"]);
	}
	if (equalsTo) {
		var DivEquals = document.createElement("div");
		if (equalsTo.value != o.value) {


			DivEquals.className = "warning";
			DivEquals.innerHTML = TextRegistry.get("warnPwMatchFailed." + o.form.id);
		} else {
			DivEquals.className = "ok";
			DivEquals.innerHTML = TextRegistry.get("warnPwMatchOK." + o.form.id);
		}
		o.assistDiv.appendChild(DivEquals);
	}
	
	if (o.assistDiv.innerHTML.length) {
		o.assistDiv.style.display = "block";
	}
	
	if (e && !e.nodeName && o && o.referencedPasswordField) {// If it was called via an event, then we need to check the other password field too.
		_checkPassword(o.referencedPasswordField);
	}
}
function passwordAssist() {
	for (var i = 0, ii = document.forms.length; i < ii; i++) {
		if (!document.forms[i].className.match(/\bpasswordAssist:\S+:\S+/)) continue;
		
		var parse = document.forms[i].className.match(/\bpasswordAssist:([^:]+):([^:]+):?([^:]+)?/);
		var PasswordField1 = document.getElementById(parse[1]);
		var PasswordField2 = document.getElementById(parse[2]);
			PasswordField2.isConfirmField = true;
		var ChildPasswordField = parse[3] ? document.getElementById(parse[3]) : null;
		
		var DivAssist1 = document.createElement("div");
		DivAssist1.className = "assist";
		PasswordField1.referencedPasswordField = PasswordField2;
			PasswordField1.assistDiv = PasswordField1.parentNode.appendChild(DivAssist1);
		addEvent(PasswordField1, "keyup", _checkPassword);
		
		var DivAssist2 = document.createElement("div");
		DivAssist2.className = "assist";
		PasswordField2.referencedPasswordField = PasswordField1;
			PasswordField2.assistDiv = PasswordField2.parentNode.appendChild(DivAssist2);
		addEvent(PasswordField2, "keyup", _checkPassword);
		
		if (ChildPasswordField) {
			var ChildDivAssist = document.createElement("div");
			ChildDivAssist.className = "assist";
				ChildPasswordField.assistDiv = ChildPasswordField.parentNode.appendChild(ChildDivAssist);
			addEvent(ChildPasswordField, "keyup", _checkPassword);
		}
	}
}
addLoadEvent(passwordAssist);


function jumpHomeNow()
{
	top.location="index.html";
}

function jumpHome()
{
setTimeout('jumpHomeNow()',5000);
}

/**
* Business functions
*
*
*/
	
function registerPaymentToolForRemoval(tableObject) {			
	document.getElementById("toolToRemove").value = nodeBefore(tableObject).innerHTML;
}

/**
*Utils
*/
function nodeBefore(sib) {
  while ((sib = sib.previousSibling)) {
    if (!isIgnorable(sib)) return sib;
  }
  return null;
}

function isIgnorable(nod) {
  return ( nod.nodeType == 8) || ( (nod.nodeType == 3) && isAllWs(nod) );
}

function isAllWs(nod) {
  // Use ECMA-262 Edition 3 String and RegExp features
  return !(/[^\t\n\r ]/.test(nod.data));
}

addLoadEvent(function(){
	// Add onblur and onfocus events to password fields.
	var passwordFields = document.getElementsByTagName("input");
	for (var i = 0, ii = passwordFields.length; i < ii; i++) {
		if (passwordFields[i].type != "password") {
			continue;
		}
		passwordFields[i].onblur = passwordFieldEventHandler;
		passwordFields[i].onfocus = passwordFieldEventHandler;
	}
});
function passwordFieldEventHandler(e) {
	e = e || window.event;
	o = e.target || e.srcElement;
	
	switch (e.type) {
		case "focus":
			if (!o.veryOriginalValue) {
				o.veryOriginalValue = o.value;
			}
			o.originalValue = o.value;
			if (o.value.match(/^\*+$/)) {
				o.value = "";
				
				if (o.referencedPasswordField) {
					o.referencedPasswordField.value = "";
				}
			}
			break;
		
		case "blur":
			if (o.value.match(/^\**$/)) {
				if (!o.value.replace(/\s/g, "").length) {
					if (o.veryOriginalValue) {
						o.value = o.veryOriginalValue;
					}
				} else {
					if (o.originalValue) {
						o.value = o.originalValue;
					}
				}

				if (o.referencedPasswordField) {
					o.referencedPasswordField.value = o.veryOriginalValue ? o.veryOriginalValue : o.originalValue;
				}
			}
			break;
	}
}

		
function fixOrphanWords() {
	var o;
	var td = document.getElementsByTagName("TD");
	for (var i = 0, ii = td.length; i < ii; i++) {
		if (td[i].className.match(/bnrmaincontent/)) {
			o = td[i];
			break;
		}
	}
	if (!o) return false;
	
	function traverse(node) {
		for (var i = 0, ii = node.childNodes.length; i < ii; i++) {
			if (3 == node.childNodes[i].nodeType) {
				node.childNodes[i].nodeValue = node.childNodes[i].nodeValue.replace(
						/([a-z0-9:"'()-]+)\s+([a-z0-9"'()-]+[.,!:;]?)$/i,
						"$1" + (String.fromCharCode(0xA0)) + "$2"// 0xA0 = &nbsp;
					);
			}
			if (node.childNodes[i].childNodes.length) {
				traverse(node.childNodes[i]);
			}
		}
	}
	traverse(o);
}
addLoadEvent(fixOrphanWords);




/**
 * Automatically sets equal arbitrary dimensions of the selected elements.
 * The elements are marked via special CSS class names.
 * 
 * Format:
 * <div class="autosizegroup:<unique group name>:<dimension to be equalized;>">content</div>

 * <div class="autosizegroup:<the same name as above>">content</div>
 * ... as many additional elements as you need, there is no limit.
 * 
 * Example:
 * <div class="autosizegroup:myGroup:height">content</div>
 * <div class="autosizegroup:myGroup">content</div>
 * <div class="autosizegroup:myGroup otherCssClass">content</div>
 * These three divs will be set to have equal heights.
 * 
 * Valid dimensions are as follows:
 * width, x
 * height, y
 * <anything else will mean that both dimensions are to be equalized>
 * 
 * You may define the dimension part at any of the elements, the last definition will be used.
 */
function autoResize() {
	var oAutoGroups = [];
	var cElems = document.getElementsByTagName("*");
	var aInstruction;
	
	for (var i = 0, ii = cElems.length; i < ii; i++) {
		if (cElems[i].className.match(/autosizegroup:/i)) {
			aInstruction = cElems[i].className.match(/autosizegroup:\S+/ig);
			
			for (var j = 0, jj = aInstruction.length; j < jj; j++) {
				var aThisInstruction = aInstruction[j].match(/autosizegroup:([^:\s]+):?(\S*)/i);
				var currentGroup = aThisInstruction[1].toLowerCase();
				
				if (typeof(oAutoGroups[currentGroup]) != "object") {
					oAutoGroups[currentGroup] = {
						matchTheseDimensions : "",
						maxWidth : 0,
						maxHeight : 0,
						aMembers : []
					};
				}
				oAutoGroups[currentGroup]["aMembers"].push(cElems[i]);
				if (aThisInstruction[2].length) {
					oAutoGroups[currentGroup].matchTheseDimensions = aThisInstruction[2].toLowerCase();
				}
				
				if (oAutoGroups[currentGroup]["maxWidth"] < cElems[i].clientWidth) {
					oAutoGroups[currentGroup]["maxWidth"] = cElems[i].clientWidth;
				}
				if (oAutoGroups[currentGroup]["maxHeight"] < cElems[i].clientHeight) {
					oAutoGroups[currentGroup]["maxHeight"] = cElems[i].clientHeight;
				}
			}
		}
	}
	
	var obj, maxWidth, maxHeight;
	for (var i in oAutoGroups) {
		for (var j = 0, jj = oAutoGroups[i]["aMembers"].length; j < jj; j++) {

			obj = oAutoGroups[i]["aMembers"][j];

			maxWidth = oAutoGroups[i]["maxWidth"];
			maxHeight = oAutoGroups[i]["maxHeight"];
			
			if (obj.tagName == "BUTTON") {
				try {
					spans = obj.getElementsByTagName("span");
					span1Width = parseFloat(getStyle(spans[0], "width"));
					span2Width = parseFloat(getStyle(spans[1], "width"));
					if (window.isIE7 && !obj.className.match(/\biur\b/)) {
						maxWidth += (span1Width + span2Width);
					} else {
						maxWidth -= (span1Width + span2Width);
					}
					obj = obj.getElementsByTagName("DIV")[0];
					paddingLeft = parseInt(getStyle(obj, "padding-left"), 10);
						paddingLeft = isNaN(paddingLeft) ? 0 : paddingLeft;
					paddingRight = parseInt(getStyle(obj, "padding-right"), 10);
						paddingRight = isNaN(paddingRight) ? 0 : paddingRight;
					if (window.isIE7 && !obj.parentNode.className.match(/\biur\b/)) {
						maxWidth += paddingLeft + paddingRight;
					}
				} catch(ex) {}
			}
			
			switch (oAutoGroups[i]["matchTheseDimensions"]) {
				case "x":
				case "width":
					obj.style.width = maxWidth + "px";
					obj.style.minWidth = maxWidth + "px";
					break;

				case "y":
				case "height":
					obj.style.height = maxHeight + "px";
					obj.style.minHeight = maxHeight + "px";
					break;

				default:
					obj.style.width = maxWidth + "px";
					obj.style.minWidth = maxWidth + "px";
					obj.style.minHeight = maxHeight + "px";
			}
		}
	}
}
//addDOMLoadEvent(autoResize);
addLoadEvent(autoResize);




function resetThisFormOnDOMLoad() {
	return;// temporarily disabled. 2008-09-12
	var oForm = document.getElementById("upgradeAccVipSubs");
	if (!oForm) return;
	
	// Check if there are server-side error messages on the page. If there are, we should not reset the form.
	var cCheckServerMessages = getElementsByClassName("notification");
	if (!cCheckServerMessages.length) return;
	
	var currElem;
	for (var i = 0, ii = oForm.elements.length; i < ii; i++) {
		currElem = oForm.elements[i];
		
		if (currElem.id.match(/countryCode/)) continue;// skip specific form elements.
		
		switch (currElem.nodeName.toLowerCase()) {
			case "input":
				if (currElem.type.match(/text|password/)) {
					currElem.value = "";
					continue;
				}
				if (currElem.type.match(/checkbox|radio/)) {
					currElem.checked = false;
					continue;
				}
				break;
			
			case "textarea":
				currElem.value = "";
				break;
			
			case "select":
				currElem.selectedIndex = 0;
				break;
		}
	}
	
	if (oForm.paymentToolCard) oForm.paymentToolCard.checked = true;
	if (oForm.addNewPaymentTool) oForm.addNewPaymentTool.checked = true;
}







function createFullScreenNotifier(id, msg, oButton1, oButton2) {
	if ("undefined" == typeof oButton1)
	{
		var oButton1 = {
			text : "OK",
			onclick : "notifierOk(event)"
		};
	}
	
	var oDiv1 = document.createElement("div");
	oDiv1.id = (typeof id == "undefined" ? "notifier" : id);
	oDiv1.className = "fullPageNotifier";
		var oDiv2 = document.createElement("div");
		oDiv2.className = "fullPageShielded";
	oDiv1.appendChild(oDiv2);
	var oDiv3 = document.createElement("div");
		oDiv3.className = "warning";
	var oDiv4 = document.createElement("div");
	oDiv4.className = "top";
		oDiv3.appendChild(oDiv4);
	var oDiv5 = document.createElement("div");
	oDiv5.className = "bg";
		oDiv5.innerHTML = "<p>" + msg + "</p>";
		
		var content = "<button type=\"button\" class=\"small\" onclick=\"" + oButton1.onclick + "\">"
			+ oButton1.text + "<\/button>";
		if (oButton2) {
			content += "<button type=\"button\" class=\"small\" onclick=\"" + oButton2.onclick + "\">" + oButton2.text + "<\/button>";
		}
		
		oDiv5.innerHTML += "<div style=\"text-align:center\">"
			+ content
			+ "</div>";
		
		oDiv3.appendChild(oDiv5);
	var oDiv6 = document.createElement("div");
	oDiv6.className = "bottom";
		oDiv3.appendChild(oDiv6);
	oDiv1.appendChild(oDiv3);
		
	document.getElementsByTagName("body")[0].insertBefore(oDiv1, document.getElementsByTagName("body")[0].firstChild);
	
	initButtons();
}
function toggleFullScreenNotifier(oSource, id, forceThisStatus) {
	var o = document.getElementById(id);
	if (!o) return false;
	o.oSource = oSource;
	var newStatus;
	if ("undefined" == typeof forceThisStatus) {
		newStatus = getStyle(o, "display");
		newStatus == (newStatus == "none" ? "block" : "none");
	} else {
		newStatus = (forceThisStatus == "block" ? "block" : "none");
	}
	if (document.all && !window.isIE7) {
		// IE6 tweak
		document.getElementsByTagName("html")[0].style.overflow = (newStatus == "none") ? "" : "hidden";
	}
	o.style.display = newStatus;
}


function launchForeignLinkFromFlash(url) {
	createFullScreenNotifier(
		"fsnForeignLinks",
		TextRegistry.get("LeavingDisney.Disclaimer.notice"),
		{text:TextRegistry.get("LeavingDisney.Leave.button.text"), onclick:"location = '" + url + "'"},
		{text:TextRegistry.get("LeavingDisney.Cancel.button.text"), onclick:"notifierCancel()"}
	);
}

function warnOnForeignLinks() {
	if (!window.TextRegistry) return;
	
	createFullScreenNotifier(
		"fsnForeignLinks",
		TextRegistry.get("LeavingDisney.Disclaimer.notice"),
		{text:TextRegistry.get("LeavingDisney.Leave.button.text"), onclick:"notifierOk(event)"},
		{text:TextRegistry.get("LeavingDisney.Cancel.button.text"), onclick:"notifierCancel()"}
	);
	
	// If a URL starts with this regex, then it is considered a foreign link.
	var rxForeignLinkIndicator = new RegExp("leave\\.html\\?url=");
	
	var cLinks = document.links;
	var href;
	for (var i = 0, ii = cLinks.length; i < ii; i++) {
		if (!cLinks[i].href.match(rxForeignLinkIndicator)) continue;
		
		href = cLinks[i].getAttribute("href").split(rxForeignLinkIndicator);
		cLinks[i].href = href[1];
		
		if (cLinks[i].onclick) {
			cLinks[i].oldonclick = cLinks[i].onclick;
			cLinks[i].onclick = null;
		}
		
		addEvent(cLinks[i], "click", function (e) {
			e = e || window.event;
			o = e.target || e.srcElement;
			
			if (o.nodeName == "IMG" && o.parentNode && o.parentNode.nodeName == "A") {
				o = o.parentNode;
			}
			if (e.preventDefault) e.preventDefault();
			e.cancelBubble = true;
			
			toggleFullScreenNotifier(o, "fsnForeignLinks", "block");
			
			return false;
		});
	}
	
	var cButtons = document.getElementsByTagName("button");
	for (var i = 0, ii = cButtons.length; i < ii; i++) {
		if (!cButtons[i].onclick || !cButtons[i].onclick.toString().match(rxForeignLinkIndicator)) continue;
		
		var func = cButtons[i].onclick.toString().replace(/leave\.html\?url=/, "");
		cButtons[i].oldonclick = func;
		cButtons[i].onclick = null;
		
		addEvent(cButtons[i], "click", function (e) {
			e = e || window.event;
			o = e.target || e.srcElement;
			if (o.nodeName == "DIV") {// FF fix
				o = o.parentNode;
			}
			
			if (e.preventDefault) e.preventDefault();
			e.cancelBubble = true;
			
			toggleFullScreenNotifier(o, "fsnForeignLinks", "block");
			
			return false;
		});
	}
}
addDOMLoadEvent(warnOnForeignLinks);
function notifierOk(e) {
	e = e || window.event;
	o = e.target || e.srcElement;
	
	var oDiv = o;
	var timeoutCounter = 25;
	while (!oDiv.oSource && -- timeoutCounter) {
		oDiv = oDiv.parentNode;
	}
	if (oDiv.oSource.oc) {
		oDiv.oSource.oc();
	} else {
		if (oDiv.oSource.nodeName == "BUTTON") {
			var oldOnClick = oDiv.oSource.getAttribute("oldonclick");
			if (oldOnClick) {
				eval(oldOnClick.replace(/^function anonymous\(\)\s*\{/m, "").replace(/\}\s*$/, ""));
			} else {
				var commandToExecute = oDiv.oSource.getAttribute("onclick").replace(/leave\.html\?url=/, "");
				eval(commandToExecute);
			}
		} else {
			var onclickFunc = (oDiv.oSource.oldonclick) ? oDiv.oSource.oldonclick.toString() : String(oDiv.oSource.getAttribute("onclick"));  
			
			if (
				("_blank" == oDiv.oSource.getAttribute("target"))
					||
				(onclickFunc.match(/window\.open/))
			) {
				window.open(oDiv.oSource.href);
			} else {
				location = oDiv.oSource.href;
			}
		}
	}
	toggleFullScreenNotifier(null, "fsnForeignLinks", "none");
	return false;
}
function notifierCancel() {
	toggleFullScreenNotifier(null, "fsnForeignLinks", "none");
	return false;
}




function _hideFormHints(oF) {
//	var cHints = getElementsByClassName(oF, "popuphint");
	var cHints = getElementsByClassName(document, "popuphint");
	for (var i = 0, ii = cHints.length; i < ii; i++) {
		cHints[i].style.display = "none";
	}
}
function _formHintFocus(event) {
	event = event || window.event;
	var o = event.target || event.srcElement;
	
	if (o.tagName.toLowerCase() == "img" && o.className.match(/\bshow-form-hint\b/)) {
		o = o.previousSibling;
	}
	
	if (!o.hint) return;
	var currentDisplayStatus = getStyle(o.hint, "display");
	if ("none" != currentDisplayStatus) return;
	
	_hideFormHints(o.form);
	
	oDivRow = getParentTag(o, "div", "\\brow\\b|\\brow2\\b");
	aDivRowPos = findPos(oDivRow);
	o.hint.style.left = (document.documentElement.clientWidth / 2) + 310 + "px";
//	o.hint.style.left = aDivRowPos[0] + oDivRow.clientWidth + "px";
	o.hint.style.top = aDivRowPos[1] - 17 + "px";
	
	o.hint.style.display = "block";
	
}

function initFormHints() {
	var cForms = document.forms;
	var oBody = document.getElementsByTagName("body")[0];
	
	for (var i = 0, ii = cForms.length; i < ii; i++) {
		if (!cForms[i].className.match(/\bautomatic-hints\b|\bmanual-hints\b/)) {
			continue;
		}
		
		var formId = cForms[i].id;
		var elementId, oImgShowHint, cPreviousImg;
		var oDivRow, oDivPopupHint, oStaticHint, oHintDiv;
		var isAutomatic = !!cForms[i].className.match(/\bautomatic-hints\b/);
		var bForDoodle = !!cForms[i].className.match(/\bfor-kids\b/);
		
		for (var j = 0, jj = cForms[i].elements.length; j < jj; j++) {
			elementId = cForms[i].elements[j].id;
			if (!elementId) continue;

			// TODO formId is not mandatory, fallback to default
			var hintContent = TextRegistry.get("hintStr." + elementId + "." + formId, true);
			if (!hintContent) continue;
			
			oDivRow = getParentTag(cForms[i].elements[j], "div", "\\brow\\b|\\brow2\\b");
			if (!oDivRow) continue;
			
			if (cForms[i].elements[j].tagName == "INPUT" && cForms[i].elements[j].type == "checkbox" && isAutomatic) {
				// Checkboxes have static hints.
				oStaticHint = document.createElement("div");
					oStaticHint.className = "small limitwidth";
					oStaticHint.innerHTML = hintContent;
				oDivRow.appendChild(oStaticHint);
			} else {
				// Non-checkboxes and non-automatic checkboxes have dynamic hints.
				oDivPopupHint = document.createElement("div");
					oDivPopupHint.className = "popuphint hint-for:" + elementId;
					oDivPopupHint.innerHTML = hintContent;
				//oHintDiv = oDivRow.insertBefore(oDivPopupHint, oDivRow.firstChild);
//				oHintDiv = oDivRow.appendChild(oDivPopupHint);
				oHintDiv = oBody.appendChild(oDivPopupHint);
				
				cForms[i].elements[j].hint = oHintDiv;				
				_wrapInPopupDesign(oHintDiv, !isAutomatic, bForDoodle);
				
				if (isAutomatic) {
					addEvent(cForms[i].elements[j], "focus", _formHintFocus);
					addEvent(cForms[i].elements[j], "keyup", _formHintFocus);
					addEvent(cForms[i].elements[j], "click", _formHintFocus);
					addEvent(cForms[i].elements[j], "blur", _hideFormHints);
				} else {
					cPreviousImg = getElementsByClassName(oDivRow, "show-form-hint");
					if (cPreviousImg.length) {
						// There can be only one... (for the last element in the row)
						cPreviousImg[0].parentNode.removeChild(cPreviousImg[0]);
					}
					
					oImgShowHint = document.createElement("img");
					oImgShowHint.src = "images/help-icon.gif";
					oImgShowHint.className = "show-form-hint";
					oImgShowHint.onclick = _formHintFocus;
					
					cForms[i].elements[j].parentNode.insertBefore(oImgShowHint, cForms[i].elements[j].nextSibling);
				}
			}
		}
	}
	
}
addLoadEvent(initFormHints);



function _failedValidationIndicator(oForm, bState) {// TODO: I'll have to provide an easy way to set the head and the content.
	var d = document.getElementById("_visibleValidationIndicator");
	if (bState && !d) {
		// show
		d = document.createElement("div");
		d.id = "_visibleValidationIndicator";
		d.className = "warning-box";
		
		var dHead = document.createElement("div");
		dHead.className = "head";
		dHead.innerHTML = TextRegistry.find("warnStr", oForm.id, "dataSavingFailed");
		d.appendChild(dHead);
		
		var dContent = document.createElement("div");
		dContent.className = "content";
		dContent.innerHTML = TextRegistry.find("warnStr", oForm.id, "clientSideValidationProblem"); 
		d.appendChild(dContent);
		
		oForm.parentNode.insertBefore(d, oForm);
	}
	if (!bState && d) {
		// hide
		d.parentNode.removeChild(d);
	}
}

/**
 * VALIDATOR 2
 */
/**
* Collects the validator criterias from the ValidatorData JavaScript object (global, inheritable values), then from
*  inline CSS class names (which override the inherited values).
* Define these CSS names as follows:
* 
* v:
* {CASE SENSITIVE validator function name, e.g. "mandatory" or "maxLength"}
* [:{function argument. You can escape space and colon characters by putting a \ before them.}]
* [:{additional, optional function arguments. Each begins with a colon. As always, space and colon characters can be escaped by putting a \ before them.}]
*
* == EXAMPLE ==
* <input type="text" class="v:minLength:3 v:maxLength:7 shorttext v:pattern:^[^a-z\:\ 0-9]$:gi" />
* So we require that the above field's value must
* - be at least 3 characters long (minLength)
* - no longer than 7 characters (maxLength)
* - and matches the given regular expression pattern of ^[^a-z\:\ 0-9]$ , which pattern is "global and case insensitive" -> gi
* The "shorttext" is a CSS name which has no role in the validation process, it is included to demonstrate that
*  CSS class names NOT beginning with "v:" will not interfere with validation.
*/
function validate2(oForm, fFuncBeforeSubmit, notForSubmission) {
	if (typeof oForm == "string") {
		oForm = document.getElementById(oForm);
	}
	this.fFuncBeforeSubmit = fFuncBeforeSubmit;
	this.notForSubmission = notForSubmission;
	var validator = new Validator(oForm);
	return validator.validate();
}
function Validator(oForm) {
	this.oForm = oForm;
	this.oCurrElem;
	this.oCurrParams;
	
	/**
	* @access private
	* @param String CSS classname of a form tag or a form element which contains v: parameters.
	*/
	this._getParams = function (className) {
		var oReturnParams = {};
		var paramName, aParamValues;
		var aRawParams = className.replace(/\\ /g, "$$32$$").replace(/\\:/g, "$$58$$").match(/\bv:\S+/g);
		
		if (aRawParams && aRawParams.length) {
			for (var i = 0, ii = aRawParams.length; i < ii; i++) {
				aParamValues = aRawParams[i].substr(2).split(":");
				paramName = aParamValues.shift();
				if (aParamValues.length == 0) aParamValues[0] = true;
				oReturnParams[paramName] = aParamValues || Array(paramName);
				for (var j in oReturnParams[paramName]) {
					oReturnParams[paramName][j] = String(oReturnParams[paramName][j]).replace(/\$\$32\$\$/g, " ").replace(/\$\$58\$\$/g, ":");
				}
			}
		}
		return oReturnParams;
	}
	
	/**
	* @access private
	* Merges the inheritable and the local parameters of a form element, yielding the aggregated parameters.
	* @param Object Hash map of the global, inheritable properties (from the form tag)
	* @param Object Hash map of the local properties of the current form element
	*/
	this._mergeParams = function (oGlobalParams, oElementParams) {
		var oReturnParams = {};
		for (var i in oGlobalParams) {
			oReturnParams[i] = [oGlobalParams[i]];
		}
		// Local parameters will override inherited ones.
		for (var i in oElementParams) {
			oReturnParams[i] = oElementParams[i];
		}
		return oReturnParams;
	}
	
	/**
	* @access public
	*/
	this.validate = function () {
		__shouldSkipHiddenFields = true;
		if (this.oForm.alreadySubmitted) return true;

		_failedValidationIndicator(this.oForm, false);// Hide the generic warning message.
		
		// Remove any error messages (inherited from previous failed validations)
		var aErrorMessageDivs = this.oForm.getElementsByTagName("div");
		for (var i = 0, ii = aErrorMessageDivs.length; i < ii; i++) {
			if (!aErrorMessageDivs[i] || !aErrorMessageDivs[i].className || !aErrorMessageDivs[i].className.match(/\bform-error\b/)) {
				continue;
			}
			aErrorMessageDivs[i].className = aErrorMessageDivs[i].className.replace(/\s*form-error\s*/g, "");
			var headDiv = aErrorMessageDivs[i].firstChild;
			if (headDiv.nodeName == "DIV" && headDiv.className == "head") {
				headDiv.parentNode.removeChild(headDiv);
			}
		}

		//// Collect inheritable properties from the <form> tag.
		//var oProperties = this._getParams(this.oForm.className);
		
		var oValidatorData;
		
		// Init error messages.
		var aErrorMessages = [];
		
		var currentMethod, currentErrorTargetTagId, currentErrorMessage;
		
		for (var i = 0, ii = this.oForm.elements.length; i < ii; i++) {
			this.oCurrElem = this.oForm.elements[i];
			if (__shouldSkipHiddenFields && this.oCurrElem.type == "hidden") {
				continue;
			}
			if (this.oCurrElem.type && this.oCurrElem.type == "radio") {
				oValidatorData = ValidatorData["field-based"][this.oCurrElem.name];
			}
			else {
				oValidatorData = ValidatorData["field-based"][this.oCurrElem.id];
			}
			this.oCurrParams = this._mergeParams(oValidatorData/*, oProperties*/, this._getParams(this.oCurrElem.className));
			for (var j in this.oCurrParams) {
				if ("function" == typeof this[j]) {
					if (!this[j](this.oCurrParams[j])) {
						
						_addErrorMessage(this.oCurrElem, TextRegistry.find("errStr", this.oCurrElem.id, this.oForm.id, j));
						/*
						_failedValidationIndicator(this.oForm, true);// Show the generic warning message.
						
						// Mark the row as problematic.
						if (this.oCurrRow) {
							if (!this.oCurrRow.className.match(/\form-berror\b/)) {
								this.oCurrRow.className += " form-error";
								
								var dErrorBox = this.oCurrRow.firstChild;
								if (dErrorBox.tagName != "DIV" || dErrorBox.className != "head") {
									dErrorBox = document.createElement("div");
									dErrorBox.className = "head";
									dErrorBox = this.oCurrRow.insertBefore(dErrorBox, this.oCurrRow.firstChild);
								}
								dErrorBox.innerHTML += "<div class=\"message\">" + TextRegistry.find("errStr", this.oCurrElem.id, this.oForm.id, j) + "</div>";
//console.debug("errStr." + this.oCurrElem.id + "." + this.oForm.id + "." + j);
							}
						}
						*/
						
						// Open the relevant section at the myAccount pages (if there is one).
						var dSectionWrapper = getParentTag(this.oCurrElem, "div", "\\bformSection\\b");
						if (dSectionWrapper) dSectionWrapper.style.display = "block";
					}
				} else {
					try {console.error("No such validator.", this.oCurrElem, this[j])} catch (ex) {}
				}
			}
		}
		
		if (!document.getElementById("_visibleValidationIndicator")) {
			// Show the "wait while saving" message, if there is any (for this form)
			var waitMessage = TextRegistry.get("warnSavingWait." + this.oForm.id, true);
			if (waitMessage) {
				var oldHoldOnMessage = document.getElementById("pleaseHoldOn");
				if (oldHoldOnMessage) {
					oldHoldOnMessage.innerHTML = waitMessage;
					oldHoldOnMessage.style.display = "block";
				} else {
					// Find the submit button and insert a new message div before it.
					var cButtons = this.oForm.getElementsByTagName("button");
					for (var i = 0, ii = cButtons.length; i < ii; i++) {
						if (String(cButtons[i].getAttribute("onclick")).match(/\bvalidate2/)) {
							var divMessage = document.createElement("div");
								divMessage.id = "please-wait-while-saving";
								divMessage.innerHTML = waitMessage;
							cButtons[i].parentNode.insertBefore(divMessage, cButtons[i]);
//							location.hash = "please-wait-while-saving";
							break;
						}
					}
				}
			}
			
			disableUnloadWarning = true;
			if (this.fFuncBeforeSubmit && typeof(this.fFuncBeforeSubmit) == "function")
			{
				this.fFuncBeforeSubmit();
			}
			
			// Remove the server-side messages, if there is any.
			var cServerMessages = getElementsByClassName("notification");
			for (var i = 0; i < cServerMessages.length; i++) {
				if (cServerMessages[i].nodeName == "UL") {
					cServerMessages[i].parentNode.removeChild(cServerMessages[i]);
				}
			}
			
			// Let's shield the whole page so the user cannot click on anything.
			var oShield = document.createElement("div");
			oShield.id = "oSubmitShield";
			oShield.style.position = "absolute";
			oShield.style.zIndex = "123456";
			oShield.style.width = "100%";
			oShield.style.height = document.body.clientHeight + "px";
			oShield.style.top = "0";
			oShield.style.left = "0";
			oShield.style.background = "url(images/_blank.gif)";
			oShield = document.getElementsByTagName("body")[0].appendChild(oShield);
			// After a while remove the shield:
			setTimeout("var oShield = document.getElementById('oSubmitShield'); oShield.parentNode.removeChild(oShield)"
				, 60000);// 60000 = 1 minute
			
			this.oForm.alreadySubmitted = true;
			setReadOnly(this.oForm);
			
			window.onbeforeunload = null;
			
			//only submit the form if the form submission was not disabled
			if (!this.notForSubmission) {
				this.oForm.submit();
			}
		}
		
		markTabsWithInvalidFields();

//		location.hash = "#";// jump to the top of the page, so the user will see the generic error message
		return false;// just for fun, it is not necessary as we cannot use <form onsubmit>
	}
}
function _addErrorMessage(oField, msg) {
	if (!oField || ("FORM" != oField.nodeName && !oField.form)) {
		return;
	}
	
	var form = ("FORM" === oField.nodeName) ? oField : oField.form;
	
	_failedValidationIndicator(form, true);// Show the generic warning message.
	
	if (form === oField) {
		document.getElementById("_visibleValidationIndicator").innerHTML += "<div class=\"message\">" + msg + "</div>";
	}
	else {
		var oRow = getParentTag(oField, "div", "\\brow2?\\b");
		
		// Mark the row as problematic.
		if (oRow) {
			if (!oRow.className.match(/\form-berror\b/)) {
				oRow.className += " form-error";
				
				var dErrorBox = oRow.firstChild;
				if (dErrorBox.tagName != "DIV" || dErrorBox.className != "head") {
					dErrorBox = document.createElement("div");
					dErrorBox.className = "head";
					dErrorBox = oRow.insertBefore(dErrorBox, oRow.firstChild);
				}
				dErrorBox.innerHTML += "<div class=\"message\">" + msg + "</div>";
			}
		}
	}
}

/**
* @param Numeric
*/
Validator.prototype.minLength = function () {
	if (!this.oCurrElem.value.length) return true;
	
	return (String(this.oCurrElem.value).length >= parseInt(arguments[0], 10));
}

/**
* @param Numeric
*/
Validator.prototype.maxLength = function () {
	if (!this.oCurrElem.value.length) return true;
	
	return (String(this.oCurrElem.value).length <= parseInt(arguments[0], 10));
}

/**
* @param String "mandatory"
*/
Validator.prototype.mandatory = function (force) {
	if (true !== force && (arguments[0] != "mandatory" && arguments[0] != "true")) return true;
	
	var tagName = this.oCurrElem.tagName.toLowerCase();
	if ("input" == tagName) {
		if ("checkbox" == this.oCurrElem.getAttribute("type").toLowerCase()
			||
			"radio" == this.oCurrElem.getAttribute("type").toLowerCase()) {
			return this.oCurrElem.checked;
		} else {
			return (this.oCurrElem.value.length > 0);
		}
	} else if ("textarea" == tagName) {
		return (this.oCurrElem.value.length > 0);
	} else if ("select" == tagName) {
		if (this.oCurrElem.getAttribute("multiple") != "multiple") {
			return (this.oCurrElem.selectedIndex > 0);
		}
		for (var i = 0, ii = this.oCurrElem.options.length; i < ii; i++) {
			if (this.oCurrElem.options[i].selected) return true;
		}
		return false;
	}
}

/**
* @param String [string|int|integer|float|number|email|month|day|year]
*/
Validator.prototype.dataType = function () {
	if (!this.oCurrElem.value.length) return true;
	
	switch (arguments[0][0]) {
		case "string":
			return true;
		
		case "int":
		case "integer":
			return this.oCurrElem.value.match(/^-?[0-9]+$/);
		
		case "float":
		case "number":
			return this.oCurrElem.value.match(/^-?[0-9]+(\.[0-9]+)?$/);
		
		case "email":
			return this.oCurrElem.value.match(/^\S+@\S+\.\S+$/);
		
		case "month":
			return (!isNaN(this.oCurrElem.value)
				&& 1 <= this.oCurrElem.value
				&& 12 >= this.oCurrElem.value);
		
		case "day":
			return (!isNaN(this.oCurrElem.value)
				&& 1 <= this.oCurrElem.value
				&& 31 >= this.oCurrElem.value);
		
		case "year":
			return !isNaN(this.oCurrElem.value) && this.oCurrElem.value.match(/^(19|20)[0-9]{2}$/);
	}
}

/**
* @param String Reference object ID names are to be separated by spaces or commas. Uses "AND" relation.
*/
Validator.prototype.ifChecked = function () {
	var aRefObjList = arguments[0][0].split(/[ ,]+/);
	var oRef;
	for (var i = 0, ii = aRefObjList.length; i < ii; i++) {
		oRef = document.getElementById(aRefObjList[i]);
		if (!oRef) continue;// Just skip non-existing elements.
		
		if (oRef.nodeName == "INPUT" && oRef.type.match(/radio|checkbox/)) {
			if (!oRef.checked) {
				return true;
			}
		}
		if (oRef.nodeName == "INPUT" && oRef.type.match(/text|password/)) {
			if (!oRef.value.length) {
				return true;
			}
		}
		if (oRef.nodeName == "TEXTAREA" && !oRef.value.length) {
			return true;
		}
	}
	return this.mandatory(true);
}


/**
* @param String Radio group name
*/
Validator.prototype.mandatoryRadioGroup = function () {
	if (arguments[0] != "mandatoryRadioGroup" && arguments[0] != "true") {
		return true;
	}
	
	// Ideally only one radio element should have a "mandatoryRadioGroup" value, but to make things easier,
	// it automatically ignores any subsequent calls in a radio group by storing the already validated group names in this array.
	if (!this.alreadyValidatedRadioGroups) this.alreadyValidatedRadioGroups = [];
	var groupName = this.oCurrElem.getAttribute("name");
	
	for (var i = 0, ii = this.alreadyValidatedRadioGroups.length; i < ii; i++) {
		if (this.alreadyValidatedRadioGroups[i] == groupName) {
			return true;
		}
	}
	
	this.alreadyValidatedRadioGroups.push(groupName);
	
	for (var i = 0, ii = this.oForm[groupName].length; i < ii; i++) {
		if (this.oForm[groupName][i].checked) {
			return true;
		}
	}
	return false;
}

/**
* @param Numeric
*/
Validator.prototype.minValue = function () {
	if (!this.oCurrElem.value.length) return true;
	
	return (parseFloat(this.oCurrElem.value) >= parseFloat(arguments[0]));
}

/**
* @param Numeric
*/
Validator.prototype.maxValue = function () {
	if (!this.oCurrElem.value.length) return true;
	
	return (parseFloat(this.oCurrElem.value) <= parseFloat(arguments[0]));
}

/**
* @param String A regular expression
* @param String Optional flags for the regex. (e.g. "g", "gi", "gim" etc.)
*/
Validator.prototype.pattern = function () {
	if (!this.oCurrElem.value.length) return true;
	
	var flags = arguments[1] || "";
	return RegExp(arguments[0], flags).test(this.oCurrElem.value);
}

/**
* @param String Ids separated by spaces or commas.
*/
Validator.prototype.equalsTo = function () {
	//if (!this.oCurrElem.value.length) return true;

	var aTargetElements = arguments[0][0].split(/[\s,]+/);
	var targetElement;
	for (var i = 0, ii = aTargetElements.length; i < ii; i++) {
		targetElement = document.getElementById(aTargetElements[i]);
		if (targetElement && this.oCurrElem.value != targetElement.value) {
			return false;
		} 
	}
	
	return true;
}

/**
* @param String Ids separated by spaces or commas.
*/
Validator.prototype.notEqualsTo = function () {
	//if (!this.oCurrElem.value.length) return true;
	
	var aTargetElements = arguments[0][0].split(/[\s,]+/);
	var targetElement;
	for (var i = 0, ii = aTargetElements.length; i < ii; i++) {
		targetElement = document.getElementById(aTargetElements[i]);
		targetElementValue = targetElement
			? targetElement.value
			: document.getElementById("inserted-" + aTargetElements[i])
				? document.getElementById("inserted-" + aTargetElements[i]).innerHTML
				: null;
		if (targetElement && this.oCurrElem.value == targetElementValue) {
			return false;
		} 
	}
	
	return true;
}

/**
* @param String Valid extension.
*/
Validator.prototype.fileExtension = function () {
	//if (!this.oCurrElem.value.length) return true;
	
	return !!this.oCurrElem.value.match(new RegExp("\." + arguments[0] + "$", "i")); 
}


function positionIncapableBrowserHint() {
	var oWrapperDiv = document.getElementById("incapableBrowser");
	var oPointerDiv = document.getElementById("incapableBrowserPointer");
	if (!oWrapperDiv || !oPointerDiv) return;
	
	var oPointerImg = oPointerDiv.getElementsByTagName("img")[0];
	
	var cDivs = oWrapperDiv.getElementsByTagName("div");
	var lft = 0;
	for (var i = 0, ii = cDivs.length; i < ii; i++) {
		lft += cDivs[i].clientWidth;
		if (cDivs[i].className.match(/\bfailed\b/)) {
			if (i > 0) {
				var mod = (i == 1) ? 20 : 10;
				oPointerImg.style.left = lft - (cDivs[i].clientWidth / 2) + (oPointerImg.clientWidth / 2) - mod + "px";
			}
			break; 
		}
	}
}

function showManualInstallSteps() {
	if (window.isIE6) {
		document.getElementById("manualdl-ie6").style.display = "block";
	} else if (!window.isIE7 && !window.opera) {
		document.getElementById("manualdl-ff").style.display = "block";
	} else if (window.opera) {
		document.getElementById("manualdl-opera").style.display = "block";
	} else {
		document.getElementById("manualdl-ie7").style.display = "block";
	}
}

function initProgressIndicator() {
	var ul = document.getElementById("progress-indicator");
	if (!ul) {
		return;
	}
	var li = ul.getElementsByTagName("li");
	li[0].className += " first-child";
	li[li.length - 1].className += " last-child";
	
	for (var i = 0, ii = li.length; i < ii; i++) {
		if (li[i].className.indexOf("current") > -1) {
			li[i].innerHTML = "<span><\/span>";
			break;
		} else {
			li[i].className += " passed";
		}
	}
}


function popupForImage(src, width, height) {
	var w = window.open('', '', 'width=' + width + ',height=' + height + ',top='
		+ ((screen.availHeight-height)/2) + ',left=' + ((screen.availWidth-width)/2));
	w.document.open();
	w.document.write('<html><head><title>'
		+ src
		+ '<\/title><\/head><body style="margin:0;padding:0" onblur="self.close()"><img src="'
		+ src
		+ '" width="'
		+ width
		+ '" height="'
		+ height
		+ '" alt=""><\/body><\/html>');
	w.document.close();
	w.focus();
	return false;
}



function activatePaymentToolComponent() {
	var setAsDefaultRadio = document.getElementById( "newPaymentTool" );
	if ( ! setAsDefaultRadio || setAsDefaultRadio.tagName != "INPUT" ) {
		return false;
	}
	
	var component = getParentTag( setAsDefaultRadio, "table" );
	
	var inputs = component.getElementsByTagName( "input" );
	for ( var i = 0, ii = inputs.length; i < ii; i++ ) {
		switch ( inputs[ i ].type ) {
			case "radio" :
				inputs[i].onclick = function(){
					if ( this.checked ) {
						setAsDefaultRadio.checked = true;
					}
				}
				break;
				
			case "text" :
			case "password" :
				inputs[i].onblur = function(){
					if ( this.value.length ) {
						setAsDefaultRadio.checked = true;
					}
				}
				break;
		}
	}
}
addDOMLoadEvent( activatePaymentToolComponent );


function showServerSideMessagesOnTabs() {
	var errorMsgDivs = [], divs = document.getElementsByTagName("div");
	for (var i = 0, ii = divs.length; i < ii; i++) {
		if (divs[i].className.match(/\berrormsg\b/)) {
			errorMsgDivs.push(divs[i]);
		}
	}
	if (!errorMsgDivs.length) {
		return;// found no server-side messages, nothing to do.
	}
	for (var i = 0, ii = errorMsgDivs.length; i < ii; i++) {
		var div = errorMsgDivs[i];
		var form = div.parentNode;
//		div.innerHTML += "\nemail=email Test Server Error Message";
//		div.innerHTML += "\ncompanyInfoByEmail=companyInfoByEmail Test Server Error Message";
//		div.innerHTML += "\nYY=DADA=daAD";
		var messages = div.innerHTML.replace(/^\s+|\s+$/g, "").split(/\n/g);
		if (messages.length) {
			var m;
			for (var j = 0, jj = messages.length; j < jj; j++) {
				m = messages[j].match(/^(.*?)=(.+)$/);
				if (null === m) {
					continue;
				}
				// m[1] <= form field ID (if empty, then the message couldn't be tied to a single field, therefore it is a global message)
				// m[2] <= message text
				var elem = (m[1] && m[1].length) ? document.getElementById(m[1]) : form;
				_addErrorMessage(elem, m[2]);
			}
		}
	}
	markTabsWithInvalidFields();
}
function initTab(tabLabelElem) {
	function setActiveTab(evt) {
		var cTabLabels, srcElement, label, link;
		cTabLabels = tabLabelElem.getElementsByTagName( "li" );
		if (evt === true) {
			for ( var i = cTabLabels.length - 1, ii = 0; i >= ii; i-- ) {
				srcElement = cTabLabels[i];
				if ( srcElement.className.match(/\bactive\b/)
						|| (location.hash && location.hash.length && location.hash == String(srcElement.getElementsByTagName("a")[0].href).replace(/.+(?=#)/, "")) ) {
					// remove "active" class from every other <li>s, and set it for the current one (in support of location.hash-based deep linking)
					for ( var j = cTabLabels.length - 1, jj = 0; j >= jj; j-- ) {
						cTabLabels[j].className.replace(/\bactive\b/g, "");
						if (cTabLabels[j] === label) {
							cTabLabels[j].className += " active";
						}
					}
					break;
				}
			}
			label = srcElement;
		}
		else {
			srcElement = this;
			label = this.parentNode;
		}
//		createCookie( "activeMyAccountTab", li );
		
		// Reset the active status of the tab labels, then mark the active one.
		// Hide the non-active tab panels.
		var isActive, panel;
		for ( var i = 0, ii = cTabLabels.length; i < ii; i++ ) {
			isActive = false;
			cTabLabels[i].className = cTabLabels[i].className.replace(/\bactive\b/g, "");// hide
			if ( cTabLabels[i] == label ) {
				isActive = true;
				cTabLabels[i].className += " active";
			}
			panel = document.getElementById( cTabLabels[i].firstChild.getAttribute("href").replace(/.*#/, "") );
			if (panel) {
				panel.style.display = isActive ? "block" : "none";
				panel.tabLabelLink = cTabLabels[i].getElementsByTagName("a")[0];
			}
		}
		
		label.getElementsByTagName("a")[0].blur();
		
		return false;
	}
	
	if ( typeof tabLabelElem == "string" ) {
		tabLabelElem = document.getElementById( tabLabelElem );
	}
	
	var cTabs = tabLabelElem.getElementsByTagName( "li" );
	var refPanelId, isActive, isMultiLine;
	for ( var i = 0, ii = cTabs.length; i < ii; i++ ) {
		if ( i == 0 ) {
			cTabs[i].className += " first-child";
		}
		cTabs[i].firstChild.onclick = setActiveTab;
		isMultiLine = !!cTabs[i].firstChild.innerHTML.match(/<br\s*\/?>/i);
		cTabs[i].firstChild.innerHTML = "<span class=\"icon\"><\/span><span class=\"bg\"><span class=\"text" + (isMultiLine ? " multiline" : "") + "\">" + cTabs[i].firstChild.innerHTML + "<\/span><\/span>";
	}
	
	setActiveTab(true);
	showServerSideMessagesOnTabs();
}
function markTabsWithInvalidFields() {
	var wrapperDiv = document.getElementById("fullPageLayout0904");
	if (!wrapperDiv) {
		return;
	}
	
	var tabPanelDivs = [], div = wrapperDiv.getElementsByTagName("div");
	for (var i = 0, ii = div.length; i < ii; i++) {
		if (div[i].className.match(/\btab-panels\b/)) {
			tabPanelDivs.push(div[i]);
		}
	}

	var areLabelsCleared = false;	
	for (i = 0, ii = tabPanelDivs.length; i < ii; i++) {
		var div = tabPanelDivs[i].getElementsByTagName("div");
		for (var j = 0, jj = div.length; j < jj; j++) {
			if (div[j].className.match(/\bform-error\b/)) {
				var divPanel = getParentTag(div[j], "div", "tab-panel");
				if (!areLabelsCleared) {
					// Init. Remove the "error" class names from the tab label links.
					var tabLinks = divPanel.tabLabelLink.parentNode.parentNode.getElementsByTagName("a");
					for (var k = 0, kk = tabLinks.length; k < kk; k++) {
						tabLinks[k].className = tabLinks[k].className.replace(/\s*error\s*/g, ""); 
					}
					areLabelsCleared = true;
				}
				divPanel.tabLabelLink.className += " error";
			}
		}
	}
}

function attachUnsavedFormLister(formId, promptMessage) {
	var f = document.getElementById(formId);
	for (var i = 0, ii = f.elements.length; i < ii; i++) {
		addEvent(f[i], "change", function (e) {
			e = e || window.event;
			var o = e.target || e.srcElement;
			if (!o.form.hasChanged) {
				o.form.hasChanged = true;
				window.onbeforeunload = function(){
					return o.form.unsavedMessage;
				}
			}
		});
	}
	f.unsavedMessage = promptMessage.replace(/<br\s*\/?>/g, "\n").replace(/&nbsp;/g, " ");
}
