//basic funtions

var isIE = (document.all) ? true : false;
function $()		{ var elements = new Array(); for (var i = 0; i < arguments.length; i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element); } return elements; };
function $C(elType) { return document.createElement(elType);};
function $C2(loc, elType) {return loc.createElement(elType);};
function $T(text)	{ return document.createTextNode(text);};
function $I(div,innerHTML) {if (!$(div)){return;};$(div).innerHTML = innerHTML};
function addEvent(elm, evType, fn, useCapture) { if (elm.addEventListener) { elm.addEventListener(evType, fn, useCapture); return true; } else if (elm.attachEvent) { var r = elm.attachEvent('on' + evType, fn); return r; } else { elm['on' + evType] = fn; } };
function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { oldonload(); func(); } } };
function inArray (array,value) {var i; for (i=0; i < array.length; i++) { if (array[i] == value) { return i; } } return -1; };
function arrayAvg(array){
	var sum=0;
	for(var i=0,sum=0;i<array.length;sum+=array[i++]);
	return sum/array.length;
}
//Array.prototype.avg = function(){
//	for(var i=0,sum=0;i<this.length;sum+=this[i++]);
//	return sum/this.length;
//}

function keyExists(key,obj){
	var exists = 0;
	for(var k in obj){if (k == key){exists=1;break;}}
	return exists;
}

function showDiv(divId) {if (!$(divId)){return;};$(divId).style.display = "block";};
function hideDiv(divId) {if (!$(divId)){return;};$(divId).style.display = "none";};
//cookie
function getCookie( name ) {var start = document.cookie.indexOf( name + "=" ); var len = start + name.length + 1; if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) { return null; } if ( start == -1 ) return null; var end = document.cookie.indexOf( ';', len ); if ( end == -1 ) end = document.cookie.length; return unescape( document.cookie.substring( len, end ) ); };
function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date(); today.setTime( today.getTime() ); if ( expires ) { expires = expires * 1000 * 60 * 60 * 24; } var expires_date = new Date( today.getTime() + (expires) ); document.cookie = name+'='+escape( value ) + ( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + ( ( path ) ? ';path=' + path : '' ) + ( ( domain ) ? ';domain=' + domain : '' ) + ( ( secure ) ? ';secure' : '' ); }; 
function deleteCookie( name, path, domain ) {	if ( getCookie( name ) ) document.cookie = name + '=' +	( ( path ) ? ';path=' + path : '') + 	( ( domain ) ? ';domain=' + domain : '' ) +	';expires=Thu, 01-Jan-1970 00:00:01 GMT';};
function openNewWin(url,w,h) {
	var l = Math.max((screen.width - w ) /2,0);
	var t = Math.max((screen.height - h ) /2,0);
	var newwin = window.open(url,"newwin","top="+t+",left="+l+",height="+h+",width="+w+",status=yes,toolbar=yes,menubar=yes,location=yes,resizable=yes,scrollbars=yes");
	newwin.focus();
};
function loadFile(fileName, toDiv)	{
	var p = ((typeof toDiv) == 'object') ? toDiv : $(toDiv);
	if (!p){return;}
	p.innerHTML = MyAjax.get(fileName);
};

function unLoadPage(toDiv)		{
	if (!($(toDiv) && $(toDiv).hasChildNodes())){return;}	var children = $(toDiv).childNodes; for(i=children.length -1; i>=0;i--) { if (children[i].nodeType == 1){ $(toDiv).removeChild(children[i]); } } };

function loadPage(pageName,toDiv, paras){
	if (!$(toDiv)){	return; }
	unLoadPage(toDiv);
	if (!(paras["noLoading"] && paras["noLoading"] == 1)){
		var loading = $C('div');
		loading.setAttribute("id", "loadingloadedIframe" + toDiv);
		var loadingAnimation = $C('img');
		loadingAnimation.setAttribute('src','/tpl/rsft/images/loading.gif');
		loading.appendChild(loadingAnimation);
		loading.style.width="80px";
		loading.style.textAlign="center";
		$(toDiv).appendChild(loading);
	}
	
	var iframe = (isIE) ? $C('<iframe onload="removeLoadingCaption(this,'+paras["height"]+')"></iframe>') : $C('iframe');
	if (!isIE) {iframe.setAttribute("onload", "removeLoadingCaption(this,"+paras["height"]+")")};

	iframe.setAttribute("src", pageName);
	iframe.setAttribute("id", "loadedIframe" + toDiv);
	iframe.setAttribute("scrolling", (paras["scroll"] == 1)?"auto":"no");
//	iframe.setAttribute("scrolling", "auto");
	iframe.setAttribute("width", paras["width"]||0);
	iframe.setAttribute("height", paras["height"]||0);
	iframe.setAttribute("frameBorder", "0");
	$(toDiv).appendChild(iframe);
//	if (!(paras["nofocus"] ==1) && iframe.focus()){iframe.focus();}
};

function removeLoadingCaption(obj,h) {
	var p = obj.parentNode;
	if (!p) return;
	var d = p.getElementsByTagName("div");
	if (d[0] && d[0].id == "loading"+obj.id) {
		p.removeChild(d[0]);
	}
	if (obj.contentDocument &&  obj.contentDocument.body.offsetHeight) {
			obj.height = h || (obj.contentDocument.body.offsetHeight + 23);    
	} else if (obj.Document && obj.Document.body.scrollHeight) {
			obj.height = h || obj.Document.body.scrollHeight;
	}
};

function adjustIframeView(toDiv,s) {
	var p = ((typeof toDiv) == 'object') ? toDiv : $(toDiv); 
	if (!p){return;}
	var d = p.getElementsByTagName("iframe");
	var oD = ((s ==1 ) ? top.window.oDialog2: top.window.oDialog);

	if (d[0]) {
		var obj = d[0];
		if (obj.contentDocument &&  obj.contentDocument.body.offsetHeight) {
			// W3C DOM syntax for NN 6
			if (obj.id.indexOf('cxt') >-1){
				var dispHeight = (obj.contentDocument.body.offsetHeight<=450)?obj.contentDocument.body.offsetHeight:450;
				obj.height = dispHeight+23;
				oD.hide();
				oD.resizeTo(Math.max(492,obj.contentDocument.body.offsetWidth),dispHeight+28);
				oD.show();
			}else{
				obj.height = obj.contentDocument.body.offsetHeight + 10;    
			}
		} else if (obj.Document && obj.Document.body.scrollHeight) {
			// IE DOM syntax
			if (obj.id.indexOf('cxt') >-1){
				var dispHeight = (obj.Document.body.scrollHeight<=450)?obj.Document.body.scrollHeight:450;
				obj.height = dispHeight;
				oD.hide();
				oD.resizeTo(Math.max(obj.Document.body.scrollWidth,489),dispHeight+2);
				oD.show();
			}else{
				obj.height = obj.Document.body.scrollHeight;
			}
		}
	}
};

//simple ajax class
if (! this.MyAjax) MyAjax = function () {};
MyAjax.get =	function(url, callback,loadingCallback) { return (new MyAjax()).get( { 'url': url, 'onComplete': callback,'onLoading': loadingCallback} ); };
MyAjax.post = function(url, data, callback,loadingCallback) { return (new MyAjax()).post( { 'url': url, 'data': data, 'onComplete': callback,'onLoading': loadingCallback } ); };
proto = MyAjax.prototype;
proto.die = function(e) { throw(e) };
proto.get = function(params) {this._init_object(params); this.request.open('GET', this.url, Boolean(this.onComplete || this.onLoading)); return this._send(); };
proto.post = function(params) { this._init_object(params); this.request.open('POST', this.url, Boolean(this.onComplete|| this.onLoading)); this.request.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' ); return this._send(); };
proto._init_object = function(params) {for (key in params) { if (! key.match(/^url|data|onComplete|onLoading$/)) throw("Invalid Ajax parameter: " + key); this[key] = params[key]; } if (! this.url) throw("'url' required for Ajax get/post method"); if (this.request) throw("Don't yet support multiple requests on the same Ajax object"); this.request = new XMLHttpRequest(); if (! this.request) return this.die("Your browser doesn't do Ajax"); if (this.request.readyState != 0) return this.die("Ajax readyState should be 0"); return this; };

proto._send = function() { 
	var self = this; 
	if (this.onComplete || this.onLoading) { 
		this.request.onreadystatechange = function() { self._check_asynchronous(); }; 
	} 
	this.request.send(this.data); 
	return Boolean(this.onComplete) ? this : this._check_synchronous(); 
};

proto._check_status = function() { if (this.request.status != 200) { return this.die( 'Ajax request for "' + this.url + '" failed with status: ' + this.request.status ); } };

proto._check_synchronous = function() { this._check_status(); return this.request.responseText; };
proto._check_asynchronous = function() { 
	if (this.request.readyState == 1){ if ((typeof this.onLoading) == "function") {this.onLoading();}; return;}else {if (this.request.readyState != 4) return; }
	this._check_status(); 
	this.onComplete(this.request.responseText); 
}; 
if (window.ActiveXObject && !window.XMLHttpRequest) { window.XMLHttpRequest = function() { var name = (navigator.userAgent.toLowerCase().indexOf('msie 5') != -1) ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP'; return new ActiveXObject(name); } };

//form check
var digits = "0123456789";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyz";
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var whitespace = " \t\n\r";
var decimalPointDelimiter = ".";
var phoneNumberDelimiters = "()- ";
var validUSPhoneChars = digits + phoneNumberDelimiters;
var validWorldPhoneChars = digits + phoneNumberDelimiters + "+";
var digitsInUSPhoneNumber = 10;
var ZIPCodeDelimiters = "-";
var ZIPCodeDelimeter = "-"
var validZIPCodeChars = digits + ZIPCodeDelimiters;
var digitsInZIPCode1 = 5;
var digitsInZIPCode2 = 9;
var creditCardDelimiters = " ";
var defaultEmptyOK = false;

function isEmpty(s)					{ return ((s == null) || (s.length == 0))};
function isWhitespace (s)			{ var i; if (isEmpty(s)) return true; for (i = 0; i < s.length; i++) {   var c = s.charAt(i); if (whitespace.indexOf(c) == -1) return false; } return true; };
function stripCharsInBag (s, bag)	{ var i; var returnString = ""; for (i = 0; i < s.length; i++) {   var c = s.charAt(i); if (bag.indexOf(c) == -1) returnString += c; } return returnString; };
function stripCharsNotInBag(s, bag) { var i; var returnString = ""; for (i = 0; i < s.length; i++) {   var c = s.charAt(i); if (bag.indexOf(c) != -1) returnString += c; } return returnString; };
function stripWhitespace (s)		{ return stripCharsInBag (s, whitespace)};
function isLetter (c)				{ return ( ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")) )};
function isDigit (c)				{ return ((c >= "0") && (c <= "9"))};
function isLetterOrDigit (c)		{ return (isLetter(c) || isDigit(c))};
function isInteger (s)				{ var i; if (isEmpty(s)) if (isInteger.arguments.length == 1) return defaultEmptyOK; else return (isInteger.arguments[1] == true); for (i = 0; i < s.length; i++) {   var c = s.charAt(i); if (!isDigit(c)) return false; } return true; };
function isSignedInteger (s)		{ if (isEmpty(s))  if (isSignedInteger.arguments.length == 1) return defaultEmptyOK;        else return (isSignedInteger.arguments[1] == true);     else {         var startPos = 0;         var secondArg = defaultEmptyOK;         if (isSignedInteger.arguments.length > 1)             secondArg = isSignedInteger.arguments[1];         if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )            startPos = 1;            return (isInteger(s.substring(startPos, s.length), secondArg))  } };
function isPositiveInteger (s)		{ var secondArg = defaultEmptyOK; if (isPositiveInteger.arguments.length > 1) secondArg = isPositiveInteger.arguments[1]; return (isSignedInteger(s, secondArg) && ( (isEmpty(s) && secondArg)  || (parseInt (s) > 0) ) ); };
function isFloat (s)				{ var i; var seenDecimalPoint = false; if (isEmpty(s)) if (isFloat.arguments.length == 1) return defaultEmptyOK; else return (isFloat.arguments[1] == true); if (s == decimalPointDelimiter) return false; for (i = 0; i < s.length; i++) {   var c = s.charAt(i); if ( ((c == decimalPointDelimiter) || (c == ",")) && !seenDecimalPoint) seenDecimalPoint = true; else if(!isDigit(c)) return false; else seenDecimalPoint=false; } return true; };
function isAlphabetic (s)			{ var i; if (isEmpty(s)) if (isAlphabetic.arguments.length == 1) return defaultEmptyOK; else return (isAlphabetic.arguments[1] == true); for (i = 0; i < s.length; i++) {   var c = s.charAt(i); if (!isLetter(c)) return false; } return true; };
function isAlphanumeric (s)			{ var i; if (isEmpty(s)) if (isAlphanumeric.arguments.length == 1) return defaultEmptyOK; else return (isAlphanumeric.arguments[1] == true); for (i = 0; i < s.length; i++) {   var c = s.charAt(i); if (! (isLetter(c) || isDigit(c) ) ) return false; } return true; };
function isAlphanumeric2 (s)			{ var i; if (isEmpty(s)) if (isAlphanumeric.arguments.length == 1) return defaultEmptyOK; else return (isAlphanumeric.arguments[1] == true); for (i = 0; i < s.length; i++) {   var c = s.charAt(i); if (! (isLetter(c) || isDigit(c) || c =='-' ) ) return false; } return true; };
function isUSPhoneNumber (s)		{ if (isEmpty(s)) if (isUSPhoneNumber.arguments.length == 1) return defaultEmptyOK; else return (isUSPhoneNumber.arguments[1] == true); return (isInteger(s) && s.length == digitsInUSPhoneNumber) };
function isInternationalPhoneNumber(s)	{ if (isEmpty(s)) if (isInternationalPhoneNumber.arguments.length == 1) return defaultEmptyOK; else return (isInternationalPhoneNumber.arguments[1] == true); return (isPositiveInteger(s)) };
function isZIPCode (s)				{ if (isEmpty(s)) if (isZIPCode.arguments.length == 1) return defaultEmptyOK; else return (isZIPCode.arguments[1] == true); return (isInteger(s) && ((s.length == digitsInZIPCode1) || (s.length == digitsInZIPCode2))) };
function isCanadaCode(s)			{ var str = s; re = /(\w\d\w\s*\d\w\d)/i; found = str.match(re); return(found); };
function isEmail (s)				{ if (isEmpty(s)) if (isEmail.arguments.length == 1) return defaultEmptyOK; else return (isEmail.arguments[1] == true); if (isWhitespace(s)) return false; var i = 1; var sLength = s.length; while ((i < sLength) && (s.charAt(i) != "@")) { i++ } if ((i >= sLength) || (s.charAt(i) != "@")) return false; else i += 2; while ((i < sLength) && (s.charAt(i) != ".")) { i++ } if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false; else return true; };
function isCreditCard(st)			{ if (st.length > 19) return (false); sum = 0; mul = 1; l = st.length; for (i = 0; i < l; i++) { digit = st.substring(l-i-1,l-i); tproduct = parseInt(digit ,10)*mul; if (tproduct >= 10) sum += (tproduct % 10) + 1; else sum += tproduct; if (mul == 1) mul++; else mul--; } if ((sum % 10) == 0) return (true); else return (false); };
function isVisa(cc)					{ if (((cc.length == 16) || (cc.length == 13)) && (cc.substring(0,1) == 4)) return isCreditCard(cc); return false; };
function isMasterCard(cc)			{ var firstdig = cc.substring(0,1); var seconddig = cc.substring(1,2); if ((cc.length == 16) && (firstdig == 5) && ((seconddig >= 1) && (seconddig <= 5))) return isCreditCard(cc); return false; };
function isAmericanExpress(cc)		{ var firstdig = cc.substring(0,1); var seconddig = cc.substring(1,2); if ((cc.length == 15) && (firstdig == 3) && ((seconddig == 4) || (seconddig == 7))) return isCreditCard(cc); return false; };
function jumpNext(obj,n,objnext)	{ if(obj.value.length == n) { $(objnext).focus(); } };

function CommaFormatted(amount)
{
	if (typeof(amount) != 'string'){amount = String(amount);}
	var delimiter = ","; 
	if (amount.indexOf('.') <0)	{amount += ".00";}
	var a = amount.split('.',2);
	var d = a[1];
	if (d.length == 1){ d += "0";};
	var i = parseInt(a[0]);
	if(isNaN(i)) { return ''; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	var n = new String(i);
	var a = [];
	while(n.length > 3)
	{
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) { a.unshift(n); }
	n = a.join(delimiter);
	if(d.length < 1) { amount = n; }
	else { amount = n + '.' + d; }
	amount = "$" + minus + amount;
	return amount;
};



var WIN_POP_WIDTH = 700;
var WIN_POP_HEIGHT = 431;
var WIN_POP_PAGE_WIDTH = 676;
if(isIE)
	var WIN_POP_PAGE_HEIGHT = 360;
else 
	var WIN_POP_PAGE_HEIGHT = 950;

var alertMessage = function(){
	var div;
	var timeoutid;
	var closeMessage = function(){if ($('table_message_info'))
		$('table_message_info').style.display = "none";};

	var init = function(){
			div = $C('div');
			div.setAttribute("id", "alertMessage")
			YAHOO.util.Dom.addClass(div,"alert");	
			document.body.appendChild(div);
			div = $('alertMessage');
			div.innerHTML = MyAjax.get("/php/alertmessage.ajax");
	};

	return {
		show:function(para,obj){
			if (!div){init();};
			$('table_message_info').style.display = "block";
			if (para["title"]) $('alertCaption').innerHTML = para["title"];
			$('alertContent').innerHTML = para["msg"];
			div.style.top = (Math.floor(YAHOO.util.Dom.getY(obj)-div.offsetHeight+obj.offsetHeight/2+(para["adjustY"]||0)))+"px";
			div.style.left =(Math.floor(YAHOO.util.Dom.getX(obj)+(para["adjustX"]||0)))+"px";
//			div.style.top = "0px";
//			div.style.left = "0px";
			div.style.zIndex = 2; // 2/5/2007 Luke Hwang
//			alert('zindex of alert message is '+div.style.zIndex);
//			if (para["noAutoClose"] ==1) return;
			if (timeoutid){clearTimeout(timeoutid);timeoutid = null;};
			timeoutid = setTimeout(closeMessage,3000);
		},
		close:function(){
			closeMessage();	
			if (timeoutid){clearTimeout(timeoutid);timeoutid = null;};
		
		}
	}
}();

function checkDefaultValue(obj,mode) {
	switch(mode) {
		case 'f' : // onFocus
			if(obj.value == $(obj.id+"Value").innerHTML) {
				obj.value = '';
				obj.style.color = '#000000';

			}
		break;
		case 'b' : // onBlur
			if(obj.value == '') {
				obj.value = $(obj.id+"Value").innerHTML;
				obj.style.color = '#999999';
			}
		break;
	}
}

function getDomain(url){
	var domain="";array = url.split("/");
	if (array.length>0){for (var i=0;i<array.length;i++){if (array[i].indexOf(".")>-1){domain = array[i]; break;}}}
	if (domain == ""){domain = "www.realtysoft.com";}
	return domain;
}

function Is ()
{   // convert all characters to lowercase to simplify testing
    var agt=navigator.userAgent.toLowerCase();

    // *** BROWSER VERSION ***
    // Note: On IE5, these return 4, so use is.ie5up to detect IE5.

    this.major = parseInt(navigator.appVersion);
    this.minor = parseFloat(navigator.appVersion);

    // Note: Opera and WebTV spoof Navigator.  We do strict client detection.
    // If you want to allow spoofing, take out the tests for opera and webtv.
    this.nav  = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
                && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
                && (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1));
    this.nav2 = (this.nav && (this.major == 2));
    this.nav3 = (this.nav && (this.major == 3));
    this.nav4 = (this.nav && (this.major == 4));
    this.nav4up = (this.nav && (this.major >= 4));
    this.navonly      = (this.nav && ((agt.indexOf(";nav") != -1) ||
                          (agt.indexOf("; nav") != -1)) );
    this.nav6 = (this.nav && (this.major == 5));
    this.nav6up = (this.nav && (this.major >= 5));
    this.gecko = (agt.indexOf('gecko') != -1);


    this.ie     = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
    this.ie3    = (this.ie && (this.major < 4));
    this.ie4    = (this.ie && (this.major == 4) && (agt.indexOf("msie 4")!=-1) );
    this.ie4up  = (this.ie  && (this.major >= 4));
    this.ie5    = (this.ie && (this.major == 4) && (agt.indexOf("msie 5.0")!=-1) );
    this.ie5_5  = (this.ie && (this.major == 4) && (agt.indexOf("msie 5.5") !=-1));
    this.ie5up  = (this.ie  && !this.ie3 && !this.ie4);
    this.ie5_5up =(this.ie && !this.ie3 && !this.ie4 && !this.ie5);
    this.ie6    = (this.ie && (this.major == 4) && (agt.indexOf("msie 6.")!=-1) );
    this.ie6up  = (this.ie  && !this.ie3 && !this.ie4 && !this.ie5 && !this.ie5_5);

    // KNOWN BUG: On AOL4, returns false if IE3 is embedded browser
    // or if this is the first browser window opened.  Thus the
    // variables is.aol, is.aol3, and is.aol4 aren't 100% reliable.
    this.aol   = (agt.indexOf("aol") != -1);
    this.aol3  = (this.aol && this.ie3);
    this.aol4  = (this.aol && this.ie4);
    this.aol5  = (agt.indexOf("aol 5") != -1);
    this.aol6  = (agt.indexOf("aol 6") != -1);

    this.opera = (agt.indexOf("opera") != -1);
    this.opera2 = (agt.indexOf("opera 2") != -1 || agt.indexOf("opera/2") != -1);
    this.opera3 = (agt.indexOf("opera 3") != -1 || agt.indexOf("opera/3") != -1);
    this.opera4 = (agt.indexOf("opera 4") != -1 || agt.indexOf("opera/4") != -1);
    this.opera5 = (agt.indexOf("opera 5") != -1 || agt.indexOf("opera/5") != -1);
    this.opera5up = (this.opera && !this.opera2 && !this.opera3 && !this.opera4);

    this.webtv = (agt.indexOf("webtv") != -1); 

    this.TVNavigator = ((agt.indexOf("navio") != -1) || (agt.indexOf("navio_aoltv") != -1)); 
    this.AOLTV = this.TVNavigator;

    this.hotjava = (agt.indexOf("hotjava") != -1);
    this.hotjava3 = (this.hotjava && (this.major == 3));
    this.hotjava3up = (this.hotjava && (this.major >= 3));

    // *** JAVASCRIPT VERSION CHECK ***
    if (this.nav2 || this.ie3) this.js = 1.0;
    else if (this.nav3) this.js = 1.1;
    else if (this.opera5up) this.js = 1.3;
    else if (this.opera) this.js = 1.1;
    else if ((this.nav4 && (this.minor <= 4.05)) || this.ie4) this.js = 1.2;
    else if ((this.nav4 && (this.minor > 4.05)) || this.ie5) this.js = 1.3;
    else if (this.hotjava3up) this.js = 1.4;
    else if (this.nav6 || this.gecko) this.js = 1.5;
    // NOTE: In the future, update this code when newer versions of JS
    // are released. For now, we try to provide some upward compatibility
    // so that future versions of Nav and IE will show they are at
    // *least* JS 1.x capable. Always check for JS version compatibility
    // with > or >=.
    else if (this.nav6up) this.js = 1.5;
    // note ie5up on mac is 1.4
    else if (this.ie5up) this.js = 1.3

    // HACK: no idea for other browsers; always check for JS version with > or >=
    else this.js = 0.0;

    // *** PLATFORM ***
//    this.win   = ( (agt.indexOf("win")!=-1) || (agt.indexOf("16bit")!=-1) );
//    // NOTE: On Opera 3.0, the userAgent string includes "Windows 95/NT4" on all
//    //        Win32, so you can't distinguish between Win95 and WinNT.
//    this.win95 = ((agt.indexOf("win95")!=-1) || (agt.indexOf("windows 95")!=-1));
//
//    // is this a 16 bit compiled version?
//    this.win16 = ((agt.indexOf("win16")!=-1) || 
//               (agt.indexOf("16bit")!=-1) || (agt.indexOf("windows 3.1")!=-1) || 
//               (agt.indexOf("windows 16-bit")!=-1) );  
//
//    this.win31 = ((agt.indexOf("windows 3.1")!=-1) || (agt.indexOf("win16")!=-1) ||
//                    (agt.indexOf("windows 16-bit")!=-1));
//
//    // NOTE: Reliable detection of Win98 may not be possible. It appears that:
//    //       - On Nav 4.x and before you'll get plain "Windows" in userAgent.
//    //       - On Mercury client, the 32-bit version will return "Win98", but
//    //         the 16-bit version running on Win98 will still return "Win95".
//    this.win98 = ((agt.indexOf("win98")!=-1) || (agt.indexOf("windows 98")!=-1));
//    this.winnt = ((agt.indexOf("winnt")!=-1) || (agt.indexOf("windows nt")!=-1));
//    this.win32 = (this.win95 || this.winnt || this.win98 || 
//                    ((this.major >= 4) && (navigator.platform == "Win32")) ||
//                    (agt.indexOf("win32")!=-1) || (agt.indexOf("32bit")!=-1));
//
//    this.winme = ((agt.indexOf("win 9x 4.90")!=-1));
//    this.win2k = ((agt.indexOf("windows nt 5.0")!=-1));
//
//    this.os2   = ((agt.indexOf("os/2")!=-1) || 
//                    (navigator.appVersion.indexOf("OS/2")!=-1) ||   
//                    (agt.indexOf("ibm-webexplorer")!=-1));
//
//    this.mac    = (agt.indexOf("mac")!=-1);
//    // hack ie5 js version for mac
//    if (this.mac && this.ie5up) this.js = 1.4;
//    this.mac68k = (this.mac && ((agt.indexOf("68k")!=-1) || 
//                               (agt.indexOf("68000")!=-1)));
//    this.macppc = (this.mac && ((agt.indexOf("ppc")!=-1) || 
//                                (agt.indexOf("powerpc")!=-1)));
//
//    this.sun   = (agt.indexOf("sunos")!=-1);
//    this.sun4  = (agt.indexOf("sunos 4")!=-1);
//    this.sun5  = (agt.indexOf("sunos 5")!=-1);
//    this.suni86= (this.sun && (agt.indexOf("i86")!=-1));
//    this.irix  = (agt.indexOf("irix") !=-1);    // SGI
//    this.irix5 = (agt.indexOf("irix 5") !=-1);
//    this.irix6 = ((agt.indexOf("irix 6") !=-1) || (agt.indexOf("irix6") !=-1));
//    this.hpux  = (agt.indexOf("hp-ux")!=-1);
//    this.hpux9 = (this.hpux && (agt.indexOf("09.")!=-1));
//    this.hpux10= (this.hpux && (agt.indexOf("10.")!=-1));
//    this.aix   = (agt.indexOf("aix") !=-1);      // IBM
//    this.aix1  = (agt.indexOf("aix 1") !=-1);    
//    this.aix2  = (agt.indexOf("aix 2") !=-1);    
//    this.aix3  = (agt.indexOf("aix 3") !=-1);    
//    this.aix4  = (agt.indexOf("aix 4") !=-1);    
//    this.linux = (agt.indexOf("inux")!=-1);
//    this.sco   = (agt.indexOf("sco")!=-1) || (agt.indexOf("unix_sv")!=-1);
//    this.unixware = (agt.indexOf("unix_system_v")!=-1); 
//    this.mpras    = (agt.indexOf("ncr")!=-1); 
//    this.reliant  = (agt.indexOf("reliantunix")!=-1);
//    this.dec   = ((agt.indexOf("dec")!=-1) || (agt.indexOf("osf1")!=-1) || 
//                  (agt.indexOf("dec_alpha")!=-1) || (agt.indexOf("alphaserver")!=-1) || 
//                  (agt.indexOf("ultrix")!=-1) || (agt.indexOf("alphastation")!=-1)); 
//    this.sinix = (agt.indexOf("sinix")!=-1);
//    this.freebsd = (agt.indexOf("freebsd")!=-1);
//    this.bsd = (agt.indexOf("bsd")!=-1);
//    this.unix  = ((agt.indexOf("x11")!=-1) || this.sun || this.irix || this.hpux || 
//                 this.sco ||this.unixware || this.mpras || this.reliant || 
//                 this.dec || this.sinix || this.aix || this.linux || this.bsd || this.freebsd);
//
//    this.vms   = ((agt.indexOf("vax")!=-1) || (agt.indexOf("openvms")!=-1));
}

var browser_detect;
var isIE3Mac = false;
// this section is designed specifically for IE3 for the Mac

if ((navigator.appVersion.indexOf("Mac")!=-1) && (navigator.userAgent.indexOf("MSIE")!=-1) && 
(parseInt(navigator.appVersion)==3))
       isIE3Mac = true;
else   browser_detect = new Is(); 

var browser_type;
if ( browser_detect.ie){browser_type =1;}
else if (browser_detect.nav) {browser_type =2;}
else if (browser_detect.opera){browser_type =3;}
else {browser_type =4;}

function copyToClipboard(s)
{
	if( window.clipboardData && clipboardData.setData )
	{
		clipboardData.setData("Text", s);
	}
	else
	{
		// You have to sign the code to enable this or allow the action in about:config by changing
		user_pref("signed.applets.codebase_principal_support", true);
		netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

		var clip = Components.classes['@mozilla.org/widget/clipboard;[[[[1]]]]'].createInstance(Components.interfaces.nsIClipboard);
		if (!clip) return;

		// create a transferable
		var trans = Components.classes['@mozilla.org/widget/transferable;[[[[1]]]]'].createInstance(Components.interfaces.nsITransferable);
		if (!trans) return;

		// specify the data we wish to handle. Plaintext in this case.
		trans.addDataFlavor('text/unicode');

		// To get the data from the transferable we need two new objects
		var str = new Object();
		var len = new Object();

		var str = Components.classes["@mozilla.org/supports-string;[[[[1]]]]"].createInstance(Components.interfaces.nsISupportsString);

		var copytext=meintext;

		str.data=copytext;

		trans.setTransferData("text/unicode",str,copytext.length*[[[[2]]]]);

		var clipid=Components.interfaces.nsIClipboard;

		if (!clip) return false;

		clip.setData(trans,null,clipid.kGlobalClipboard);	   
	}
}

var fieldToggleHelpText = function(){
	return {on:function(fld){if (isEmpty(fld.helptext)){fld.helptext = fld.value;};	if (fld.value == fld.helptext )	{fld.value='';YAHOO.util.Dom.replaceClass(fld,"fld2","fld1")}},
	out:function(fld){if (isEmpty(fld.value))	{fld.value=fld.helptext;YAHOO.util.Dom.replaceClass(fld,"fld1","fld2");}}}
}();

var serializeForm = function(flds){
	var res=[];
	for(var i=0;i<flds.length;i++)	{res.push(flds[i]+"="+escape($(flds[i]).value)); }
	return res.join("&");
}

function ltrim(value) {var re = /\s*((\S+\s*)*)/;return value.replace(re, "$1");}
// Removes ending whitespaces
function rtrim( value ){var re = /((\s*\S+)*)\s*/;return value.replace(re, "$1");}
// Removes leading and ending whitespaces
function trim(value) {return ltrim(rtrim(value));}

function customized_form_submit(){
	if(top.window.$('openPreviewBox')) {
	    var doc = top.window.$("openPreviewBox").Document || top.window.$("openPreviewBox").contentDocument;
		var obj = doc.customized_form;
		var tmp = obj.id.split("_");
		var form_type = tmp[1];
		var user = tmp[2];
		if (obj.FirstName){
			var fld = obj.FirstName; 
			if (isEmpty(fld.value)){alert("Please input your first name.");fld.focus();return;}
		}
		if (obj.LastName){fld = obj.LastName; if (isEmpty(fld.value)){alert("Please input your last name.");fld.focus();return;}}
		if (obj.Email){
			fld = obj.Email; if (isEmpty(fld.value)){alert("Please input your email.");fld.focus();return;}
			if (!isEmail(fld.value)){alert("Invalid email address.");fld.focus();return;}
		}
		if(obj.Turing){
		fld = obj.Turing; if (isEmpty(fld.value)){alert("Please type the code shown below.");fld.focus();return;}}
	}else{
		var doc = window.document;
		var obj = document.forms["customized_form"];
		if (!obj.id){obj=document.forms[0];}
		var tmp = obj.id.split("_");
		var form_type = tmp[1];
		var user = tmp[2];
		if (isEmpty(user)){return;}
		if (obj.FirstName){var fld = obj.FirstName; 
		if (isEmpty(fld.value)){alertMessage.show({msg:"Please input your first name."},fld);fld.focus();return;}}
		if (obj.LastName){fld = obj.LastName; if (isEmpty(fld.value)){alertMessage.show({msg:"Please input your last name."},fld);fld.focus();return;}}
		if (obj.Email){fld = obj.Email; if (isEmpty(fld.value)){alertMessage.show({msg:"Please input your email."},fld);fld.focus();return;}
		if (!isEmail(fld.value)){alertMessage.show({msg:"Invalid email address."},fld);fld.focus();return;}}
		if(obj.Turing){
		fld = obj.Turing; if (isEmpty(fld.value)){alertMessage.show({msg:"Please type the code shown below."},fld);fld.focus();return;}}
	}

	var site = window.location.href;
	var url = "<a href='"+escape(window.location.href)+"'>"+escape(window.location.href)+"</a>";
	if (site.indexOf('?')>-1){site = site.substr(0,site.indexOf('?'));}
	var flds = ["ac=1","user="+user,"site="+site,"form_type="+form_type];	var radios = {};for(var i=0;i<obj.length;i++){
			fld = obj[i];switch(fld.type){
			case "text":case "textarea":case "hidden":case "select-one":flds.push(fld.name+"="+escape(fld.value));break;
			case "radio":var n = fld.name;var f = 0;for(var r in radios){if (r == n) f = 1;}if (f ==0) radios[n] = "";if (fld.checked == true) radios[n] = fld.value;break;
			case "checkbox":if (fld.checked == true)	flds.push(fld.name+"="+fld.value);break;
			case "select-multiple":	var opts = fld.options;	var s = [];	for (var j =0;j<opts.length;j++){if (opts[j].selected == true) s.push(opts[j].value);}	if (s.length >0) flds.push(fld.name+"="+s.join(","));break;
			default:break;
		}
	}
	flds.push("PageURL="+url);
	for(var r in radios){if (radios[r] == "") continue;	flds.push(r+"="+radios[r]);}
	doc.getElementById('user_customized_form_submit').innerHTML = "<img src='/tpl/rsft/images/loading.gif'>";	var onComplete = function(res) {
		if(res==0) {
			if(top.window.$('openPreviewBox')) 
			alert("Incorrect text.");
			else 
			alertMessage.show({msg:"Incorrect text."},obj.Turing);
			obj.Turing.focus();
			doc.getElementById('user_customized_form_submit').innerHTML = "<INPUT onclick=top.window.customized_form_submit() type=button value=Submit>";
		}
		else
			doc.getElementById('user_customized_form_submit').innerHTML = "<span style='color:red;font-family: Verdana;font-size:12px;'>Email was sent successfully.</span>";
		};
	MyAjax.post("/php/controlpanel/mywebsites/user_customized_form.ajax",flds.join("&"), onComplete);	
}

	function refreshImg() {
		if(top.window.$('openPreviewBox')) {
			var obj = top.window.$("openPreviewBox").Document || top.window.$("openPreviewBox").contentDocument;
			obj.getElementById('captcha').src = obj.getElementById('captcha').src+'?'+(new Date()).getMilliseconds();
		}
		else
		document.getElementById('captcha').src = document.getElementById('captcha').src+'?'+(new Date()).getMilliseconds();
	}
	
	function unserializePHPString(input){
		return PHP_Unserialize(Base64.decode(input));
	}

    function PHP_Unserialize(input) {
        var result = PHP_Unserialize_(input);
        return result[0];
    }

    function PHP_Unserialize_(input)

    {
        var length = 0;
        
        switch (input.charAt(0)) {
            /**
            * Array
            */

            case 'a':

                length = PHP_Unserialize_GetLength(input);
                input  = input.substr(String(length).length + 4);

                var arr   = new Array();
                var key   = null;
                var value = null;

                for (var i=0; i<length; ++i) {
                    key   = PHP_Unserialize_(input);
                    input = key[1];

                    value = PHP_Unserialize_(input);
                    input = value[1];

                    arr[key[0]] = value[0];
                }

                input = input.substr(1);
                return [arr, input];

                break;
            
            /**
            * Objects
            */
            case 'O':

                length = PHP_Unserialize_GetLength(input);
                var classname = String(input.substr(String(length).length + 4, length));
                
                input  = input.substr(String(length).length + 6 + length);
                var numProperties = Number(input.substring(0, input.indexOf(':')))
                input = input.substr(String(numProperties).length + 2);

                var obj      = new Object();
                var property = null;
                var value    = null;

                for (var i=0; i<numProperties; ++i) {
                    key   = PHP_Unserialize_(input);
                    input = key[1];
                    
                    // Handle private/protected
                    key[0] = key[0].replace(new RegExp('^\x00' + classname + '\x00'), '');
                    key[0] = key[0].replace(new RegExp('^\x00\\*\x00'), '');

                    value = PHP_Unserialize_(input);
                    input = value[1];

                    obj[key[0]] = value[0];
                }

                input = input.substr(1);
                return [obj, input];
                break;


            /**
            * Strings
            */

            case 's':
                length = PHP_Unserialize_GetLength(input);
                return [String(input.substr(String(length).length + 4, length)), input.substr(String(length).length + 6 + length)];

                break;


            /**
            * Integers and doubles
            */

            case 'i':
            case 'd':
                var num = Number(input.substring(2, input.indexOf(';')));
                return [num, input.substr(String(num).length + 3)];

                break;
            
            /**
            * Booleans
            */
            case 'b':
                var bool = (input.substr(2, 1) == 1);
                return [bool, input.substr(4)];
                break;
            
            /**
            * Null
            */
            case 'N':
                return [null, input.substr(2)];
                break;

            /**
            * Unsupported
            */
            case 'o':
            case 'r':
            case 'C':
            case 'R':
            case 'U':
                alert('Error: Unsupported PHP data type found!');

            /**
            * Error
            */
            default:
                return [null, null];
                break;

        }

    }
    

    /**
    * Returns length of strings/arrays etc
    *
    * @param string input Input to parse
    */

    function PHP_Unserialize_GetLength(input)

    {

        input = input.substring(2);

        var length = Number(input.substr(0, input.indexOf(':')));

        return length;

    }

	var Base64 = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }
}

function parseUrl(href) {
//    var e=/^((http|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+\.[^#?\s]+)(#[\w\-]+)?$/;
    var e=/^((http|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+)(#[\w\-]+)?$/;

    if (href.match(e)) {
        return  {url: RegExp['$&'],
                protocol: RegExp.$2,
                host:RegExp.$3,
                path:RegExp.$4,
                file:RegExp.$6,
                hash:RegExp.$7};
    }
    else {
        return  {url:"", protocol:"",host:"",path:"",file:"",hash:""};
    }
}

function myescape(str){
//	str = str.replace(/¡/,'&iexcl;');
//	str = str.replace(/¿/,'&iquest;');
//	str = str.replace(/á/,'&aacute;');
//	str = str.replace(/Á/,'&Aacute;');
//	str = str.replace(/é/,'&eacute;');
//	str = str.replace(/É/,'&Eacute;');
//	str = str.replace(/í/,'&iacute;');
//	str = str.replace(/Í/,'&Iacute;');
//	str = str.replace(/ñ/,'&ntilde;');
//	str = str.replace(/Ñ/,'&Ntilde;');
//	str = str.replace(/ó/,'&oacute;');
//	str = str.replace(/Ó/,'&Oacute;');
//	str = str.replace(/ú/,'&uacute;');
//	str = str.replace(/Ú/,'&Uacute;');
//	str = str.replace(/ü/,'&uuml;');
//	str = str.replace(/Ü/,'&Uuml;');
//	str = str.replace(/à/,'&agrave;');
//	str = str.replace(/ò/,'&ograve;');
//	str = str.replace(/ç/,'&Ccedil;');
//	str = str.replace(/ô/,'&Ocirc;');
//	str = str.replace(/â/,'&acirc;');
//	str = str.replace(/ï/,'&iuml;');
//	str = str.replace(/ê/,'&ecirc;');
//	str = str.replace(/œ/,'&oelig;');
//	str = str.replace(/è/,'&egrave;');
	return str;
}