if (top !== self) {
	alert('The URL ' + self.location.href + ' cannot be viewed inside a frame.  You will be redirected.');
	top.location.href = self.location.href;
}

var $Y = YAHOO, //
$D = YAHOO.util.Dom, //
$C = $D.getElementsByClassName, //
$E = YAHOO.util.Event, //
$CONN = YAHOO.util.Connect, //
$ = YAHOO.util.Dom.get, //
$LANG = YAHOO.lang, //
$COOKIE = YAHOO.util.Cookie, //
$J = YAHOO.lang.JSON, //
$W = YAHOO.widget, //
$L = YAHOO.log, //
o1 = {}, //
LampcmsException = function(message, exceptionName) {
	this.message = message;
	this.name = exceptionName || "LampcmsException";
};

oSL = {};
oSL.Regform = function() {
};

/**
 * This member handles the success response must determine what the result is
 * for: can be for doc or tpl or can be a text with css we should test the
 * returned text which should always be a JSONobject
 */
oAjaxObject = {
	handleSuccess : function(o) {

		var eLastDiv, json, sDoc, sTpl, errDiv, strMessage = '', //
		eLogin = $("loginHead"), // was nbar
		strContentType = $LANG.trim(o.getResponseHeader["Content-Type"]);
		// alert('ContentType: ' + strContentType);
		switch (strContentType) {
		case 'text/json; charset=UTF-8':
		case 'text/javascript; charset=UTF-8':
			// alert('42 got something that looks like js');
			try {
				json = $J.parse(o.responseText);
				// alert(json);
			} catch (e) {
				alert("Invalid json data in responceText " + $LANG.dump(e) + " strContentType " + strContentType + "\noRespnose: " + $LANG.dump(o.responseText));
			}

			switch (true) {
			case json.hasOwnProperty('error'):
				oSL.setLoginError(json.error);
				break;

			case json.hasOwnProperty('exception'):
				if (json.hasOwnProperty('errHeader')) {
					strMessage += '<u>' + json.errHeader + '</u><br>';
				}

				errDiv = document.createElement('div');
				errDiv.id = 'exc';
				var mainDiv = $C('yui-b', 'div')[0];
				$D.insertBefore(errDiv, mainDiv.firstChild);

				errDiv.innerHTML = strMessage + json.exception;
				if ($('go')) {
					$('go').disabled = false;
				}
				break;

			case json.hasOwnProperty('redirect'):
				window.location.assign(json.redirect);
				break;

			case json.hasOwnProperty('navbar'):
				oSL.fMakeNavBar(json);
				break;

			case json.hasOwnProperty('message'):
				eLogin.innerHTML = json.message;
				// oSL.renderGfcButton();
				oSL.fColorChange(eLogin, '#00FF00', '#FFFFFF');
				break;

			case json.hasOwnProperty('quickreg'):
				eLastDiv = document.createElement('div');
				eLastDiv.innerHTML = json.quickreg;
				document.body.appendChild(eLastDiv);
				oSL.modal.hide();
				oSL.Regform.getInstance().show();
				break;

			}

		}
	},
	handleFailure : function(o) {
		alert($LANG.dump(o));
	}
}; //
oSL = {
	toString : function() {
		return 'object oSL';
	},
	getQuickRegForm : function() {
		if (oSL.Regform && oSL.Regform.hasDialog()) {
			oSL.Regform.getInstance().show();
		} else {
			/**
			 * &ajaxid=1&tplflag=1
			 */
			if (oSL.modal) {
				oSL.modal.show();
			}
			$CONN.asyncRequest("GET", "/index.php?a=getregform", oSL.oCallback);
		}

	},
	hideRegForm : function() {
		$COOKIE.set("dnd", "1", {
			path : "/"
		});
		if (oSL.Regform) {
			oSL.Regform.getInstance().hide();
			window.location.reload();
		}

		return false;
	},
	initFBSignup : function() {
		fbPerms = this.getMeta('fbperms');
		if (!fbPerms) {
			fbPerms = '';
		}
		if (FB) {
			FB.login(function(response) {
				if (response.session) {
					$L('FB Signed in');
					if (response.perms) {
						// user is logged in and granted some
						// permissions.
						// perms is a comma separated list of granted
						// permissions
						// alert('Granted perms: ' + response.perms);
						window.top.location.reload(true);
					} else {
						// user is logged in, but did not grant any
						// permissions
					}
				} else {
					// user is not logged in
				}
			}, {
				perms : fbPerms
			});
		}

		return;
	},
	/**
	 * Render Google friendConnect button Called on page load but also after the
	 * login form is rendered after it is received via ajax In that case we will
	 * have just the login-fcbutton in the html and need to render the actual
	 * button again
	 */
	renderGfcButton : function() {
		var myDiv = $('login-fcbutton');
		if (myDiv && google && google.friendconnect) {
			google.friendconnect.renderSignInButton({
				"id" : "loginHead",
				"text" : "Sign in with Google Friend Connect",
				"style" : "long"
			});
		}
	}, //
	/**
	 * Get value of specific meta tag This assumes that meta tag name is unique -
	 * only appears once in the meta tags If meta tag not found then returns
	 * false
	 * 
	 * @param string
	 *            sMetaName name of meta tag of which we need the value
	 * 
	 * @param book
	 *            bAsElement if passed and is true then return the actual
	 *            DOMElement for that meta tag instead of just the value
	 */
	getMeta : function(sMetaName, bAsElement) {
		$L('182 looking for meta tag ' + sMetaName);
		var el, i, aMeta = document.getElementsByTagName('meta');
		$L('43 ' + $LANG.dump(aMeta) + ' total metas: ' + aMeta.length);
		if (!aMeta) {
			$L('45 no meta tags in document', 'error');
			return false;
		}

		for (i = 0; i < aMeta.length; i += 1) {
			if (aMeta[i].name && (aMeta[i].name == sMetaName) && aMeta[i].content) {
				if (bAsElement) {
					var el = aMeta[i];
					$L('213 meta tag element ' + el);

					return el;
				}

				return aMeta[i].content;
			}
		}

		return false;
	},

	/**
	 * Get value of 'mytoken' meta tag which serves as a security token for form
	 * validation.
	 */
	getToken : function() {
		$L('166 getToken');
		var token = this.getMeta('version_id');
		return token;
	},
	/**
	 * Test to determine if page is being viewed by a logged in user a logged in
	 * user has the session-tid meta tag set to value of twitter userid
	 */
	isLoggedIn : function() {
		$L('64 this is: ' + this); // oTQ

		var ret, uid = this.getMeta('session-uid');
		$L('148 uid: ' + uid);

		ret = (uid && (uid !== '') && (uid !== '0'));

		$L('66 ret: ' + ret);

		return ret;
	},
	/**
	 * Set the value of meta session-tid
	 */
	setMetaTag : function(name, val) {
		var eMeta = this.getMeta(name, true);
		if (eMeta) {
			eMeta.content = val;
		}

		$L('249 meta set, now: ' + this.getMeta(name));
	},
	/**
	 * Set (update) the value of meta name="mytoken" meta tag with the new value
	 */
	setToken : function(val) {
		var el = this.getMeta('version_id', true);
		el.setAttribute('content', val);
	},
	/**
	 * Callback to login the user this is called from the oAuth popup window OR
	 * can be called from Ajax callback if AsyncRequest was used to check login
	 * status
	 * 
	 * This method will set meta session-tid to user_id, will replace the
	 * welcome block with the one from the object and IF not in someone else's
	 * page, then will set style, background, etc to styles from o.profile
	 */
	processLogin : function(o) {
		$L('116 this is: ' + this); // object oTQ when called from popup
		$L('118 o: ' + $LANG.dump(o), 'warn');
		var sCurLocation, eWelcome = $('loginHead'), eException = $('excsl');

		this.Twitter.cancelIntervals();
		this.Twitter.cancelAsyncCalls();
		/**
		 * Just reload the window This is the easiest way to re-render the page
		 * with the login block updated as well as other elements. for example,
		 * a comments form may now appear as 'available' because now the user is
		 * logged in
		 * 
		 * This may not be as fancy as just re-render the login block with color
		 * change, but it takes care of other elements on the page that may be
		 * different for logged in and not logged in users.
		 * 
		 * Lastly, if we have a post-signup action like asking user for email
		 * address after user signup with Twitter or FB or GFC, this would make
		 * it very easy to just show that special 'last-step' page that asks for
		 * the email address.
		 */
		window.location.reload();
		/**
		 * If the page has div id 'exc' with class 'login' this means there was
		 * an error with text Must Login In this case we must reload the current
		 * location
		 * 
		 */

		if (eException && 'login' === eException.className) {
			window.location.reload();
		}

		if (o.welcome && eWelcome) {
			eWelcome.innerHTML = o.welcome;
			setTimeout("oSL.fColorChange('loginHead', '#FF0000', '#00FF00')", 500);
		}

	}, //
	/**
	 * Get timezone offset based on user clock
	 * 
	 * @return number of secord from UTC time can be negative
	 */
	getTZO : function() {
		var tzo, nd = new Date();
		tzo = (0 - (nd.getTimezoneOffset() * 60));

		return tzo;

	},
	/**
	 * Get value of timezone offset and set it as tzo cookie This way a value
	 * can be read on the server This is useful during the registration as a way
	 * to pass the value of timezone offset but without using the POST and
	 * without adding it to GET
	 * 
	 * The cookie is set as SESSION cookie with site-wide path (accessible from
	 * any page but must be in the same domain)
	 */
	setTZOCookie : function() {
		$L('109 this is: ' + this);
		var tzo = this.getTZO();
		$L('117 tzo: ' + tzo);
		$COOKIE.set("tzo", tzo, {
			path : "/"
		});
	},
	oCallback : {
		success : oAjaxObject.handleSuccess,
		failure : oAjaxObject.handleFailure,
		scope : oAjaxObject
	},//
	fAddIcon : function(s, b) {
		var el = (typeof (s) === 'string') ? $(s) : s;

		if (!this.eLoader) {
			this.eLoader = document.createElement("img");
			this.eLoader.src = '/images/ajax-loader.gif';
			this.eLoader.id = "loadericon";
		}

		if (this.eLoader) {
			if (b && b === true) {
				el.innerHTML = '';
			}

			el.appendChild(this.eLoader);

		}
	}, //
	fRemoveIcon : function() {
		if (this.eLoader && this.eLoader.parentNode) {
			$L('include.js 118 eLoader parent: ' + this.eLoader.parentNode + ' id: ' + this.eLoader.parentNode.id);
			this.eLoader.parentNode.removeChild(this.eLoader);
		}
	},
	/**
	 * Compares 2 HTML form Dom nodes
	 * 
	 * @param {Object}
	 *            oNewForm a new HTML form, usually the one use tries to submit
	 * @param {Object}
	 *            oOldForm an old HTML form, usually the one with default values
	 *            (valued when page first loaded)
	 * @return boolean true if at least one of new form's values is different
	 *         from the same one in old form or if the new form has a form
	 *         element that is not present in the old form.
	 */
	fCompareForms : function(oNewForm, oOldForm) {
		$L($CONN.setForm(oNewForm));
		$L($CONN.setForm(oOldForm));

		if ($CONN.setForm(oNewForm) === $CONN.setForm(oOldForm)) {
			return true;
		}

		return false;
	},//
	/**
	 * Use color animation to change background-color of an element slowly from
	 * one color to a new color, then back to sFromColor, then set
	 * backgroundColor to its original (the one before this function) This can
	 * be used to display changes or to attract attention to some message inside
	 * a div like to a new error message.
	 * 
	 * @param {Object}
	 *            el
	 * @param {Object}
	 *            sToColor
	 */
	fColorChange : function(el, sFromColor, sToColor) {
		$L('starting fColorChange for ' + el);
		var myChange, curBg, myChangeBack, //              
		element = (typeof el === 'string') ? $(el) : el, //
		sToColor = (sToColor && typeof sToColor === 'string') ? sToColor : '#FF0000', //
		sFromColor = (sFromColor && typeof sFromColor === 'string') ? sFromColor : '#FFFFFF';

		$L('element is: ' + element);

		if (element) {

			curBg = $D.getStyle(element, 'background-color');
			$D.setStyle(element, 'background-color', sFromColor);
			myChange = new YAHOO.util.ColorAnim(element, {
				backgroundColor : {
					to : sToColor
				}
			});

			/**
			 * Change the background back to what if was before the animation
			 * started
			 */
			myChangeBack = function() {
				element.style.backgroundColor = curBg;
			};

			myChange.onComplete.subscribe(myChangeBack);
			myChange.animate();

		}
	}, //
	fMakeMeNav : function(id, o) {
		/**
		 * What has to be done here? IF called from normal web page, not via
		 * ajax: we have html with div id loginHead inside we have table class
		 * usernav, with 2nd td that has our 'menav' div which we need to
		 * convert to drop-down menu
		 * 
		 * So... We just do it.
		 * 
		 * IF called via ajax then second arg o is passed Then we already have a
		 * login form inside the loginHead div and we need to destroy the
		 * contents of it and replace it with the contents of ....???
		 * 
		 * 
		 * Possible cases: 1. Response to Logout action: we receive back the
		 * html of Login form. as a value of o.message In this case the content
		 * of loginHead div is replaced with content of o.message which is the
		 * login form and everything just works.
		 * 
		 * 
		 * 2. After we get the json in response to ajax based login that json
		 * contains html of the 'usernav' table, so we stick the 'username'
		 * table inside the loginHead div, replacing the previously displayed
		 * login form, then this method is called in order to render the menu
		 * and possibly take care of 'merged' sub-menu
		 * 
		 * 
		 * 3. Responce to switch account posting
		 * 
		 */
		$L('178 id is: ' + id);
		// return true; // for testing without navbar just return here
		var oMerged = null;
		if (o && o.merged) {
			oMerged = o.merged;
			$L('193 merged: ' + oMerged);
		}

		$L('101 starting fMakeMeNav ' + id, "warn");
		// var id = 'menav';
		var elMenav = $(id);
		$L('104 elMenav ' + elMenav, "warn");
		if (elMenav == 'undefined' || null === elMenav) {
			return true;
		}

		/**
		 * Here we do some fancy things by cloning node, then removing contents
		 * or cloned node's parent with an empty string effectively wiping out
		 * the cloned node, then appending the new clone as a child of the
		 * 'nbar' element.
		 * 
		 * This is interesting, but what if the parent of cloned node was
		 * already the 'nbar' div? Then we just did something complicated that
		 * resulted in the same exact html and dom structure as before: we
		 * cloned node, destroyed the cloned node, then appended the clone to
		 * the same parent...
		 * 
		 * Why do we need to do this anyway?
		 * 
		 * This can be understood IF the id passed to this method is different
		 * from 'nbar', for example if the HTML of the navigation menu was in
		 * some other div on the page, like maybe it was on the left menu and
		 * what we doing is moving it to the nvar (to the top)
		 * 
		 * This whole thing is probably no longed necessary it was originally
		 * designed to extract contents of some div that was somewhere in the
		 * side bar like new items... then move the whole thing to the top
		 * inside the navbar, so we needed to clode the node and then remove the
		 * original from the side bar.
		 * 
		 * We don't put the nav links in the side bar anymore.
		 */

		var elParent = elMenav.parentNode;
		$L('218 elParent.id: ' + elParent.id);
		// commening out the old stuff on Dec 3 09
		/*
		 * if (elParent.id !== 'loginHead') { var elClone =
		 * elMenav.cloneNode(true); elParent.innerHTML = ''; var nRoot =
		 * $('nbar'); nRoot.appendChild(elClone); } else { $L('Dude! this does
		 * not make sense', "warn"); elClone = elMenav; }
		 */

		elClone = elMenav;
		$L('192 elMenav ' + elMenav, "warn");
		/**
		 * o1 is just a new namespace o1.oMenu is our top menu bar
		 */
		o1.oMenu = new $W.MenuBar(elClone, {
			position : "static",
			autosubmenudisplay : true,
			hidedelay : 550,
			iframe : false,
			lazyload : false
		});

		$L('201 elMenav ' + elMenav, "warn");
		o1.oMenu.render();

		$L('204 elMenav ' + elMenav, "warn");
		this.makeSwitchMenu(oMerged);
		$L('206 elMenav ' + elMenav, "warn");

	}, //
	fMakeNavBar : function(o) {
		/**
		 * This method is called ONLY when we receive ajax back from login
		 * action and it contains navbar
		 */
		var sHTML = o.navbar, //
		eNavBar = $('loginHead');
		if (!eNavBar) {
			return false;
		}
		/**
		 * If we already have the o1.oMenu (a top nav bar object) then use its'
		 * destroy() method to completely destroy it, including all sub-menus
		 * and remove all event listeners
		 */
		if (o1 && o1.oMenu) {
			o1.oMenu.destroy(); // this also destroys menav div element
			// itself
		}
		/**
		 * Here we stick the html (value of o.navbar) as the innerHTML of the
		 * DOM element with id 'nvar', which is our top div on the page. So
		 * whatever html it may have had before, it will now have the totally
		 * new html
		 */
		eNavBar.innerHTML = sHTML;
		$L('google: ' + google + ' fc: ' + google.friendconnect);

		// this.fMakeMeNav('menav', o); // here o is json object and has
		// navbar
		// and
		// also may have 'merged' object
	}, //
	fGetErrTd : function() {
		this.eErrTd = $("titleWarning");
		return this.eErrTd;
	}, //
	setLoginError : function(message) {

		if (this.eErrTd) {
			$D.setStyle(oSL.eErrTd, "backgroundColor", "#FFFFCC");
			this.eErrTd.innerHTML = message;
			this.fColorChange(oSL.eErrTd, '#FFFFFF', '#FF0000');
			$('go').disabled = false;
		} else {
			alert(message);
		}
	}, //
	validateLogin : function(oFrm) {
		if (oFrm && oFrm.elements) {
			for ( var element in oFrm.elements) {
				var fElement = oFrm.elements[element];
				if (fElement && fElement.name) {
					var elName = oFrm.elements[element].name;
					if (elName === 'login' || elName === 'pwd') {
						if ('' === fElement.value) {
							fElement.style.borderWidth = "2px";
							fElement.style.borderStyle = "solid";
							fElement.style.borderColor = "#FF0000";
							if (oFrm.elements['r']) {
								this.setLoginError(oFrm.elements['r'].value);
							}
							return false;
						} else {
							fElement.style.borderWidth = '';
							fElement.style.borderStyle = '';
							fElement.style.borderColor = '';
						}
					}
				}
			}
		}

		return true;
	},//   
	fLogin : function(o) {
		var target = $E.getTarget(o), //
		errTd = oSL.fGetErrTd(), //
		formObject = $("frmLogin"), //
		formObjectTest = $("sampleForm"), //
		oTweet, //
		fbAppId, //
		fbcookie, //
		fbPerms;

		/**
		 * This one is for a style editor form on that page the form name is
		 * 'sampleForm' and we just want to disable the submittion of that form
		 * when button is clicked
		 */
		if (target && target.type && formObjectTest && target.type.toLowerCase() === 'submit') {
			$E.stopEvent(o);
			return;
		}

		if (target && target.type && formObject && target.type.toLowerCase() === 'submit') {

			$E.stopEvent(o);

			if (oSL.validateLogin(formObject)) {
				target.disabled = true;
				if (errTd) {
					oSL.fAddIcon(errTd);
				}
				$CONN.setForm(formObject);
				// This example facilitates a POST transaction.
				// An HTTP GET can be used as well.
				$CONN.asyncRequest("POST", "/index.php", oSL.oCallback, "ajaxid=1");
			}
		} else {
			if (target.nodeName && target.nodeName.toLowerCase() === 'a' && target.href.toLowerCase().match('logout')) {
				$L('376 clicked on Logout');
				$E.stopEvent(o);
				fbAppId = this.getMeta('fbappid');
				if (!FB) {
					alert('no FB');
				} else {
					// alert('logging out of FB');
					/**
					 * Calling FB.logout causes to be logged out of facebook,
					 * but that's not really what we want. We only want to
					 * logout of our site But unless we logout of FB the FB
					 * Javascript will automatically log the user back in (set
					 * the fbs_ cookie) without user having to click on login
					 * button This would make it impossible to actually logout
					 */
					FB.logout();
					// alert('Logged out of FB');
					if (fbAppId) {
						fbcookie = "fbs_" + fbAppId;
						$L('going to remove fbs cookie ' + fbcookie);
						$COOKIE.remove(fbcookie, {
							path : "/"
						});

						oSL.fAddIcon(target);

						/*
						 * resetFormState() is very important because if the
						 * page has had another setForm() ran for a different
						 * form, the $CONN will still be configured with a
						 * different form object
						 */
						$CONN.resetFormState();
						$CONN.asyncRequest("GET", "/index.php?a=logout&ajaxid=1", oSL.oCallback);
					}

				}
				target.href = '#';

				return;
			}
		}

		if (target.id === 'gfcset' && google && google.friendconnect) {
			$L('451 clicked on GFC Settings');
			$E.stopEvent(o);
			google.friendconnect.requestSettings();

			return;
		}

		if (target.id === 'gfcinvite' && google && google.friendconnect) {
			$L('451 clicked on Invite');
			$E.stopEvent(o);
			google.friendconnect.requestInvite();

			return;
		}

		if (target.id === 'twinvite') {
			$L('636 clicked on ' + target.id);
			oTweet = oSL.tweet.getInstance();
			$L('637 oTweet: ' + oTweet);
			oTweet.show();

			return;
		}

		if (target.id === 'fbinvite') {
			$L('635 clicked on Facebook Invite');
			$E.stopEvent(o);
			if (!FB) {
				$L('No FB object', 'error');
			}

			var siteTitle = oSL.getMeta('site_title');
			var siteUrl = oSL.getMeta('site_url');
			var siteDescription = target.title;
			var caption = oSL.getMeta('site_description');
			$L('target title: ' + siteDescription);
			FB.ui({
				method : 'stream.publish',
				message : 'I joined this site with Facebook Connect button. You should check it out too',
				attachment : {
					name : siteTitle,
					caption : caption,
					description : siteDescription,
					href : siteUrl
				},
				action_links : [ {
					text : siteTitle,
					href : siteUrl
				} ],
				user_message_prompt : 'Invite your Facebook Friends to join this site'
			}, function(response) {
				if (response && response.post_id) {
					$L('Post was published to Wall');
				} else {
					$L('Post was not published to Walll', 'warn');
				}
			});

			return;
		}

		if ('twsignin' === target.id) {
			$L('477 clicked on Twitter button this is: ' + this); // HTML
			// div
			this.Twitter.startDance();
			return;
		}

		if ('gfcsignin' === target.id) {
			$L('738 clicked on GFC button this is: ' + this); // HTML
			// div
			if (!google || !google.friendconnect) {
				$L('No google or google.friendconnect', 'error');
				return;
			}
			google.friendconnect.requestSignIn();
			return;
		}

		if ('fbsignup' === target.id) {
			this.initFBSignup();
		}

		if ('signup' == target.className) {
			$L('730 clicked on signup');
			$E.stopEvent(o);
			this.getQuickRegForm();
		}

	},//
	fMakeLangSelect : function(id) {
		/*
		 * 
		 * var oSplitButton1 = new $W.Button("splitbutton1", { type: "split",
		 * menu: "splitbutton1select" }); }
		 */
		$E.onAvailable(id, function() {
			if ($('splitbutton1')) {
				var oSplitButton1 = new $W.Button("splitbutton1", {
					type : "split",
					menu : "splitbutton1select"
				});
			}
		});
	}, //
	/**
	 * Closure based object constructor do NOT use 'new' to instantiate!
	 * 
	 * @param {Object}
	 *            o
	 */
	oSwitcharoo : function(o) {

		/**
		 * Upon calling this constructor validate the input object and may throw
		 * LampcmsException if object is missing some expected elements
		 */
		this.validateParsed(o);

		/**
		 * These vars will be private through closure: any function of returned
		 * object will have access to these but they cannot be accessed directly
		 * no can they be changed directly
		 */
		var oUsers = o.users, //
		sMenuId = "switcmenu1", //
		sSwitchItemId = "switcher1", //
		sPostUrl = '/index.php', //
		sLabel = o.sLabel;
		$L('361 oUsers: ' + $LANG.dump(oUsers));

		var oRet = {
			toString : function() {
				return 'Switcharoo object';
			},//
			onMenuItemClick : function(p_sType, p_aArgs, p_oValue) {
				$L('412 include.js p_oValue: ' + p_oValue, 'warn');
				$CONN.asyncRequest('POST', oSL.oS.getPostUrl(), oSL.oCallback, oSL.oS.makeFormParams(p_oValue));
			},//
			getMenuId : function() {
				return sMenuId;
			},//
			getSwitchItemId : function() {
				return sSwitchItemId;
			},//
			getPostUrl : function() {
				return sPostUrl;
			},//
			getUid : function(sUsername) {
				for ( var uid in oUsers) {
					if (oUsers[uid] === sUsername) {
						return uid;
					}
				}

				return null;
			},//
			makeFormParams : function(uid) {
				var result;
				// var uid = this.getUid(sUsername);
				if (!uid) {
					throw new LampcmsException('userid not found for this username: ' + sUsername);
				}

				result = 'qf_version=' + o.qf_version + '&a=' + o.a + '&uid=' + uid;

				$L('441 include.js result: ' + result, 'warn');

				return result;
			}, //
			getA : function() {
				return o.a;
			},//
			getToken : function() {
				return o.qf_version;
			},//
			getSwitchText : function() {
				return sLabel;
			},//
			getUsersArray : function() {
				var oMyUser, aMyUsers = [];
				for ( var id in oUsers) {
					oMyUser = {
						text : oUsers[id],
						onclick : {
							fn : oSL.oS.onMenuItemClick,
							obj : id
						}
					};
					aMyUsers.push(oMyUser);
				}

				return aMyUsers;
			}
		};

		return oRet;
	},// 
	// A workaround for XSL-to-XHTML systems that don't
	// implement XSL 'disable-output-escaping="yes"'.
	//
	// sburke@cpan.org, Sean M. Burke.
	// - I hereby release this JavaScript code into the public domain.
	check_decoding : function() {
		var d = $('cometestme');

		if (!d) {
			alert("Can't find an id='cometestme' element?");
			throw LampcmsException("Can't find an id='cometestme' element?");
		} else if (!('textContent' in d)) {
			// It's a browser with a halfassed DOM implementation (like
			// IE6)
			// that doesn't implement textContent! Assume that if it's
			// that
			// dumb, it probably doesn't implement
			// disable-content-encoding.

		} else {
			ampy = d.textContent;

			// alert("432 Got " + ampy);

			if (ampy === undefined) {
				// alert('436 Firefox developers suck ballz and eats
				// shit');
				throw LampcmsException("'cometestme' element has undefined text content?!");
			}
			if (ampy === '') {
				// alert(' 440 Firefox developers suck ballz and eats
				// shit');
				throw LampcmsException("'cometestme' element has empty text content?!");
			}

			if (ampy == "\x26") {
				// alert(' 445 Firefox developers suck ballz and eats
				// shit');
				this.is_decoding = true;
			} else {
				// alert('448 Firefox developers suck ballz and eats
				// shit');
				if (ampy == "\x26amp;") {
					// alert('765 this is ' + this);
					// alert('451 Firefox developers suck ballz and eats
					// shit');
					this.is_decoding = false;
				} else {
					// alert('454 Firefox developers suck ballz and eats
					// shit');
					throw LampcmsException('Insane value: "' + ampy + '"!');
				}
			}

		}

		var msg = (this.is_decoding === undefined) ? "I can't tell whether the XSL processor supports disable-content-encoding!D"
				: this.is_decoding ? "The XSL processor DOES support disable-content-encoding" : "The XSL processor does NOT support disable-content-encoding";

		// alert(msg);

		return msg;
	}, //
	go_decoding : function() {
		if (!(document.getElementById)) {

			alert("Your browser sucks eggs.\n\nConsider upgrading to Internet Explorer 6, Firefox, or Mozilla or Chrome.");
		}

		// alert('473');
		this.check_decoding();

		if (true === this.is_decoding) {
			// alert("588 No work needs doing -- already decoded!");
			return;
		}

		var to_decode = document.getElementsByName('decodeable');
		var to_decode = $C('decodeable');

		if (!(to_decode && to_decode.length)) {
			// alert("No work needs doing -- no elements to decode!");
			return;
		}

		var s;
		for ( var i = to_decode.length - 1; i >= 0; i--) {
			s = to_decode[i].textContent;

			if (s == undefined || (s.indexOf('&') == -1 && s.indexOf('<') == -1)) {
				// the null or markupless element needs no reworking
			} else {
				to_decode[i].innerHTML = s; // that's the magic
			}
		}

		return;
	}, //
	makeSwitchMenu : function(o) {
		try {
			$L('515 o ' + o, "window");
			if (!o || (o === null)) {
				$L('517 o is null', "window");
				var o = this.parseSwitchForm();
				$L('397 o: ' + $LANG.dump(o), "window");
			} else {
				$L('418 o: ' + $LANG.dump(o), "warn");
			}
			if (this.oS) {

				// delete (this['oS']);
			}
			$L('527 o: ' + $LANG.dump(o), "warn");
			this.oS = this.oSwitcharoo(o);
			$L('529 o: ' + $LANG.dump(o), "warn");
		} catch (e) {
			$L("424 Caught error: " + e.message, "error");
			return false;
		}

		// $L('412 items: ' + $LANG.dump(this.oS.getMenuItems()) + '
		// messenger
		// uid: ' + this.oS.getUid('messenger'));
		/**
		 * check if oMenu exists, if it has menu oWelcome if oWelcome already
		 * has item with id 'switcharoo' then remove it (along with sub-menu)
		 * append item with id 'switcharoo' and submenu find the newly created
		 * item object and subscribe it to onClick event
		 */
		if (o1 && o1.oMenu) {
			$L('489 starting this is ' + this);

			var oSwitchMenu, oMenuBar = o1.oMenu;
			$L('493');
			var aItems = oMenuBar.getItems();
			$L('495');

			var oWelcomeMenu = aItems[0].cfg.getProperty("submenu");
			$L('497');

			var aMyUsers = this.oS.getUsersArray();
			$L('560 aMyUsers: ' + $LANG.dump(aMyUsers));

			var sSubId = this.oS.getMenuId();
			$L('501 sSubId ' + sSubId);

			var oSub1 = new $W.Menu(sSubId);

			var sLabelText = this.oS.getSwitchText();
			// $L('504 sLabelText ' + sLabelText + ' oSub1 ' +
			// $LANG.dump(oSub1));

			var sMyItemId = this.oS.getSwitchItemId();
			$L('571 sMyItemId ' + sMyItemId);

			oSub1.addItems(aMyUsers);

			// $L('575: ' + $LANG.dump(oSub1));

			oWelcomeMenu.insertItem({
				id : sMyItemId,
				text : sLabelText
			}, 0);

			// $L('582: ' + $LANG.dump(oWelcomeMenu));
			/**
			 * oSwitchMenu is now the first menuItem in the welcom menu
			 */
			oSwitchMenu = oWelcomeMenu.getItem(0);

			$L('589');
			oSwitchMenu.cfg.setProperty("submenu", oSub1);
			$L('591');

			oWelcomeMenu.render();
			$L('594');

		}
	}, //
	validateParsed : function(oRes) {
		if (!oRes.a || !oRes.qf_version || !oRes.sLabel || !oRes.users) {
			throw new LampcmsException('Not all required elements found in form');
		}
	}, //
	parseSwitchForm : function() {
		var sLabel, sName, sType, elParent, sQfv, oRes = {}, oUsers = {}, bUser = false, oFrm = $('fSwitch');
		$L('591 oFrm ' + oFrm, "warn");
		if (!oFrm || !oFrm.elements) {
			throw new LampcmsException('Form "fSwitch" not found in document');
		}

		elParent = oFrm.parentNode;
		$L('545 form parent: ' + elParent);
		/**
		 * Now can remove actual form from the page
		 */
		if (elParent) {
			elParent.removeChild(oFrm);
		}

		for ( var element in oFrm.elements) {
			var fElement = oFrm.elements[element];
			if (fElement) {
				sName = fElement.name;
				sType = fElement.type;
				if ((sName) && (sName === 'a' || sName === 'qf_version')) {
					oRes[sName] = fElement.value;
				}
				if (fElement.type === 'submit') {
					oRes['sLabel'] = fElement.value;
				}
				// if (sName === 'amerged' && fElement.options) {
				if (sName === 'uid' && fElement.options) {
					$L('399 num options: ' + fElement.options.length);
					for ( var i = 0; i < fElement.options.length; i++) {
						var oOption = fElement.options[i];
						if (oOption.value && oOption.text) {
							bUser = true;
							oUsers[oOption.value] = oOption.text;
						}
					}
					if (bUser) {
						oRes['users'] = oUsers;
					}
				}
			}
		}

		$L('634 ', "warn");
		this.validateParsed(oRes);
		$L('414 oRes: ' + $LANG.dump(oRes));

		return oRes;
	},//
	makeHomeTabs : function() {
		/*
		 * var rootdiv1 = $("mybody"); if (rootdiv1 == "undefined") { alert('no
		 * element "mybody"'); };
		 */
		var rootdiv1, aRoot = $C('yui-b', 'div', 'yui-main');
		if (aRoot && aRoot[0]) {
			rootdiv1 = aRoot[0];
		}
		$L('544 rootdiv1: ' + rootdiv1);

		var recentHTML = rootdiv1.innerHTML;

		rootdiv1.innerHTML = "";
		$L('537 rootdiv1: ' + rootdiv1);
		var navblock = $("navBlock");
		if (navblock == "undefined") {
			alert('no element "navBlock"');
		}
		$L('542 navblock: ' + navblock);

		var aLinks = navblock.getElementsByTagName("a");
		var tabView = new $W.TabView();
		$L('546 tabView: ' + tabView);

		for ( var i = 0; i < aLinks.length; i++) {
			var sTitle = aLinks[i].getAttribute("title");
			// if aLinks[i].getAttribute("href") has ? then separate by
			// &, else
			// by ?
			var href = aLinks[i].getAttribute("href");
			var separator = (href.search(/\?/) > 0) ? "&" : "?";
			var sHref = href + separator + "do=home";

			if (i === 0) {
				tabView.addTab(new $W.Tab({
					label : sTitle,
					content : recentHTML,
					active : true
				}));
			} else {
				tabView.addTab(new $W.Tab({
					label : sTitle,
					dataSrc : sHref,
					cacheData : true,
					active : false
				}));
			}

		}
		$L('570 tabView: ' + tabView);
		navblock.innerHTML = "";
		tabView.appendTo(rootdiv1);
	}, //
	updateUserPic : function(src) {
		$L('804 updateUserPic', 'warn');
		var ts, qpos, a = $C('upic', 'td', $('loginHead'));
		var tdAvatar = a[0];
		$L('806: eAvatar: ' + tdAvatar, 'warn');

		tdAvatar.innerHTML = src;

		// qpos = eAvatar.src.indexOf('?');
		// src = (qpos > -1 ) ? eAvatar.src.substr(0, qpos) :
		// eAvatar.src;

		// $L('799 src: ' + src, 'warn');
		// ts = new Date().getTime();
		// $L('801 ts: ' + ts, 'warn');
		// src = src + '?' + ts;
		// eAvatar.setAttribute("src", src);
		// $L('eAvatar.src: ' + eAvatar.src, 'warn');

	}, //
	/**
	 * Parse data object, depending of keys and values update elements on the
	 * page.
	 * 
	 * @param {Object}
	 *            o parsed json data returned from server after processing form
	 *            values.
	 */
	fParseQf : function(json) {
		$L($LANG.dump(json));

		var strMessage = '', aAvatars, i = 0, el, formField, eMessageDiv = $('qfe');

		switch (true) {

		case json.hasOwnProperty('exception'):
			if (json.hasOwnProperty('errHeader')) {
				strMessage += '<u>' + json.errHeader + '</u><br>';
			}
			eMessageDiv.innerHTML = '<div id="qfErrors">' + strMessage + json.exception + '</div>';
			break;

		case json.hasOwnProperty('success'):
			// this is doc
			if (eMessageDiv) {
				strMessage += json.success;
			}
			if (json.blog_title && json.blog_title.val) {
				if (this.eH1) {
					this.eH1.innerHTML = json.blog_title.val;
				}
			}
			if (this.eH2 && json.blog_description && json.blog_description.val) {
				this.eH2.innerHTML = json.blog_description.val;
			}
			for ( var formField in json) {
				if (json.hasOwnProperty(formField) && json[formField].hasOwnProperty('err')) {
					// alert('formField: ' + formField + 'err: ' +
					// json[formField].err);
					strMessage += '<br><u>' + json[formField].err + '</u><br>';
				}
			}

			/**
			 * If avatar has been updated, then we will have an element 'avatar'
			 * which is an array and its 'val' will be a full html img src tag
			 * to avatar We will need to update all divs with class 'avatar'
			 * Normally there will be 2 of these divs: one under the profile
			 * form itself and one in the user's template nav bar.
			 */
			if (json.avatar && json.avatar.val && json.avatar.val !== '') {
				$Y.log('this is ' + this, 'warn');
				$D.setStyle(this.aTrs, 'visibility', '');
				$D.setStyle(this.aTrs, 'display', '');

				aAvatars = $C('avatar', 'div');
				if (aAvatars) {
					for (i = 0; i < aAvatars.length; i += 1) {
						aAvatars[i].innerHTML = json.avatar.val;
					}
					$L('856 before updateUserPic this is ' + this, 'warn');
				} else {
					$Y.log('no div with class "avatar"', 'warn');
				}
			}

			if (json.avatar && json.avatar.sqr && json.avatar.sqr !== '') {
				this.updateUserPic(json.avatar.sqr);
			}

			eMessageDiv.innerHTML = strMessage;
			this.fColorChange('qfmessage', '#00FF00', '#FFFFFF'); // eMessageDiv
			break;

		case json.hasOwnProperty('errors'):
			if (json.hasOwnProperty('errHeader')) {
				strMessage += '<u>' + json.errors.errHeader + '</u><br>';
			}

			eMessageDiv.innerHTML = '<div id="qfErrors">' + strMessage + json.errors.errMessage + '</div>';
			this.aEls = [];
			for (formField in json) {
				if (json.hasOwnProperty(formField) && json[formField].hasOwnProperty('err')) {
					el = $('a' + formField);
					if (el) {
						el.style.backgroundColor = '#FFFFCC';
						this.aEls.push(el);
					}
				}
			}

			this.fColorChange('qfmessage', '#FF0000', '#FFFFFF'); // eMessageDiv
			break;

		}

		if (oSL.oFrm && oSL.oFrm.elBtnSubmit) {
			oSL.oFrm.elBtnSubmit.disabled = false;
		}
		var elPbar = $('progressBar'), elAvatarField = $('aavatar');
		if (elPbar) {
			elPbar.parentNode.removeChild(elPbar);
		}
		if (elAvatarField) {
			$D.setStyle(elAvatarField, 'display', 'block');
		}

	}, //
	/**
	 * Get translated value of a string if it exists in oLampcmsTr object This
	 * object is usually added (sometimes) directly to the html page from the
	 * clsWebPage->addTranslatedJson()
	 * 
	 * @param string
	 *            s a string to translate
	 * 
	 * @param string
	 *            sTrPage a translation page where to find the string
	 */
	translateTrString : function(s, sPage) {

		// $L('starting translateTrString ' + s + ' 888 this is: ' +
		// this);

		if (!s || !sPage) {
			throw new LampcmsException('oSL.translateTrString() requires 2 arguments!');
		}

		if (!this.oLampcmsTr || !this.oLampcmsTr[sPage]) {
			this.formatTrKey(s);
		}

		return (this.oLampcmsTr[sPage][s]) ? this.oLampcmsTr[sPage][s] : this.formatTrKey(s);

	}, //
	/**
	 * In case translation string was not translated (not found in translation
	 * lookup table) then we usually return the untranslated key, but first we
	 * need to format the key nicely, at least convert it to upper case and
	 * replace underscores with spaces
	 * 
	 * @param {Object}
	 *            s
	 */
	formatTrKey : function(s) {
		var first, rest;
		if (!s) {
			throw new LampcmsException('oSL.formatTrKey() requires one non-empty string parameter');
		}

		first = s.substr(0, 1);
		rest = s.substr(1, s.length - 1);
		s = first.toUpperCase() + rest.toLowerCase();

		return s = s.replace('_', ' ');
	}
}; //

oSL.alerter = (function() {
	var oPanel;

	return {

		getInstance : function() {
			if (!oPanel) {
				oPanel = new $W.SimpleDialog("dlg1", {
					width : "400px",
					fixedcenter : true,
					modal : true,
					visible : false,
					close : true,
					zindex : 90,
					constraintoviewport : true,
					buttons : [ {
						text : "close",
						handler : function() {
							this.hide();
						},
						isDefault : true
					} ],
					draggable : false,
					effect : [ {
						effect : $W.ContainerEffect.FADE,
						duration : 0.2
					} ]

				});

				oPanel.setHeader("Alert");
				oPanel.render(document.body);
			}

			return oPanel;
		},
		/**
		 * Useful if we need to call destructor
		 */
		destroy : function() {
			if (oPanel) {
				oPanel.destroy();
			}
		},
		/**
		 * If panel exists call the hide() method
		 */
		hide : function() {
			if (oPanel) {
				oPanel.hide();
			}
		},
		toString : function() {
			return 'object created with oTQ.showAlert()';
		}
	};

})();

/**
 * Modal is the object to show 'loading modal' when ajax call starts and to hide
 * it when it ends
 */
oSL.modal = (function() {
	var oModal;

	return {
		show : function(sText) {
			$L('modal show');
			if (!oModal) {
				$L('1189 cp');
				oModal = new $W.Panel("mywait", {
					width : "240px",
					fixedcenter : true,
					close : false,
					draggable : false,
					zindex : 4,
					modal : true,
					visible : false
				});
				$L('1199 cp');

				oModal.setHeader('');
				oModal.setBody("<img src=\"/images/loading-bar.gif\"/>");
				oModal.render(document.body);
			}

			sText = (sText) ? sText : 'Loading, please wait...';
			oModal.setHeader(sText);
			oModal.show();
		},
		hide : function() {
			if (oModal) {
				oModal.hide();
			}
		}
	};
})();
/**
 * Dialog used for Tweeting from our site Should display modal window with a
 * short form to send tweet.
 */
oSL.tweet = (function() {

	var oDialog;
	var siteTitle = oSL.getMeta('site_title');
	var siteUrl = oSL.getMeta('site_url');
	var token = oSL.getToken();

	return {

		getInstance : function() {
			var eRootDiv, oFrm, siteDescription, sForm;
			if (!oDialog) {
				if (!$('dialog1')) {

					sForm = '<div class="hd">Please enter your information</div>' + '<div class="bd"><hr/>' + '<form method="POST" action="/index.php">'
							+ '<input type="hidden" name="a" value="tweet">' + '<input type="hidden" name="token" value="' + token + '">'
							+ '<h3 class="tweetdlg">Tweet this:</h3>' + '<div class="clear"></div>' + '<textarea cols="44" rows="5" name="tweet">'
							+ $('twinvite').title + ' ' + siteTitle + ' ' + siteUrl + '</textarea>' + '<div class="clear"></div>' + '</form>';

					eRootDiv = document.createElement('div');
					eRootDiv.id = 'dialog1';
					document.body.appendChild(eRootDiv);
					eRootDiv.innerHTML = sForm;
				}
				oDialog = new $W.Dialog("dialog1", {
					width : "30em",
					fixedcenter : true,
					visible : false,
					constraintoviewport : true,
					/*
					 * x : 200, y : 200,
					 */
					buttons : [ {
						text : "Submit",
						handler : function() {
							this.submit();
						},
						isDefault : true
					}, {
						text : "Cancel",
						handler : function() {
							this.cancel();
						}
					} ]
				});
				oDialog.beforeSubmitEvent.subscribe(function() {
					$L('before submit tweet');
					oSL.modal.show();
				});
				oDialog.callback = {
					success : function(o) {
						alert('Tweet sent');
						oSL.modal.hide();
					},
					failure : function(o) {
						alert('Tweet not sent');
						oSL.modal.hide();
					}
				};
				oDialog.setHeader("Invite Your Friends");
				oDialog.render(document.body);
			}

			return oDialog;
		},
		/**
		 * Useful if we need to call destructor
		 */
		destroy : function() {
			if (oDialog) {
				oDialog.destroy();
			}
		},
		/**
		 * If panel exists call the hide() method
		 */
		hide : function() {
			if (oDialog) {
				oDialog.hide();
			}
		},

		setTextArea : function(s) {

		},
		toString : function() {
			return 'object oDialog created with oSL.dialog()';
		}
	};

})();

/**
 * Object for Signin with Twitter
 */

oSL.Twitter = {
	/**
	 * Popup window object
	 */
	popupWindow : null,
	/**
	 * Array of Async requests This is just a stack, there should only be one
	 * async request and no more, so we add async request object to this stack,
	 * then open success we clear it and before each new request we must check
	 * if another request is still running
	 */
	aRequests : [],

	/**
	 * Interval object There should be only one of this if we already have an
	 * interval then we should not start another login process OR clear previous
	 * interval first
	 */
	oInterval : null,

	/**
	 * Start the oAuth login process by opening the popup window
	 */
	startDance : function() {
		$L('1084 starting oAuth dance this is: ' + this, 'window');
		var popupParams = 'location=0,status=0,width=800,height=450,alwaysRaised=yes,modal=yes', mydomain = window.location.hostname;

		// alert('1528 ' + mydomain);

		/**
		 * Prevent user from opening more than one Twitter oAuth popup windows.
		 * This is helpful when the already opened window has gone out of focus
		 * (turned into popunder) accedentally
		 * 
		 */
		if (this.popupWindow && !this.popupWindow.closed) {
			this.popupWindow.location.href = 'http://' + mydomain + '/index.php?a=logintwitter';
			this.popupWindow.focus();
			return;
		}

		this.popupWindow = window.open('http://' + mydomain + '/index.php?a=logintwitter', 'twitterWindow', popupParams);

		if (!this.popupWindow) {
			alert('Unable to open login window. Please make sure to disable popup blockers in your browser');
			return;
		}

		/**
		 * This is very important to cancel any already running intervaled jobs,
		 * otherwise the next one will override prev one but the job will still
		 * be running in the background, so it will never be cancelled,
		 * resulting in continuesly issuing asyncRequests to the server like
		 * crazy
		 * 
		 * This can happend when someone opens multiple browser windows by
		 * clickin on 'signin with twitter' several times
		 */
		if (oSL.Twitter.oInterval) {
			alert('1109 something is still running');
			window.clearInterval(oSL.Twitter.oInterval);
			oSL.Twitter.oInterval = null;
		}

		this.oInterval = window.setInterval(this.checkLogin, 500);
		$L('1085 this.oInterval ' + this.oInterval, 'warn');
	},

	/**
	 * This method is check via oInterval, every half a second to check if popup
	 * window has been closed on not. If popup has been closed then we assume
	 * that the first step in oAuth dance is done and can check with the server
	 * to see if session now has user object
	 */
	checkLogin : function() {
		$L('11125 checking login', 'window');

		var transaction, cObj;

		if (!oSL.Twitter.popupWindow || oSL.Twitter.popupWindow.closed) {

			oSL.Twitter.cancelIntervals();
			oSL.Twitter.cancelAsyncCalls();

			/**
			 * Now it just reload the page Simple, just like most other sites
			 * doing it.
			 * 
			 */
			window.location.reload(true);
		}
	},
	/**
	 * In case there are any jobs still running at intervals we must cancell the
	 * job and null the interval
	 * 
	 * This will also be called from the processLogin() method as well as from
	 * the checkLogin() when we detect that popup has been closed
	 */
	cancelIntervals : function() {

		$L('1150 cancellng pending intervals this: ' + this, 'window');
		if (oSL.Twitter.oInterval) {
			$L(' 1131 killing interval');
			window.clearInterval(oSL.Twitter.oInterval);
			oSL.Twitter.oInterval = null;
		}
	},
	/**
	 * If any other XHR transactions are still running we abort them before
	 * starting this one This will also be called from the processLogin() method
	 * because its very possible that when popup passes the data to opener and
	 * then closes, the opener will also detect that popup has closed and will
	 * fire the async request to check login
	 */
	cancelAsyncCalls : function() {

		$L('1147 cancelling all XHR calls this: ' + this, 'error');

		if (oSL.Twitter.aRequests.length > 0) {
			for ( var i = 0; i < oSL.Twitter.aRequests.length; i += 1) {
				transaction = oSL.Twitter.aRequests[i];
				if ($CONN.isCallInProgress(transaction)) {
					$CONN.abort(transaction);
				}
			}
		}
	},
	toString : function() {
		return 'object oSL.Twitter';
	}
};
/**
 * Javascript for creating modal window with registration form, handling
 * registration form submittio via ajax, handling various responses, errors
 */
oSL.Regform = (function() {

	var errDiv;

	/**
	 * Object of type Dialog which is a form inside of modal window
	 */
	var oDialog;

	/**
	 * Associative array of dialog objects
	 */
	var aDialogs = {};

	/**
	 * SimpleDialog prompt that will handle the "Cancel" button
	 */
	var oPrompt;

	/**
	 * Handle click on submit button "this" is object of oDialog Must disable
	 * the submit button, start validation and actually submit the form and add
	 * 'loading' icon or start email validation progress bar.
	 */
	var handleSubmit = function() {
		$L('12 this is: ' + this);
		// oSL.Regform.setButtonsDone();
		this.submit();
	};

	/**
	 * User clicked on Cancel button We must show prompt "Are you sure?" Yes/No
	 * if Yes, then must set cookie 'skipReg' so that next time during the same
	 * sessin we don't show this prompt again
	 */
	var handleCancel = function() {
		$L('41 clicked on Cancel this is: ' + this);
		oSL.Regform.getPrompt().show();;
	};
	/**
	 * Handles when user clicked on "Continue registration" button in the "Are
	 * you sure?" Prompt
	 */
	var handleContinue = function() {
		this.hide();
	};
	/**
	 * Handle click on Exit registration button in the oPrompt prompt This will
	 * close the prompt and will close the registration Dialog
	 */
	var handleExit = function() {
		$L('handling exit');
		this.hide();
		oSL.Regform.getInstance().hide();
		$COOKIE.set("dnd", "1", {
			path : "/"
		});
	};
	/**
	 * Success only means that json data was received but it may still contain
	 * error messages, This function will set error messages if there are any,
	 * or in case of success it will replace the body of this panel with the
	 * success text and maybe 2 buttons "Close" and "Go to profile page" Also
	 * it's possible that if we want to show the newsletter selection page we
	 * will then probably have to destroy this panel and create a brand new one
	 * for the newsletter selections
	 */
	var handleSuccess = function(o) {
		// $L('39 success ' + this, 'warn');
		var oMyDialog = oSL.Regform.getInstance();
		oSL.modal.hide();
		oSL.Regform.enableButtons();
		// oSL.Regform.getInstance().setBody('');
		// oSL.Regform.getInstance().setFooter('<p>stuff and stuff</p>');
		var aButtons = oSL.Regform.getInstance().getButtons();
		for ( var i = 0; i < aButtons.length; i += 1) {
			$L('button ' + i + ' is ' + aButtons[i]);
		}

		var response = o.responseText;
		try {
			json = $J.parse(o.responseText);
			// alert($LANG.dump(json));
			switch (true) {
			case (json.hasOwnProperty('exception')):
				setError(json);
				break;

			case (json.hasOwnProperty('action') && (json.action == 'done')):
				oMyDialog.setHeader('Welcome!');
				oMyDialog.setFooter('');
				oMyDialog.setBody(json.body);
				break;
			}

		} catch (e) {
			oSL.modal.hide();
			alert("Invalid json data in responceText " + $LANG.dump(e) + "\noRespnose: " + $LANG.dump(o.responseText));
		}

	};

	var handleFailure = function(o) {
		oSL.modal.hide();
		oSL.Regform.enableButtons();
		oSL.Regform.getInstance().setBody('<p>boo hoo, something is wrong</p>');
		// setError('failed');
		$L('47 fail ', 'warn');
	};

	var setError = function(oError) {
		var errDiv = $('formerr');
		var aInputs, message = oError.exception, //
		oRegform = oSL.Regform.getInstance(); //
		var myForm = oRegform.form;

		errDiv.innerHTML = message;
		oSL.fColorChange(errDiv, '#FFFFFF', '#FF0000');

		if (oError.type && ('LampcmsCaptchaLimitException' === oError.type)) {
			$LANG.later(2000, oRegform, 'destroy');
		}

		if (oError.hasOwnProperty('fields')) {
			aInputs = oError.fields;
			for ( var i = 0; i < aInputs.length; i += 1) {
				if (myForm.hasOwnProperty(aInputs[i])) {
					myForm[aInputs[i]].style.backgroundColor = "#CCFFCC";
				}
			}
		}

		if (oError.hasOwnProperty('captcha')) {
			if (oError.captcha.public_key && oError.captcha.hncaptcha && oError.captcha.img) {
				myForm.public_key.value = oError.captcha.public_key;
				myForm.private_key.value = '';
				myForm.hncaptcha.value = oError.captcha.hncaptcha;
				$('imgcaptcha').innerHTML = oError.captcha.img;
			}
		} else {
			/**
			 * If error is not a captcha error this means that captcha has been
			 * verified since we do captcha verification first In this case we
			 * should set the form field to disabled oError.type means exception
			 * came from server side validation and not just from validate() js
			 * based pre-validation
			 */
			if (myForm.private_key && oError.type) {
				myForm.private_key.disabled = true;
			}
		}
	};
	/**
	 * Buttons to be used on the "Registration complete" panel These buttons
	 * will replace the other buttons that were created initially on the Dialog
	 */
	var aButtonsDone = [ {
		text : "<-- Return to page",
		handler : function() {
			alert('this is ' + this);
		},
		isDefault : true
	}, {
		text : "Go to Profile editor -->",
		handler : function() {
			alert('go to profile');
		}
	} ];

	/**
	 * Start the progress bar or progress icon
	 */
	var startProgress = function(o) {
		oSL.Regform.disableButtons();
		oSL.modal.show('Please wait...');
	};

	return {
		getInstance : function() {
			$L('cp 13', 'warn');
			if (!oDialog) {
				$L('cp 15', 'warn');
				$D.removeClass("regdiv", "yui-pe-content");
				$L('cp 17', 'warn');
				oDialog = new $W.Dialog("regdiv", {
					width : "50em",
					fixedcenter : true,
					visible : false,
					constraintoviewport : true,
					hideaftersubmit : false,
					draggable : true,
					close : false,
					modal : true,
					buttons : [ {
						text : "Create Your Account",
						handler : handleSubmit,
						isDefault : true
					}, {
						text : "Cancel",
						handler : handleCancel
					} ]
				});

				oDialog.callback = {
					success : handleSuccess,
					failure : handleFailure
				};

				oDialog.validate = function() {
					var message, //
					aInputs = [], //
					myForm = this.form, //
					nd = new Date(), //
					data = this.getData();
					$L('data: ' + $LANG.dump(data));
					var tzo = (0 - (nd.getTimezoneOffset() * 60)); // now its
					// number of
					// seconds
					if ((myForm.tzo) && (tzo)) {
						myForm.tzo.value = tzo;
					}

					var checkEmail = function(str) {
						var at = "@", dot = ".", lat = str.indexOf(at), lstr = str.length, ldot = str.indexOf(dot);

						if (str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) {

							return false;
						}

						if (str.indexOf(dot) == -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) {

							return false;
						}

						if (str.substring(lat - 1, lat) == dot || str.substring(lat + 1, lat + 2) == dot) {

							return false;
						}

						if ((str.indexOf(at) == -1) || (str.indexOf(at, (lat + 1)) != -1) || (str.indexOf(dot, (lat + 2)) == -1) || (str.indexOf(" ") != -1)) {

							return false;
						}

						return true;
					};

					switch (true) {
					case (data.email == ""):
						message = "Please enter email address";
						aInputs.push('email');
						break;

					case (data.username == ""):
						message = "Please enter Username";
						aInputs.push('username');
						break;

					case (data.hasOwnProperty('private_key') && ("" == data.private_key)):
						message = "Please enter the text from image";
						aInputs.push('private_key');
						break;

					case (!checkEmail(data.email)):
						message = "Email address appears to be invalid<br>Please enter a valid Email";
						aInputs.push('email');
						break;

					default:

						return true;
					}

					setError({
						exception : message,
						fields : aInputs
					});
					return false;

				};
				oDialog.asyncSubmitEvent.subscribe(function(type, args) {
					var connectionObject = args[0];
					startProgress();

				});

				oDialog.render();

			}

			return oDialog;
		},

		toString : function() {
			return 'object oSL.Regform';
		},
		getPrompt : function() {
			if (!oPrompt) {
				$L('making prompt');
				oPrompt = new $W.SimpleDialog("simpledialog1", {
					width : "300px",
					fixedcenter : true,
					zindex : 99,
					visible : false,
					draggable : false,
					close : true,
					modal : true,
					text : "Do you want to continue?",
					icon : $W.SimpleDialog.ICON_ALARM,
					/* icon : $W.SimpleDialog.ICON_HELP, */
					constraintoviewport : true,
					buttons : [ {
						text : "Continue registration",
						handler : handleContinue,
						isDefault : true
					}, {
						text : "Exit registration",
						handler : handleExit
					} ],
					effect : [ {
						effect : $W.ContainerEffect.FADE,
						duration : 0.2
					} ]
				});

				oPrompt.setHeader("Are you sure?");
				oPrompt.render(document.body);
			}

			$L('176 oPrompt: ' + oPrompt, 'warn');

			return oPrompt;
		},
		disableButtons : function() {
			var aBtns;
			$L('105 this is: ' + this, 'warn');
			if (oDialog) {
				aBtns = oDialog.getButtons();
				for ( var i = 0; i < aBtns.length; i += 1) {
					aBtns[i].set('disabled', true);
				}

			}
		},
		enableButtons : function() {
			var aBtns;
			$L('105 this is: ' + this, 'warn');
			if (oDialog) {
				aBtns = oDialog.getButtons();
				for ( var i = 0; i < aBtns.length; i += 1) {
					aBtns[i].set('disabled', false);
				}

			}
		},
		setButtonsDone : function() {
			oDialog.cfg.queueProperty("buttons", aButtonsDone);
		},
		destroy : function() {
			if (oDialog) {
				oDialog.destroy();
			}
		},
		hasDialog : function() {
			if (oDialog && oDialog.body) {
				return true;
			}

			return false;
		}

	};
})();
/*
 * oSL.hideRegForm = function() { if (oSL.Regform) {
 * oSL.Regform.getInstance().hide(); window.location.reload(); }
 * 
 * return false; };
 */
/*
 * oSL.getQuickRegForm = function() { if (oSL.Regform &&
 * oSL.Regform.hasDialog()) { oSL.Regform.getInstance().show(); } else {
 *//**
	 * &ajaxid=1&tplflag=1
	 */
/*
 * oSL.modal.show(); $CONN.asyncRequest("GET", "/index.php?a=getregform",
 * oSL.oCallback); } };
 */

$E.onDOMReady(function() {

	$L('1016 Window object: ' + window, 'warn');

	var eLink, myspan, dnd, tabView, gfcCounter = 0;

	oSL.fMakeLangSelect('langForm');
	$E.addListener('loginHead', "click", oSL.fLogin, oSL, true);
	// oSL.fMakeMeNav('menav'); // making this onAvailable results in
	// rendering menu twice when loaded by ajax
	/*
	 * try { oSL.go_decoding(); } catch (e) { alert("Caught error: " +
	 * e.message, "error"); return false; }
	 */

	if ($W.LogMsg && $W.LogReader) {
		$E.onContentReady('loaded', function() {
			var myLogReader = new $W.LogReader();
		});
	}

	if ($('sims')) {
		tabView = new $W.TabView('sims');
		$L('tabVies is: ' + tabView);
	}

	window.alert = function(text) {
		var oAlert = oSL.alerter.getInstance();
		oAlert.cfg.setProperty("text", text);
		oAlert.show();
	};

	// linkout
	eLink = $C('linkout', 'div');
	if (eLink && eLink[0]) {
		myspan = eLink[0].getElementsByTagName('span');
		if (myspan && myspan[0]) {
			$E.addListener(myspan[0], "click", function() {
				var sUrl, myid = parseInt(this.id.substr(4));
				var atype = this.getAttribute('class');
				if (oSL) {
					sUrl = oSL.getMeta('site_url');
					window.open(sUrl + '/index.php?a=linkout&id=' + myid + '&atype=' + atype);
				} else {
					return;
				}

			});
		}
	}

	if ($('regdiv')) {
		var dnd = false;
		$L(' 2299 have regdiv', 'window');
		dnd = $COOKIE.get("dnd");
		$L('dnd is: ' + dnd, 'window');
		/**
		 * Don't show regform if use has 'dnd' (do not disturb) cookie
		 */
		if (!dnd) {
			oSL.Regform.getInstance().show();
		}
	}

});

