YAHOO.namespace("gl");

/* Stealing the single most useful thing in the Prototype library.
 * This function allows you to explicitly bind the scope of the "this"
 * reference. The default behavior of JavaScript if you assign a function from
 * an object to another object, for example an event handler of a DOM element,
 * is for the "this" reference within the function to refer to the new owner.
 * Using this function allows you to bind the this reference to the original
 * object.
 */
Function.prototype.bind = function(object) {
	var __method = this;
	return function() {
		return __method.apply(object, arguments);
	}
};

/*
 * This function submits an ATG form via AJAX. It fakes x and y coordinates
 * of the image input specified to simulate an actual click, so the ATG
 * server will properly process the form.
 * Params:
 * formName: name of the form to submit
 * imageName: name of the image input to submit the form
 * callback: a JavaScript object suitable for call into YAHOO.util.Connect.asyncRequest.
 * At minimum this should contain success and failure properties, which should be 
 * functions to handle the response from the server.  For more info see
 * http://developer.yahoo.com/yui/connection/
 */
function submitATGImageFormAsync(formName, imageName, callback) {
	var form = document.forms[formName];
	var imageArr;
	if (form) {
		imageArr = YAHOO.util.Dom.getElementsBy(function(node) {
			return node.name == imageName;	
		}, 'input', form);
	}
	if (form && imageArr && imageArr[0]) {
		/* create fake image click data so form handler method will be invoked */
		var imageClickData = imageName + ".x=1&" + imageName + ".y=1" ; 
		
		YAHOO.util.Connect.setForm(form);
		YAHOO.util.Connect.asyncRequest(form.method, form.action, callback, imageClickData);
	}
}

/*
 * Submits an ATG form via AJAX. To use this you should declare a hidden field in the form
 * tied to the form handler method.
 * Params:
 * formName: name of the form to submit
 * callback: a JavaScript object suitable for call into YAHOO.util.Connect.asyncRequest.
 * At minimum this should contain success and failure properties, which should be 
 * functions to handle the response from the server.  For more info see
 * http://developer.yahoo.com/yui/connection/
 */
function submitATGFormAsync(formName, callback) {
	var form = document.forms[formName];

	if (form) {
		YAHOO.util.Connect.setForm(form);
		YAHOO.util.Connect.asyncRequest(form.method, form.action, callback);
	}
}

function imbedSessionId(anchor) {
  var pos = document.cookie.indexOf('JSESSIONID=');
  if (pos != -1) {
	  var valStart = pos + 11;
	  var valEnd = document.cookie.indexOf(';', valStart);
	  if (valEnd == -1) valEnd = document.cookie.length;
	  var val = document.cookie.substring(valStart, valEnd);
	  var hrefUrl = anchor.href;
	  var qPos = hrefUrl.indexOf('?');
	  if (qPos == -1) {
		qPos = hrefUrl.length; 
	  }
	  var newUrl = hrefUrl.substring(0, qPos);
	  newUrl = newUrl + ';jsessionid=' + val;
	  if (qPos != hrefUrl.length) {
		newUrl = newUrl + hrefUrl.substring(qPos);
	  }
	  anchor.href = newUrl;
  }
  return true;
}

function launchPlayer(url, params) {
	var wn;
	wn = window.open(url, "embPlayer", "resizable=no,height=678,width=952,scrollbars=0,location=0,menubar=0,toolbar=0");
	wn.focus();
	var evt = YAHOO.util.Event.getEvent();
	YAHOO.util.Event.stopEvent(evt);
}

/*
 * Resize a window so the client area is the specified dimensions.
 */
function resizeInner(width, height) {
	window.resizeTo(width, height);
	var diffw = width - YAHOO.util.Dom.getViewportWidth();
	var diffy = height - YAHOO.util.Dom.getViewportHeight();
	window.resizeTo(width + diffw, height + diffy);
}

/*
 * http://www.htmlcodetutorial.com/linking/linking_famsupp_75.html
 * 8987: remove focus on mylink page
 */
function targetopener(mylink, closeme, closeonly) {
    if (typeof window.opener != 'undefined' && window.opener && !window.opener.closed) {
		if (!closeonly) {
		    window.opener.location.href=mylink.href;
		}
		if (closeme) {
		    window.close();
		}
		return false;
    } else {
		var wn = window.open(mylink);
		if (closeme) {
		    window.close();
		}
		return false;
    }
}

function elementExpand(expandElementID, linkElementID, expandText, collapseText, linkImageElementID, expandImage, collapseImage) {
	var expandElement = document.getElementById(expandElementID);
	var linkElement = document.getElementById(linkElementID);
	var linkImagElement = document.getElementById(linkImageElementID);
	
	if( expandElement.style.display ) {
		if( expandElement.style.display == "inline" || expandElement.style.visibility == "visible" ) {
			expandElement.style.display = "none";
			expandElement.style.visibility = "hidden";
			if (linkElement && expandText) {
				linkElement.innerHTML = expandText;
			}
			
			if (linkImagElement && expandImage) {
				linkImagElement.src = expandImage;
			}
		} else {
			expandElement.style.display = "inline";
			expandElement.style.visibility = "visible";
			if (linkElement && collapseText) {
				linkElement.innerHTML = collapseText;
			}
			
			if (linkImagElement && collapseImage) {
				linkImagElement.src = collapseImage;
			}
		}
	}
}

/* These two functions work around an issue in Firefox where colors applied to <option> elements
 * will not propogate up to the containing <select>.  To use it simply include a call to
 * YAHOO.util.Event.onDOMReady(fixSelectColors, "elId") in the page, where "elId" is the ID of the 
 * <select> dropdown.
 */
function updateSelectColors() {
	var opt = this.options[this.selectedIndex];
	this.style.color = opt.style.color;
}

function fixSelectColors(type, args, elId) {
	var slct = document.getElementById(elId);
	if (slct) {
		var idx = slct.selectedIndex;
		var opt = slct.options[idx];
		var clr = opt.style.color;
		slct.style.color = clr;
		YAHOO.util.Event.addListener(slct, "change", updateSelectColors, null, slct);
	}
}

/* Thin control layer to allow external left/right arrow controls */
YAHOO.gl.CarouselControls = function(opts) {
	this.carousel = opts.carousel;
	this.leftButtonId = opts.leftButtonId;
	this.rightButtonId = opts.rightButtonId;
	this.leftDisabledClass = opts.leftDisabledClass;
	this.leftEnabledClass = opts.leftEnabledClass;
	this.rightDisabledClass = opts.rightDisabledClass;
	this.rightEnabledClass = opts.rightEnabledClass;
	YAHOO.util.Event.addListener(this.leftButtonId, "click", this.onLeftButtonClick, null, this);
	YAHOO.util.Event.addListener(this.rightButtonId, "click", this.onRightButtonClick, null, this);
	this.carousel.addListener("afterScroll", this.onAfterScroll, null, this);
}

YAHOO.gl.CarouselControls.prototype = {
	onLeftButtonClick: function() {
		this.carousel.scrollPageBackward();
	},
	onRightButtonClick: function() {
		this.carousel.scrollPageForward();
	},
	onAfterScroll: function(visibleItems) {
		var leftButton = document.getElementById(this.leftButtonId);
		var rightButton = document.getElementById(this.rightButtonId);
		var numItems = this.carousel.get("numItems");
		var numVisible = this.carousel.get("numVisible");
		
		if (leftButton) {
			if (visibleItems.first == 0) {
				YAHOO.util.Dom.replaceClass(leftButton, this.leftEnabledClass, this.leftDisabledClass);
			} else {
				YAHOO.util.Dom.replaceClass(leftButton, this.leftDisabledClass, this.leftEnabledClass);
			}
		}
		if (rightButton) {
			if (visibleItems.first == visibleItems.last || visibleItems.last - visibleItems.first < numVisible) {
				YAHOO.util.Dom.replaceClass(rightButton, this.rightEnabledClass, this.rightDisabledClass);
			} else {
				YAHOO.util.Dom.replaceClass(rightButton, this.rightDisabledClass, this.rightEnabledClass);
			}
		}
	}
}

/* truncates link text for links in fixed height divs.  assumes 1 link per container. */
function truncOverflowLinks(className, containerId, overflow, pMoreText) {
	var allowedOverflow = (overflow ? parseInt(overflow) : 0);
	var moreText = pMoreText || "...";
	var containers = YAHOO.util.Dom.getElementsByClassName(className, null, containerId);
	if (containers) {	
		for (var i = 0;i < containers.length; i++) {
			var links = YAHOO.util.Dom.getChildrenBy(containers[i], function(node) {
				return node.tagName == 'A';
			});
			if (links && links.length > 0) {
				var link = links[0];
				var text = link.innerHTML;
				var contHeight = containers[i].offsetHeight;
				var maxHeight = contHeight + allowedOverflow;
				while (link.offsetHeight > maxHeight) {
					var idx = text.lastIndexOf(" ");
					text = text.substr(0, idx);
					link.innerHTML = text + moreText;
				}
			}
		}
	}
}

/* these two functions are tightly coupled with the UI in /includes/merchSceneFrag.jhtml */
function addSceneMerchFrag(sceneId, showRemove) {
	var callback = {
		success: function(o) {
			var span = document.getElementById("sceneSpan" + o.argument.sceneId);
			if (showRemove) {
				var link = span.getElementsByTagName("a")[0];
				link.innerHTML = "Remove";
				link.onclick = function() {
					removeSceneMerchFrag(o.argument.sceneId);
				}	
			} else {
				span.innerHTML = "Saved";
			}
			YAHOO.namespace("gl");
			if (YAHOO.gl.postAddSceneFunc) {
				YAHOO.gl.postAddSceneFunc();
			}
		},
		failure: function(o) {},
		argument: {"sceneId": sceneId}
	};
	YAHOO.util.Connect.asyncRequest('GET', "/ajax/addOrRemoveScene.jhtml?add=" + sceneId, callback); 
	var evt = YAHOO.util.Event.getEvent();
	YAHOO.util.Event.stopEvent(evt);
}

function removeSceneMerchFrag(sceneId) {
	var callback = {
		success: function(o) {
			YAHOO.namespace("gl");
			if (YAHOO.gl.reloadOnRemoveScene) {
				window.location.reload(true);
			} else {
				var span = document.getElementById("sceneSpan" + o.argument.sceneId);
				var link = span.getElementsByTagName("a")[0];
				link.innerHTML = "Save";
				link.onclick = function() {
					addSceneMerchFrag(o.argument.sceneId);
				}
				if (YAHOO.gl.postRemoveSceneFunc) {
					YAHOO.gl.postRemoveSceneFunc();
				}
			}
		},
		failure: function(o) {},
		argument: {"sceneId": sceneId}
	};
	YAHOO.util.Connect.asyncRequest('GET', "/ajax/addOrRemoveScene.jhtml?remove=" + sceneId, callback);
	var evt = YAHOO.util.Event.getEvent();
	YAHOO.util.Event.stopEvent(evt);
}

function requestPassword() {
	var form = document.getElementById("passwordReminderForm");
	form.submit();
}

function setDefaultInputText(inputId, msg) {
	YAHOO.util.Event.onContentReady(inputId, function() {
		var input = document.getElementById(inputId);
		if (input.value == '') {
			input.value = msg;
			YAHOO.util.Event.addFocusListener(input, function() {
				if (this.value == msg) {
					this.value = '';
				}
			}, null, input);
			YAHOO.util.Event.addBlurListener(input, function() {
				if (this.value == '') {
					this.value = msg;
				}
			}, null, input);
		}
	});
}

function requestPasswordForError() {
	var callback = {
		success: function(o) {
			var result = YAHOO.lang.JSON.parse(o.responseText);
			displayPwMessageMoveBox(result.message);
			if (result.result == 'success') {
				var regForm = document.getElementById('registrationForm');
				var textFields = YAHOO.util.Dom.getElementsBy(function(el) {
					return el.tagName == 'INPUT' && (el.type == 'text' || el.type == 'password');
				}, 'INPUT', regForm);
				for (var i = 0; i < textFields.length; i++) {
					textFields[i].value = '';
				}
				var loginForm = document.getElementById('loginForm');
				textFields = YAHOO.util.Dom.getElementsBy(function(el) {
					return el.tagName == 'INPUT' && (el.type == 'text' || el.type == 'password');
				}, 'INPUT', loginForm);
				for (var i = 0; i < textFields.length; i++) {
					var field = textFields[i];
					if (field.type == 'text') {
						field.value = result.email;
					} else if (field.type == 'password') {
						field.focus();
					}
				}
			}
		},
		failure: function(o) {
			displayPwMessage("We encountered an error sending your password. Please try again later or contact Customer Service.");
		}
	};
	submitATGFormAsync("passwordReminderErrorForm", callback);
}

function requestPasswordForPPM() {
	var callback = {
		success: function(o) {
			var result = YAHOO.lang.JSON.parse(o.responseText);
			displayPwMessageMoveBox(result.message, 'ppmErrorBox', 'ppmLoginErrorContainer');
			updateLoginSuccessLink('/pay_per_minute.jhtml');
		},
		failure: function(o) {
			displayPwMessage("We encountered an error sending your password. Please try again later or contact Customer Service.");
		}
	};
	submitATGFormAsync("passwordReminderErrorForm", callback);
}

function updateLoginSuccessLink(successLink) {
	var login = document.getElementById('topLogin');
	
	if (login.href.indexOf('?') != -1) {
		login.href+= "&successURL=" + successLink;
	} else {
		login.href+= "?successURL=" + successLink;
	}
}

function displayPwMessage(msg) {
	var div = document.getElementById("pwResult");
	div.innerHTML = "<em>" + msg + "</em>";
	div.style.display = "block";
}

function displayPwMessageClearError(msg) {
	var div = document.getElementById("errorBox");
	div.innerHTML = '<div style="padding: 3px;"><em>' + msg + '</em></div>';
}

function displayPwMessageMoveBox(msg, errorBox, loginErrorContainer) {
	var div;
	if (errorBox) {
		div = document.getElementById(errorBox);
	} else {
		div = document.getElementById("errorBox");
	}
	var divParent = div.parentNode;
	divParent.removeChild(div);
	var loginErrorDiv;
	if (loginErrorContainer) {
		loginErrorDiv = document.getElementById(loginErrorContainer);
		loginErrorDiv.innerHTML = '<div id="ppmErrorBox" style="padding: 4px;"><em>' + msg + '</em></div>';
	} else {
		loginErrorDiv = document.getElementById("loginErrorContainer");
		loginErrorDiv.innerHTML = '<div id="errorBox" style="padding: 4px;"><em>' + msg + '</em></div>';
	}
}

function universalDisplayToggle(idOrElementOrArray, firstOption, secondOption, defaultValue) {
	var current = YAHOO.util.Dom.getStyle(idOrElementOrArray, 'display');
	if (current == null) {
		YAHOO.util.Dom.setStyle(idOrElementOrArray, 'display', defaultValue);
	} else if (current == firstOption) {
		YAHOO.util.Dom.setStyle(idOrElementOrArray, 'display', secondOption);
	} else if (current == secondOption) {
		YAHOO.util.Dom.setStyle(idOrElementOrArray, 'display', firstOption);
	} else {
		YAHOO.util.Dom.setStyle(idOrElementOrArray, 'display', defaultValue);
	}
}

//http://www.strictly-software.com/scripts/downloads/encoder.js

Encoder = {

	// When encoding do we convert characters into html or numerical entities
	EncodeType : "entity",  // entity OR numerical

	isEmpty : function(val){
		if(val){
			return ((val===null) || val.length==0 || /^\s+$/.test(val));
		}else{
			return true;
		}
	},
	// Convert HTML entities into numerical entities
	HTML2Numerical : function(s){
		var arr1 = new Array('&nbsp;','&iexcl;','&cent;','&pound;','&curren;','&yen;','&brvbar;','&sect;','&uml;','&copy;','&ordf;','&laquo;','&not;','&shy;','&reg;','&macr;','&deg;','&plusmn;','&sup2;','&sup3;','&acute;','&micro;','&para;','&middot;','&cedil;','&sup1;','&ordm;','&raquo;','&frac14;','&frac12;','&frac34;','&iquest;','&agrave;','&aacute;','&acirc;','&atilde;','&Auml;','&aring;','&aelig;','&ccedil;','&egrave;','&eacute;','&ecirc;','&euml;','&igrave;','&iacute;','&icirc;','&iuml;','&eth;','&ntilde;','&ograve;','&oacute;','&ocirc;','&otilde;','&Ouml;','&times;','&oslash;','&ugrave;','&uacute;','&ucirc;','&Uuml;','&yacute;','&thorn;','&szlig;','&agrave;','&aacute;','&acirc;','&atilde;','&auml;','&aring;','&aelig;','&ccedil;','&egrave;','&eacute;','&ecirc;','&euml;','&igrave;','&iacute;','&icirc;','&iuml;','&eth;','&ntilde;','&ograve;','&oacute;','&ocirc;','&otilde;','&ouml;','&divide;','&oslash;','&ugrave;','&uacute;','&ucirc;','&uuml;','&yacute;','&thorn;','&yuml;','&quot;','&amp;','&lt;','&gt;','&oelig;','&oelig;','&scaron;','&scaron;','&yuml;','&circ;','&tilde;','&ensp;','&emsp;','&thinsp;','&zwnj;','&zwj;','&lrm;','&rlm;','&ndash;','&mdash;','&lsquo;','&rsquo;','&sbquo;','&ldquo;','&rdquo;','&bdquo;','&dagger;','&dagger;','&permil;','&lsaquo;','&rsaquo;','&euro;','&fnof;','&alpha;','&beta;','&gamma;','&delta;','&epsilon;','&zeta;','&eta;','&theta;','&iota;','&kappa;','&lambda;','&mu;','&nu;','&xi;','&omicron;','&pi;','&rho;','&sigma;','&tau;','&upsilon;','&phi;','&chi;','&psi;','&omega;','&alpha;','&beta;','&gamma;','&delta;','&epsilon;','&zeta;','&eta;','&theta;','&iota;','&kappa;','&lambda;','&mu;','&nu;','&xi;','&omicron;','&pi;','&rho;','&sigmaf;','&sigma;','&tau;','&upsilon;','&phi;','&chi;','&psi;','&omega;','&thetasym;','&upsih;','&piv;','&bull;','&hellip;','&prime;','&prime;','&oline;','&frasl;','&weierp;','&image;','&real;','&trade;','&alefsym;','&larr;','&uarr;','&rarr;','&darr;','&harr;','&crarr;','&larr;','&uarr;','&rarr;','&darr;','&harr;','&forall;','&part;','&exist;','&empty;','&nabla;','&isin;','&notin;','&ni;','&prod;','&sum;','&minus;','&lowast;','&radic;','&prop;','&infin;','&ang;','&and;','&or;','&cap;','&cup;','&int;','&there4;','&sim;','&cong;','&asymp;','&ne;','&equiv;','&le;','&ge;','&sub;','&sup;','&nsub;','&sube;','&supe;','&oplus;','&otimes;','&perp;','&sdot;','&lceil;','&rceil;','&lfloor;','&rfloor;','&lang;','&rang;','&loz;','&spades;','&clubs;','&hearts;','&diams;');
		var arr2 = new Array('&#160;','&#161;','&#162;','&#163;','&#164;','&#165;','&#166;','&#167;','&#168;','&#169;','&#170;','&#171;','&#172;','&#173;','&#174;','&#175;','&#176;','&#177;','&#178;','&#179;','&#180;','&#181;','&#182;','&#183;','&#184;','&#185;','&#186;','&#187;','&#188;','&#189;','&#190;','&#191;','&#192;','&#193;','&#194;','&#195;','&#196;','&#197;','&#198;','&#199;','&#200;','&#201;','&#202;','&#203;','&#204;','&#205;','&#206;','&#207;','&#208;','&#209;','&#210;','&#211;','&#212;','&#213;','&#214;','&#215;','&#216;','&#217;','&#218;','&#219;','&#220;','&#221;','&#222;','&#223;','&#224;','&#225;','&#226;','&#227;','&#228;','&#229;','&#230;','&#231;','&#232;','&#233;','&#234;','&#235;','&#236;','&#237;','&#238;','&#239;','&#240;','&#241;','&#242;','&#243;','&#244;','&#245;','&#246;','&#247;','&#248;','&#249;','&#250;','&#251;','&#252;','&#253;','&#254;','&#255;','&#34;','&#38;','&#60;','&#62;','&#338;','&#339;','&#352;','&#353;','&#376;','&#710;','&#732;','&#8194;','&#8195;','&#8201;','&#8204;','&#8205;','&#8206;','&#8207;','&#8211;','&#8212;','&#8216;','&#8217;','&#8218;','&#8220;','&#8221;','&#8222;','&#8224;','&#8225;','&#8240;','&#8249;','&#8250;','&#8364;','&#402;','&#913;','&#914;','&#915;','&#916;','&#917;','&#918;','&#919;','&#920;','&#921;','&#922;','&#923;','&#924;','&#925;','&#926;','&#927;','&#928;','&#929;','&#931;','&#932;','&#933;','&#934;','&#935;','&#936;','&#937;','&#945;','&#946;','&#947;','&#948;','&#949;','&#950;','&#951;','&#952;','&#953;','&#954;','&#955;','&#956;','&#957;','&#958;','&#959;','&#960;','&#961;','&#962;','&#963;','&#964;','&#965;','&#966;','&#967;','&#968;','&#969;','&#977;','&#978;','&#982;','&#8226;','&#8230;','&#8242;','&#8243;','&#8254;','&#8260;','&#8472;','&#8465;','&#8476;','&#8482;','&#8501;','&#8592;','&#8593;','&#8594;','&#8595;','&#8596;','&#8629;','&#8656;','&#8657;','&#8658;','&#8659;','&#8660;','&#8704;','&#8706;','&#8707;','&#8709;','&#8711;','&#8712;','&#8713;','&#8715;','&#8719;','&#8721;','&#8722;','&#8727;','&#8730;','&#8733;','&#8734;','&#8736;','&#8743;','&#8744;','&#8745;','&#8746;','&#8747;','&#8756;','&#8764;','&#8773;','&#8776;','&#8800;','&#8801;','&#8804;','&#8805;','&#8834;','&#8835;','&#8836;','&#8838;','&#8839;','&#8853;','&#8855;','&#8869;','&#8901;','&#8968;','&#8969;','&#8970;','&#8971;','&#9001;','&#9002;','&#9674;','&#9824;','&#9827;','&#9829;','&#9830;');
		return this.swapArrayVals(s,arr1,arr2);
	},	

	// Convert Numerical entities into HTML entities
	NumericalToHTML : function(s){
		var arr1 = new Array('&#160;','&#161;','&#162;','&#163;','&#164;','&#165;','&#166;','&#167;','&#168;','&#169;','&#170;','&#171;','&#172;','&#173;','&#174;','&#175;','&#176;','&#177;','&#178;','&#179;','&#180;','&#181;','&#182;','&#183;','&#184;','&#185;','&#186;','&#187;','&#188;','&#189;','&#190;','&#191;','&#192;','&#193;','&#194;','&#195;','&#196;','&#197;','&#198;','&#199;','&#200;','&#201;','&#202;','&#203;','&#204;','&#205;','&#206;','&#207;','&#208;','&#209;','&#210;','&#211;','&#212;','&#213;','&#214;','&#215;','&#216;','&#217;','&#218;','&#219;','&#220;','&#221;','&#222;','&#223;','&#224;','&#225;','&#226;','&#227;','&#228;','&#229;','&#230;','&#231;','&#232;','&#233;','&#234;','&#235;','&#236;','&#237;','&#238;','&#239;','&#240;','&#241;','&#242;','&#243;','&#244;','&#245;','&#246;','&#247;','&#248;','&#249;','&#250;','&#251;','&#252;','&#253;','&#254;','&#255;','&#34;','&#38;','&#60;','&#62;','&#338;','&#339;','&#352;','&#353;','&#376;','&#710;','&#732;','&#8194;','&#8195;','&#8201;','&#8204;','&#8205;','&#8206;','&#8207;','&#8211;','&#8212;','&#8216;','&#8217;','&#8218;','&#8220;','&#8221;','&#8222;','&#8224;','&#8225;','&#8240;','&#8249;','&#8250;','&#8364;','&#402;','&#913;','&#914;','&#915;','&#916;','&#917;','&#918;','&#919;','&#920;','&#921;','&#922;','&#923;','&#924;','&#925;','&#926;','&#927;','&#928;','&#929;','&#931;','&#932;','&#933;','&#934;','&#935;','&#936;','&#937;','&#945;','&#946;','&#947;','&#948;','&#949;','&#950;','&#951;','&#952;','&#953;','&#954;','&#955;','&#956;','&#957;','&#958;','&#959;','&#960;','&#961;','&#962;','&#963;','&#964;','&#965;','&#966;','&#967;','&#968;','&#969;','&#977;','&#978;','&#982;','&#8226;','&#8230;','&#8242;','&#8243;','&#8254;','&#8260;','&#8472;','&#8465;','&#8476;','&#8482;','&#8501;','&#8592;','&#8593;','&#8594;','&#8595;','&#8596;','&#8629;','&#8656;','&#8657;','&#8658;','&#8659;','&#8660;','&#8704;','&#8706;','&#8707;','&#8709;','&#8711;','&#8712;','&#8713;','&#8715;','&#8719;','&#8721;','&#8722;','&#8727;','&#8730;','&#8733;','&#8734;','&#8736;','&#8743;','&#8744;','&#8745;','&#8746;','&#8747;','&#8756;','&#8764;','&#8773;','&#8776;','&#8800;','&#8801;','&#8804;','&#8805;','&#8834;','&#8835;','&#8836;','&#8838;','&#8839;','&#8853;','&#8855;','&#8869;','&#8901;','&#8968;','&#8969;','&#8970;','&#8971;','&#9001;','&#9002;','&#9674;','&#9824;','&#9827;','&#9829;','&#9830;');
		var arr2 = new Array('&nbsp;','&iexcl;','&cent;','&pound;','&curren;','&yen;','&brvbar;','&sect;','&uml;','&copy;','&ordf;','&laquo;','&not;','&shy;','&reg;','&macr;','&deg;','&plusmn;','&sup2;','&sup3;','&acute;','&micro;','&para;','&middot;','&cedil;','&sup1;','&ordm;','&raquo;','&frac14;','&frac12;','&frac34;','&iquest;','&agrave;','&aacute;','&acirc;','&atilde;','&Auml;','&aring;','&aelig;','&ccedil;','&egrave;','&eacute;','&ecirc;','&euml;','&igrave;','&iacute;','&icirc;','&iuml;','&eth;','&ntilde;','&ograve;','&oacute;','&ocirc;','&otilde;','&Ouml;','&times;','&oslash;','&ugrave;','&uacute;','&ucirc;','&Uuml;','&yacute;','&thorn;','&szlig;','&agrave;','&aacute;','&acirc;','&atilde;','&auml;','&aring;','&aelig;','&ccedil;','&egrave;','&eacute;','&ecirc;','&euml;','&igrave;','&iacute;','&icirc;','&iuml;','&eth;','&ntilde;','&ograve;','&oacute;','&ocirc;','&otilde;','&ouml;','&divide;','&oslash;','&ugrave;','&uacute;','&ucirc;','&uuml;','&yacute;','&thorn;','&yuml;','&quot;','&amp;','&lt;','&gt;','&oelig;','&oelig;','&scaron;','&scaron;','&yuml;','&circ;','&tilde;','&ensp;','&emsp;','&thinsp;','&zwnj;','&zwj;','&lrm;','&rlm;','&ndash;','&mdash;','&lsquo;','&rsquo;','&sbquo;','&ldquo;','&rdquo;','&bdquo;','&dagger;','&dagger;','&permil;','&lsaquo;','&rsaquo;','&euro;','&fnof;','&alpha;','&beta;','&gamma;','&delta;','&epsilon;','&zeta;','&eta;','&theta;','&iota;','&kappa;','&lambda;','&mu;','&nu;','&xi;','&omicron;','&pi;','&rho;','&sigma;','&tau;','&upsilon;','&phi;','&chi;','&psi;','&omega;','&alpha;','&beta;','&gamma;','&delta;','&epsilon;','&zeta;','&eta;','&theta;','&iota;','&kappa;','&lambda;','&mu;','&nu;','&xi;','&omicron;','&pi;','&rho;','&sigmaf;','&sigma;','&tau;','&upsilon;','&phi;','&chi;','&psi;','&omega;','&thetasym;','&upsih;','&piv;','&bull;','&hellip;','&prime;','&prime;','&oline;','&frasl;','&weierp;','&image;','&real;','&trade;','&alefsym;','&larr;','&uarr;','&rarr;','&darr;','&harr;','&crarr;','&larr;','&uarr;','&rarr;','&darr;','&harr;','&forall;','&part;','&exist;','&empty;','&nabla;','&isin;','&notin;','&ni;','&prod;','&sum;','&minus;','&lowast;','&radic;','&prop;','&infin;','&ang;','&and;','&or;','&cap;','&cup;','&int;','&there4;','&sim;','&cong;','&asymp;','&ne;','&equiv;','&le;','&ge;','&sub;','&sup;','&nsub;','&sube;','&supe;','&oplus;','&otimes;','&perp;','&sdot;','&lceil;','&rceil;','&lfloor;','&rfloor;','&lang;','&rang;','&loz;','&spades;','&clubs;','&hearts;','&diams;');
		return this.swapArrayVals(s,arr1,arr2);
	},


	// Numerically encodes all unicode characters
	numEncode : function(s){
		
		if(this.isEmpty(s)) return "";

		var e = "";
		for (var i = 0; i < s.length; i++)
		{
			var c = s.charAt(i);
			if (c < " " || c > "~")
			{
				c = "&#" + c.charCodeAt() + ";";
			}
			e += c;
		}
		return e;
	},
	
	// HTML Decode numerical and HTML entities back to original values
	htmlDecode : function(s){

		var c,m,d = s;
		
		if(this.isEmpty(d)) return "";

		// convert HTML entites back to numerical entites first
		d = this.HTML2Numerical(d);
		
		// look for numerical entities &#34;
		arr=d.match(/&#[0-9]{1,5};/g);
		
		// if no matches found in string then skip
		if(arr!=null){
			for(var x=0;x<arr.length;x++){
				m = arr[x];
				c = m.substring(2,m.length-1); //get numeric part which is refernce to unicode character
				// if its a valid number we can decode
				if(c >= -32768 && c <= 65535){
					// decode every single match within string
					d = d.replace(m, String.fromCharCode(c));
				}else{
					d = d.replace(m, ""); //invalid so replace with nada
				}
			}			
		}

		return d;
	},		

	// encode an input string into either numerical or HTML entities
	htmlEncode : function(s,dbl){
			
		if(this.isEmpty(s)) return "";

		// do we allow double encoding? E.g will &amp; be turned into &amp;amp;
		dbl = dbl | false; //default to prevent double encoding
		
		// if allowing double encoding we do ampersands first
		if(dbl){
			if(this.EncodeType=="numerical"){
				s = s.replace(/&/g, "&#38;");
			}else{
				s = s.replace(/&/g, "&amp;");
			}
		}

		// convert the xss chars to numerical entities ' " < >
		s = this.XSSEncode(s,false);
		
		if(this.EncodeType=="numerical" || !dbl){
			// Now call function that will convert any HTML entities to numerical codes
			s = this.HTML2Numerical(s);
		}

		// Now encode all chars above 127 e.g unicode
		s = this.numEncode(s);

		// now we know anything that needs to be encoded has been converted to numerical entities we
		// can encode any ampersands & that are not part of encoded entities
		// to handle the fact that I need to do a negative check and handle multiple ampersands &&&
		// I am going to use a placeholder

		// if we don't want double encoded entities we ignore the & in existing entities
		if(!dbl){
			s = s.replace(/&#/g,"##AMPHASH##");
		
			if(this.EncodeType=="numerical"){
				s = s.replace(/&/g, "&#38;");
			}else{
				s = s.replace(/&/g, "&amp;");
			}

			s = s.replace(/##AMPHASH##/g,"&#");
		}
		
		// replace any malformed entities
		s = s.replace(/&#\d*([^\d;]|$)/g, "$1");

		if(!dbl){
			// safety check to correct any double encoded &amp;
			s = this.correctEncoding(s);
		}

		// now do we need to convert our numerical encoded string into entities
		if(this.EncodeType=="entity"){
			s = this.NumericalToHTML(s);
		}

		return s;					
	},

	// Encodes the basic 4 characters used to malform HTML in XSS hacks
	XSSEncode : function(s,en){
		if(!this.isEmpty(s)){
			en = en || true;
			// do we convert to numerical or html entity?
			if(en){
				s = s.replace(/\'/g,"&#39;"); //no HTML equivalent as &apos is not cross browser supported
				s = s.replace(/\"/g,"&quot;");
				s = s.replace(/</g,"&lt;");
				s = s.replace(/>/g,"&gt;");
			}else{
				s = s.replace(/\'/g,"&#39;"); //no HTML equivalent as &apos is not cross browser supported
				s = s.replace(/\"/g,"&#34;");
				s = s.replace(/</g,"&#60;");
				s = s.replace(/>/g,"&#62;");
			}
			return s;
		}else{
			return "";
		}
	},

	// returns true if a string contains html or numerical encoded entities
	hasEncoded : function(s){
		if(/&#[0-9]{1,5};/g.test(s)){
			return true;
		}else if(/&[A-Z]{2,6};/gi.test(s)){
			return true;
		}else{
			return false;
		}
	},

	// will remove any unicode characters
	stripUnicode : function(s){
		return s.replace(/[^\x20-\x7E]/g,"");
		
	},

	// corrects any double encoded &amp; entities e.g &amp;amp;
	correctEncoding : function(s){
		return s.replace(/(&amp;)(amp;)+/,"$1");
	},


	// Function to loop through an array swaping each item with the value from another array e.g swap HTML entities with Numericals
	swapArrayVals : function(s,arr1,arr2){
		if(this.isEmpty(s)) return "";
		var re;
		if(arr1 && arr2){
			//ShowDebug("in swapArrayVals arr1.length = " + arr1.length + " arr2.length = " + arr2.length)
			// array lengths must match
			if(arr1.length == arr2.length){
				for(var x=0,i=arr1.length;x<i;x++){
					re = new RegExp(arr1[x], 'g');
					s = s.replace(re,arr2[x]); //swap arr1 item with matching item from arr2	
				}
			}
		}
		return s;
	},

	inArray : function( item, arr ) {
		for ( var i = 0, x = arr.length; i < x; i++ ){
			if ( arr[i] === item ){
				return i;
			}
		}
		return -1;
	}

}

function dropDownChange(elementId, formName){
	var element = document.getElementById(elementId);
	if(element.selectedIndex != 0){
		var form = document.forms[formName];
    	if (form) {
    		form.submit();
    	}
    }
}

/* TODO - phase out all use of this and delete - for now just consolidating JavaScript files
url-loading object.  To use, create an onload and optional onerror
function and pass them to the constructor.  These functions will essentially
be late-bound to the instance by using the this.onload.call(this) syntax, so within
your provided functions you can access the XMLHttpRequest variable by 
referencing "this.req."
*/

/* namespacing object */
var net=new Object();

net.READY_STATE_UNINITIALIZED=0;
net.READY_STATE_LOADING=1;
net.READY_STATE_LOADED=2;
net.READY_STATE_INTERACTIVE=3;
net.READY_STATE_COMPLETE=4;


/*--- content loader object for cross-browser requests ---*/
net.ContentLoader=function(url,onload,onerror,method,params,contentType){
  this.req=null;
  this.onload=onload;
  this.onerror=(onerror) ? onerror : this.defaultError;
  this.loadXMLDoc(url,method,params,contentType);
}

net.ContentLoader.prototype.loadXMLDoc=function(url,method,params,contentType){
  if (!method){
    method="GET";
  }
  if (!contentType && method=="POST"){
    contentType='application/x-www-form-urlencoded';
  }
  if (window.XMLHttpRequest){
    this.req=new XMLHttpRequest();
  } else if (window.ActiveXObject){
    this.req=new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (this.req){
    try{
      var loader=this;
      this.req.onreadystatechange=function(){
        net.ContentLoader.onReadyState.call(loader);
      }
      this.req.open(method,url,true);
      if (contentType){
        this.req.setRequestHeader('Content-Type', contentType);
      }
      this.req.send(params);
    }catch (err){
      this.onerror.call(this);
    }
  }
}


net.ContentLoader.onReadyState=function(){
  var req=this.req;
  var ready=req.readyState;
  if (ready==net.READY_STATE_COMPLETE){
	var httpStatus=req.status;
    if (httpStatus==200 || httpStatus==0){
      this.onload.call(this);
    }else{
      this.onerror.call(this);
    }
  }
}

net.ContentLoader.prototype.defaultError=function(){
  // no default error behavior
}


