// -- start common js for lite homepage

if ( document.location == "http://radiusim.com/" || document.location == "http://alpha.radiusim.com/"  ){
	window.top.location.href="http://www.radiusim.com";
}

if(typeof rad === 'undefined'){
	var rad = {};
}

function onElementFocused(e)
{	
    if (e && e.target){
    	rad.activeElement = e.target == document ? null : e.target;
    }
} 

if (document.addEventListener) {
    document.addEventListener("focus", onElementFocused, true);
}

var preloadLoading = new Image();
preloadLoading.src = "http://s0-s3cdn.radiusim.com/hudson-PATCH-0.86.002/images/loading.gif";

// -- these two functions remove or append "_over from sprite classes"
function onOverSprite( node ) {
	node.className = node.className + "_over";
}

function onOutSprite( node ) {
	node.className = node.className.replace("_over", "");
}

// -- these two functions handle similar over and out events for the normal textBtn container
function liteTextButtonOn( node ) {
	node.childNodes[0].className = "textBtnLeftClass_normal textBtnLeftClass_normal_over";
	node.childNodes[1].className = "textBtnRightClass_normal textBtnRightClass_normal_over";
}

function liteTextButtonOff( node ) {
	node.childNodes[0].className = "textBtnLeftClass_normal textBtnLeftClass_normal_reg";
	node.childNodes[1].className = "textBtnRightClass_normal textBtnRightClass_normal_reg";
}


function radXMLHttpRequest() {
	var xmlhttp;
	try{
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch(e){
		try{
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}catch(E){
			xmlhttp = false;
		}
	}
	if(!xmlhttp && typeof XMLHttpRequest != 'undefined'){
		try{
			xmlhttp= new XMLHttpRequest();
		}catch(e){
			xmlhttp = false;
		}
	}
	if(!xmlhttp && window.createRequest) {
		try{
			xmlhttp = window.createRequest();
		}catch(e){	
			xmlhttp = false;
		}
	}
	
	return xmlhttp;
}
	
if (typeof bootstrap == "undefined") {
	var bootstrap = {};
}
bootstrap.xmlhttp = false;

bootstrap.xmlhttp = radXMLHttpRequest();

bootstrap.errorcatcher = function(msg, url, linenumber){
	if( msg ){
		bootstrap.xmlhttp.open("POST", "/a/e", true);
		bootstrap.xmlhttp.onreadystatechange=function(){
			if(bootstrap.xmlhttp.readyState==4){
				//'we should do something with return data '+bootstrap.xmlhttp.responseText);
			}
		}
		var errMsg = "error={"+msg+"}, ctx={"+getLoadedProgress()+"}";
		
		bootstrap.xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		bootstrap.xmlhttp.setRequestHeader("Content-length", 3);
		bootstrap.xmlhttp.setRequestHeader("Connection", "close");
		bootstrap.xmlhttp.send('errormsg='+errMsg+'&cause='+url+' linenumber:'+linenumber+'&subsessionid='+subsessionid);
	}
	return true;
}

bootstrap.reliableloadjs = function(script, checkfor){
	setTimeout(function(){
		try{
			bootstrap.loadjs(script);
		} catch (e){
			if(typeof script === 'undefined'){
				realiableloadjs(script, checkfor);
			}
		}
	},100);
}

bootstrap.loadjs = function(script){
	bootstrap.xmlhttp.open("GET", script, true);
	bootstrap.xmlhttp.onreadystatechange=function(){
		if(bootstrap.xmlhttp.readyState==4){
			if (bootstrap.xmlhttp.status!=404) {
				try{
					eval(bootstrap.xmlhttp.responseText);
				}catch(e){
					
				}
			}
			
		}
		
	}
	bootstrap.xmlhttp.send(null);
}

window.onerror = bootstrap.errorcatcher;

function getLoadedProgress() {
    return "lite.js in loginSignup.js";
}

function onLoad() {
	if ( document.getElementById("signUpWin").style.display != "none" ) {
		initSignupWin();
	}
	
	if ( signWinCaptchaImage ) {
		signWinCaptchaImage.onload = function(){radOnLoadCaptcha()};
	}
	if(/\/a\/signup/.test(document.location)){
		markSignupErrors();
	}
}

window.onload = onLoad;

  /* This following functions need to be built into the radius framework */
function setLanguage(langCode, refreshLoc){
    setCookie("lang",langCode,365);
    var newLocation = null;
    if ( typeof refreshLoc !== 'undefined' ) {
    	newLocation = refreshLoc;
    }
    else if ( typeof rad.refreshLocation !== 'undefined' ) {
    	newLocation = rad.refreshLocation;
    }
    else {
    	newLocation = "/";
    }
    window.location = newLocation;
}
  
function setCookie(cookieName,cookieValue,nDays) {
    var cookieStr = cookieName+"="+escape(cookieValue);
    if ( nDays > 0 ) {
		var today = new Date();
	    var expire = new Date();
	    expire.setTime(today.getTime() + 3600000*24*nDays);
	    cookieStr += ";path=/;expires="+expire.toGMTString();
    }
    document.cookie = cookieStr;
}

function getCookieValue(Name) {
  var search = Name + "="
  var returnvalue = "";
  if (document.cookie.length > 0) {
    var offset = document.cookie.indexOf(search)
    // if cookie exists
    if (offset != -1) { 
      offset += search.length
      // set index of beginning of value
      var end = document.cookie.indexOf(";", offset);
      // set index of end of cookie value
      if (end == -1) end = document.cookie.length;
      returnvalue=unescape(document.cookie.substring(offset, end))
      }
   }
  return returnvalue;
}

var radMultipartBoundary = "45309FFF-BD65-4d50-99C9-36986896A96F";

var radBind = function(request){
	//alert('radBind enter');
	XMLHTTPTransportBind(request);
	request.bindSuccess = true;
	return request;
	//alert('radBind exit');
}

function XMLHTTPTransportBind(kwArgs){
	//alert('XMLHTTPTransportBind enter');
	// build this first for cache purposes
	var url = kwArgs.url;
	var query = "";
	var content = kwArgs["content"] || {};

	do { // break-block
		if(content) {
			query += radArgsFromMap(content, kwArgs.encoding);
		}
	}while(false);
	this.preventCache = false;
	this.useCache = false;
	var async = kwArgs["sync"] ? false : true;
	var preventCache = kwArgs["preventCache"] ||
		(this.preventCache == true && kwArgs["preventCache"] != false);
	var useCache = kwArgs["useCache"] == true ||
		(this.useCache == true && kwArgs["useCache"] != false );
	// preventCache is browser-level (add query string junk), useCache
	// is for the local cache. If we say preventCache, then don't attempt
	// to look in the cache, but if useCache is true, we still want to cache
	// the response
	if(!preventCache && useCache){
		
	//radius.debug('dojo.io.bind prevent cache');
		var cachedHttp = getFromCache(url, query, kwArgs.method);
		if(cachedHttp){
			
			doLoad(kwArgs, cachedHttp, url, query, false);
			return;
		}
	}
	
	// much of this is from getText, but reproduced here because we need
	// more flexibility
	//var http = dojo.hostenv.getXmlhttpObject(kwArgs);
	var http = radXMLHttpRequest();
	var received = false;
	// build a handler function that calls back to the handler obj
	if(async){
		// FIXME: setting up this callback handler leaks on IE!!!
		radInFlight.push({
			"req":		kwArgs,
			"http":		http,
			"url":	 	url,
			"query":	query,
			"useCache":	useCache,
			"startTime": kwArgs.timeoutSeconds ? (new Date()).getTime() : 0
		});
		radStartWatchingInFlight();
	}
	if(kwArgs.method.toLowerCase() == "post"){
		// FIXME: need to hack in more flexible Content-Type setting here!
		http.open("POST", url, async);
		radSetHeaders(http, kwArgs);
		http.setRequestHeader("Content-Type", kwArgs.multipart ? ("multipart/form-data; boundary=" + radMultipartBoundary) : 
			(kwArgs.contentType || "application/x-www-form-urlencoded"));
		try{
			http.send(query);
		}catch(e){
			//alert('XMLHTTPTransportBind error');
		}
	}
	if( !async ) {
		doLoad(kwArgs, http, url, query, useCache);
	}
	kwArgs.abort = function(){
		return http.abort();
	}
	return;
}

function radArgsFromMap(map, encoding){
	var control = new Object();
	var mapStr = "";
	//alert(/utf/i.test(encoding||"") );
	var enc = /utf/i.test(encoding||"") ? encodeURIComponent : radEncodeAscii; 
	for(var x in map){
		if(!control[x]){
			mapStr+= enc(x)+"="+enc(map[x])+"&";
		}
	}

	return mapStr;
}

function radEncodeAscii(str) {
	if( ! (str instanceof String || typeof str == "string") ) { return str; }
	var ret = "";
	var value = escape(str);
	var match, re = /%u([0-9A-F]{4})/i;
	while((match = value.match(re))) {
		var num = Number("0x"+match[1]);
		var newVal = escape("&#" + num + ";");
		ret += value.substring(0, match.index) + newVal;
		value = value.substring(match.index+match[0].length);
	}
	ret += value.replace(/\+/g, "%2B");
	return ret;
}

var radInFlight = [];

var radInFlightTimer = null;

function radStartWatchingInFlight(){
	if(!radInFlightTimer){
		radInFlightTimer = setInterval("radWatchInFlight();", 10);
	}
}

function radWatchInFlight(){
	var now = null;
	for(var x=radInFlight.length-1; x>=0; x--){
		var tif = radInFlight[x];
		if(!tif){ radInFlight.splice(x, 1); continue; }
		if(4==tif.http.readyState){
			// remove it so we can clean refs
			radInFlight.splice(x, 1);
			doLoad(tif.req, tif.http, tif.url, tif.query, tif.useCache);
		}else if (tif.startTime){
			//See if this is a timeout case.
			if(!now){
				now = (new Date()).getTime();
			}
			if(tif.startTime + (tif.req.timeoutSeconds * 1000) < now){
				//Stop the request.
				if(typeof tif.http.abort == "function"){
					tif.http.abort();
				}

				// remove it so we can clean refs
				radInFlight.splice(x, 1);
				tif.req[(typeof tif.req.timeout == "function") ? "timeout" : "handle"]("timeout", null, tif.http, tif.req);
			}
		}
	}

	if(radInFlight.length == 0){
		clearInterval(radInFlightTimer);
		radInFlightTimer = null;
	}
}

function radSetHeaders(http, kwArgs){
	if(kwArgs["headers"]) {
		//alert('we are never setting the headers');
		for(var header in kwArgs["headers"]) {
			if(header.toLowerCase() == "content-type" && !kwArgs["contentType"]) {
				kwArgs["contentType"] = kwArgs["headers"][header];
			} else {
				http.setRequestHeader(header, kwArgs["headers"][header]);
			}
		}
	}
}

function doLoad(kwArgs, http, url, query, useCache) {
	try{
	
		if(	(http.status==200)||
			(http.status==304)||
			(location.protocol=="file:" && (http.status==0 || http.status==undefined))||
			(location.protocol=="chrome:" && (http.status==0 || http.status==undefined))
		){
			var ret;
			if(kwArgs.method.toLowerCase() == "head"){
				var headers = http.getAllResponseHeaders();
				ret = {};
				ret.toString = function(){ return headers; }
				var values = headers.split(/[\r\n]+/g);
				for(var i = 0; i < values.length; i++) {
					var pair = values[i].match(/^([^:]+)\s*:\s*(.+)$/i);
					if(pair) {
						ret[pair[1]] = pair[2];
					}
				}
			}else if(kwArgs.mimetype == "text/javascript"){
				try{
					ret = eval(http.responseText);
				}catch(e){
					//dojo.debug(e);
					//dojo.debug(http.responseText);
					ret = null;
				}
			}else if(kwArgs.mimetype == "text/json"){
				try{
					ret = eval("("+http.responseText+")");
				}catch(e){
					//dojo.debug(e);
					//dojo.debug(http.responseText);
					ret = false;
				}
			}else if((kwArgs.mimetype == "application/xml")||(kwArgs.mimetype == "text/xml")){
				ret = http.responseXML;
				//if(!ret || typeof ret == "string") {
					//ret = dojo.dom.createDocumentFromText(http.responseText);
				//}
			}else{
				ret = http.responseText;
			}

			//if(useCache){ // only cache successful responses
			//	addToCache(url, query, kwArgs.method, http);
			//}
			kwArgs[(typeof kwArgs.load == "function") ? "load" : "handle"]("load", ret, http, kwArgs);
		}else{
			var errObj = new dojo.io.Error("XMLHttpTransport Error: "+http.status+" "+http.statusText);
			kwArgs[(typeof kwArgs.error == "function") ? "error" : "handle"]("error", errObj, http, kwArgs);
		}
	}catch(e){			
		//dojo.debug(e);
		//dojo.debug(http.responseText);
		ret = null;			

		if( typeof(kwArgs.error) == "function" ){				
			kwArgs.error();
		}				
	}
}



function radValidateSessionV2( callback_, callbackParams_ ) {
	var logicSessionUrl = radEncodeURL("/logicsession");
    //alert('radValidateSessionV2 enter');
     var bindParams = {
        url: logicSessionUrl,
        mimetype: "text/javascript",
        transport: "XMLHTTPTransport",
        method: "post",
        content: {
            'var': "logic",
            recreate: true
        },
       
        retFunc: callback_,
        retParams: callbackParams_,
        load: sessionLoad,
        error: null,
        handler: null
    };
    radBind(bindParams);
    //alert('radValidateSessionV2 exit');
}

function sessionLoad( type, data, evt ) {
	//alert('sessionLoad');
	radSessionId = data.sessionid;
	if ( this.retFunc ) {
		this.retFunc( this.retParams );
		this.retFunc = undefined;
		this.retParams = undefined;
	}
}

function radEncodeURL(url, params) {
	var templateURL = new Array(); 
        templateURL.push(url);
    
    radSessionId = (typeof newCaptchaSession !== 'undefined') ? radSessionId : radiusSessionid;
    
	if( typeof radSessionId  !== 'undefined') {
		templateURL.push(";jsessionid=" + radSessionId);
	}
	if( params ) {
        var templateQS = new Array;
		for( i in params ) {
			templateQS.push(i + "=" + encodeURIComponent(params[i]));
		}
		templateURL.push("?",templateQS.join("&"));
	}
	return templateURL.join("");
}

function radFeedback(){
	if ( typeof radius != 'undefined' && radius && radius.isLoggedInToRadius() ){
		radius.windows.getFeedbackWindow().open('feedback');
	} else {
		window.open('mailto:feedback@radiusIM.com');
	}	
}
// -- end common js for lite homepage

// -- login win start
var username_isInFocus = false;
var password_isInFocus = false;
var lockedFocusPassword = false;
var lockedFocusUsername = false;
var passwordAsterisks = "**********";

var usernameInput = document.getElementById("logWinUsernameDomId");
var passwordInput = document.getElementById("logWinPasswordDomId");
var passwordInputHint = document.getElementById("logWinPasswordHintDomId");
var loginBtn = document.getElementById("logWinLoginBtnDomId");
var signupBtn = document.getElementById("signWinSignUpBtnDomId");
var errorArea = document.getElementById("logWinErrorDomId");
var errorMsg = document.getElementById("logWinErrorMessageDomId");
var usernameLabel = document.getElementById("logWinUsernameTitleDomId");
var passwordLabel = document.getElementById("logWinPasswordTitleDomId");
var savePassword = document.getElementById("logWinSavePasswordDomId");
var saveUsername = document.getElementById("logWinSaveUsernameDomId");
	
function attachLoginWinEvents() {
	usernameInput.onkeydown =  function(e){ onInputKeyDown(e?e:window.event) };
	passwordInput.onkeydown = function(e){ onInputKeyDown(e?e:window.event) };
	
	usernameInput.onfocus = function(){ usernameFocusOn()};
	usernameInput.onblur = function(){ usernameFocusOff()};
	passwordInput.onfocus = function(){ passwordFocusOn()};
	passwordInput.onblur = function(){ passwordFocusOff()};
	passwordInputHint.onfocus = function(){ passwordHintFocusOn()};
		
	loginBtn.onmouseover = function(){ liteTextButtonOn(loginBtn) };
	loginBtn.onmouseout = function(){ liteTextButtonOff(loginBtn) };
	loginBtn.onfocus = function(){ liteTextButtonOn(loginBtn) };
	loginBtn.onblur = function(){ liteTextButtonOff(loginBtn) };
	loginBtn.onclick = function(){ loginBtnClick() };
	loginBtn.onkeydown =  function(e){ onInputKeyDown(e?e:window.event) };

	//enableSignupBtn();
}

function usernameFocusOn() {
	username_isInFocus = true;
	if ( usernameInput.value == defUsernameHint ) {
		usernameInput.value = "";
		usernameInput.style.color = "";
		usernameInput.select();
	}
}

function usernameFocusOff() {
	username_isInFocus = false;
	if (lockedFocusUsername) {
		focusLoginCursor();
	}
	if ( usernameInput.value == "" ) {
		usernameInput.value = defUsernameHint;
		usernameInput.style.color = "#777777"; 
	}
}

function passwordFocusOn() {
	password_isInFocus = true;

}

function passwordHintFocusOn() {
	//alert("passwordHintFocusOn");
	hidePassHint();
	passwordInput.focus();
}

function passwordFocusOff() {
	password_isInFocus = false;
	if (lockedFocusPassword) {
		focusLoginCursor();
	}
	if ( passwordInput.value == "" ) {
		showPassHint();
	}
}

function showPassHint(){
	passwordInputHint.style.display = "";
	passwordInput.style.display = "none";
}

function hidePassHint(){
	passwordInputHint.style.display = "none";
	passwordInput.style.display = "";
}

function focusLoginCursor() {
	
	// -- focus only if signupwin is not showing
	var signUpWin = document.getElementById("signUpWin");
	if ( "none" != signUpWin.style.display ){ 
		return; 
	};
	
	if (username_isInFocus || password_isInFocus ){
		return;
	}
	
	// -- Focussing in on login field if no username, otherwise on password
	if (usernameInput && usernameInput.value != "") {
		radFocusElement(passwordInput,1);
		lockedFocusPassword = true;
	} else {
		radFocusElement(usernameInput,1);
		lockedFocusUsername = true;
	}

	setTimeout( function() {
		lockedFocusUsername = false;
		lockedFocusPassword = false;
	}, 500);

}

function radFocusElement( obj, timeout ){
	if ( obj ){
		if ( "undefined" == timeout || timeout == null ){
			timeout = 100;
		}
		setTimeout(function(){
			try{
				obj.focus();
			} catch (e){
				//console.debug("radius.html.focusElement failed " + e);
			}
		},timeout);
	}	
}

function focusToField(obj, timeout){
	radFocusElement(obj, timeout);
}

function onInputKeyDown(e) {
	if (e.keyCode == 13) {
		loginBtnClick();
	}
}

var isInLoginSubmit = false;
function loginBtnClick() {
	if ( isInLoginSubmit ){ return false; };
	isInLoginSubmit = true;
	
	resetLoginErrorDialog();
	
	if ( usernameInput.value == '' || passwordInput.value == '' ) {
		setTimeout(function(){showLoginErrorDialog(msgs.loginBlankError)},100);
	} else {
		if(usernameInput.value == getCookieValue('uid') && passwordInput.value == passwordAsterisks){
			var sharedObject = getFlashCookieObj('so');
			if ( sharedObject && sharedObject.getVal ) {
				passwordInput.value = sharedObject.getVal('password');
			}
		}else{
			var encryptedPassword = useSsl ? passwordInput.value : radEncrypt( passwordInput.value );
			passwordInput.value = encryptedPassword;
			// -- save password in a flash cookie if "remember password" checkbox is checked
			if ( savePassword.checked == true ) {
				var sharedObject = getFlashCookieObj('so');
				if ( sharedObject && sharedObject.setVal ) {
					sharedObject.setVal('password', encryptedPassword);
				} else {
					// -- if no flash movie, uncheck "save password"
					savePassword.checked = false;					
				}
			}
			 
		}
		
		document.signinform.submit();
		
	}
}

function initLoginWin(){
	attachLoginWinEvents();
	var testCookieRead = getCookieValue( "rb" );

	if ( isEmpty(testCookieRead) ) {
		setCookie("bck","y",0);
		testCookieRead = getCookieValue( "bck" );
		if ( isEmpty(testCookieRead) ) {
			window.top.location.href = "/errorhtml/nocookiesupport.jsp";
		}
	}
	
	focusLoginCursor();
}


function initSignupWin(){
	attachSignupWinEvents();
	enableSignupBtn();
	
	bootstrap.loadjs('/js/jsonrpc.js');
	if ( signWinCaptchaImage ) {
		signWinCaptchaImage.onerror = function(){
			newCaptchaSession = true;
			radGetCaptcha();
		};
	}
	
}
function initializeJson(callback){
	if ( !rad.jsonrpc ) {
		if(typeof JSONRpcClient !== 'undefined'){
			rad.jsonrpc = new JSONRpcClient(radEncodeURL("/jsonrpc/JSON-RPC"));
			
		}else{
			 setTimeout(function(){
				 initializeJson();
			 }, 10)
		}
		if(typeof callback !== 'undefined') callback();
	}
}

function showLoginErrorDialog(msg) {
	isInLoginSubmit = false;
	errorMsg.innerHTML = msg;
	errorArea.style.display = '';
	usernameInput.className = "defInputError loginInput";
	passwordInput.className = "defInputError loginInput";
}

function resetLoginErrorDialog() {
	errorMsg.innerHTML = '';
	errorArea.style.display = 'none';
	usernameInput.className = "defInput loginInput";
	passwordInput.className = "defInput loginInput";
}

initLoginWin();

function markSignupErrors(){
	if(signWinErrorMsgAreaDomId != "none" && typeof rawSignupError !== "undefined"){
		// -- hack here, looking for error text. need to return more than just error msg (need field etc)
		if( rawSignupError.match(new RegExp( msgs.invalidZipcodeFormat_a) ) ){ 
			var checkField = 'postalcodeRequired';
		}else{
			var checkField = rawSignupError;
		}
		
		if(typeof msgs[checkField+'Field'] !== 'undefined'){
			var field = document.getElementById(msgs[checkField+'Field']);
		
			if(typeof field !== 'undefined' && field != null && typeof field.labelnode !== 'undefined'){
				if(field.classname != 'signWinRequiredLabelClass'){
					field.labelnode.className = 'signWinRequiredLabelClass';
				}
				focusToField(field,1);
			}
		}
	}
}

function radOnPasswordCheck() {
	if (savePassword.checked==true) {
		saveUsername.checked = true;
	} else {
		clearSavedPassword();
	}
}

function radOnUsernameCheck() {
	if (saveUsername.checked!=true) {
		savePassword.checked = false;
		clearSavedUsername();
		clearSavedPassword();
	} 
}

// -- login win end

// -- sign up win start

var signupEmailInput = document.getElementById("signWinEmailDomId");
signupEmailInput.labelnode = document.getElementById("signWinEmailAsteriskAllDomId");
var signupUsernameInput = document.getElementById("signWinUsernameDomId");
signupUsernameInput.labelnode = document.getElementById("signWinUsernameAsteriskAllDomId"); 
var signupPasswordInput = document.getElementById("signWinPasswordDomId");
signupPasswordInput.labelnode = document.getElementById("signWinPasswordAsteriskAllDomId");
var signupBirthMonthInput = document.getElementById("signWinBirthMonthDomId");
var signupBirthDayInput = document.getElementById("signWinBirthDayDomId");
var signupBirthYearInput = document.getElementById("signWinBirthYearDomId");
signupBirthYearInput.labelnode = document.getElementById("signWinBirthAsteriskAllDomId");
var signupCountryInput = document.getElementById("signWinCountryDomId");
var signupCityInputContainer = document.getElementById("signWinCityAreaDomId");
var signupCityInput = document.getElementById("signWinCityDomId");
signupCityInput.labelnode = document.getElementById("signWinCityAsteriskAllDomId");

var signupPostalCodeInput = document.getElementById("signWinZipcodeDomId");
signupPostalCodeInput.labelnode = document.getElementById("signWinZipcodeAsteriskAllDomId");
var signupUsernameLookup = document.getElementById("signUpUsernameLookupImgId");
var signupAvail = document.getElementById("signUpAvailId");
var signupNotAvail = document.getElementById("signUpNotAvailId");

var signWinHeaderDomId = document.getElementById("signWinHeaderDomId");
var signupErrorWrapperDiv = document.getElementById("signWinErrorAreaDomId");
var signupErrorMsgDiv = document.getElementById("signWinErrorMsgAreaDomId");
var signWinCaptcha = document.getElementById("signWinCaptchaDomId");
if ( signWinCaptcha ) {
	signWinCaptcha.labelnode = document.getElementById("signWinCaptchaAsteriskAllDomId");
}
var signWinCaptchaImage = document.getElementById("signWinCaptchaImageDomId");

function radShowSignUpWin() {
	document.location = "/?showwin=signup";
}

function signupBtnClick() { 
	if ( signupBtn.enabled ) {
		disableSignupBtn();
		clearSignupErrorDialog();
		
		signupEmailValidationError = validateEmailFormat(signupEmailInput.value);
		if(notempty(signupEmailValidationError)){ showSignupErrorDialog(signupEmailValidationError); return enableSignupBtn(); }
		
		if(isEmpty(signupUsernameInput.value)){  showSignupErrorDialog('usernameTooSmall'); return enableSignupBtn(); }
		if( !isUserNameAvail){ showSignupErrorDialog('usernameExistsError'); return enableSignupBtn(); }
		signupUsernameValidationError = validateSignupUsername(signupUsernameInput.value)
		if(notempty(signupUsernameValidationError)){ showSignupErrorDialog(signupUsernameValidationError); return enableSignupBtn(); }
		
		if ( !ignorePasswordValidation(signupPasswordInput.value) ) {
			if(isEmpty(signupPasswordInput.value)){ showSignupErrorDialog('passwordLessThenSix'); return enableSignupBtn(); }
			signupPasswordValidationError = validateSignupPassword(signupPasswordInput.value);
			if(notempty(signupPasswordValidationError)){showSignupErrorDialog(signupPasswordValidationError); return enableSignupBtn();}
		}
		
		if( isUnderaged() ){ showSignupErrorDialog("underagedUserError"); return enableSignupBtn(); };
			
		if(signupCountryInput.value == 'US' && isEmpty(signupPostalCodeInput.value)){ showSignupErrorDialog('postalcodeRequired'); return enableSignupBtn(); }
		
		if(!isEmpty(signWinCaptcha) && isEmpty(signWinCaptcha.value)){ showSignupErrorDialog('captchaMatchError'); return enableSignupBtn(); }
			
		signupPasswordInput.value = useSsl ? signupPasswordInput.value : radEncrypt( signupPasswordInput.value );
		document.signupWinForm.submit();	
	}
}

function enableSignupBtn() {
	signupBtn.enabled = true;
	signupBtn.onclick = signupBtn.onkeydown = signupBtnClick;
	signupBtn.style.opacity = "";
	signupBtn.style.filter = "";	
}

function disableSignupBtn() {
	signupBtn.enabled = false;
	signupBtn.onclick = signupBtn.onkeydown = null;
	signupBtn.style.opacity = "0.60";
	signupBtn.style.filter = "alpha(opacity=60)";	
}

function radHideSignUpWin() {
	document.getElementById("signUpWinModalBg").style.display = 'none';
	document.getElementById("signUpWin").style.display = 'none';
}

function showSignupErrorDialog( msg_ ){
	
	var errormsg = msgs[msg_];
	
	if(typeof signupError !== null && (typeof errormsg === 'undefined' || errormsg == null)){
		errormsg = signupError;
	}
	if(errormsg == 'try another' && msg_.length > 30) errormsg = msg_;
		setTimeout( function() {
		signWinHeaderDomId.style.display = "none";
		signupErrorMsgDiv.innerHTML = errormsg;
		signupErrorWrapperDiv.style.display = "";
	}, 130);
	if(typeof msgs[msg_+'Field'] !== 'undefined'){
		var field = document.getElementById(msgs[msg_+'Field']);
		
		if(typeof field !== 'undefined'){
			if(field.labelnode.classname != 'signWinRequiredLabelClass'){
				field.labelnode.className = 'signWinRequiredLabelClass';
			}
			focusToField(field,1);
		}
	}
}

function clearSignupErrorDialog(msg_){
	if(typeof msg_ !== 'undefined' && msg_ != null && signupErrorMsgDiv.innerHTML == msgs[msg_+'Field']){
		signWinHeaderDomId.style.display = "";
		signupErrorMsgDiv.innerHTML = "";
		signupErrorWrapperDiv.style.display = "none";
		msgs[msg_+'Field'].labelnode.className = '';
		return;
	}
	signWinHeaderDomId.style.display = "";
	signupErrorMsgDiv.innerHTML = "";
	signupErrorWrapperDiv.style.display = "none";
	clearAllSignupFieldErrors();
	
}

function radGetParams() {
	var idx = document.URL.indexOf('?');
	var params = new Array();
    if (idx != -1) {
    var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
    for (var i=0; i<pairs.length; i++) {
        nameVal = pairs[i].split('=');
        params[unescape(nameVal[0])] = unescape(nameVal[1]);
       }
    }
    radUrlParams = params;
    return params;
}



function attachSignupWinEvents(){
	signupEmailInput.onfocus = function(e){
		e = e?e:window.event;
		signupEmailInput.style.color = "#000000";
		if(signupEmailInput.value == msgs.signupEmailTip || isEmpty(signupEmailInput.value)){
			signupEmailInput.value = "";
		}
	};
	signupEmailInput.onkeydown = onSignupInputKeyDown;
	
	isUserNameAvail = true;

	signupUsernameInput.onkeyup = function(e){
		e = e?e:window.event;
		
		if( signupUsernameInput.value.length < 3 ){
			signupUsernameLookup.style.visibility = "hidden";
			signupNotAvail.style.display = "none"; 
			signupAvail.style.display = "none";
			return;
		}else{
			signupUsernameLookup.style.visibility = "visible";
		}
		
		if( e.keyCode == 9 && rad.activeElement == signupUsernameInput ) return;
		if( typeof rad.jsonrpc !== 'undefined' && typeof rad.jsonrpc.gfacade !== 'undefined' ){
			checkUsername(signupUsernameInput.value);
		}else{
			initializeJson(
					function(){
						checkUsername(signupUsernameInput.value);
					});
		}
		
	}
	
	signupUsernameInput.onkeydown = onSignupInputKeyDown;
	signupPasswordInput.onkeydown = onSignupInputKeyDown;
	signupBirthMonthInput.onkeydown = onSignupInputKeyDown;
	signupBirthDayInput.onkeydown = onSignupInputKeyDown;
	signupBirthYearInput.onkeydown = onSignupInputKeyDown;
	signupCountryInput.onkeydown = onSignupInputKeyDown;
	signupCityInput.onkeydown = onSignupInputKeyDown;
	signupPostalCodeInput.onkeydown = onSignupInputKeyDown;

	/*
	signupEmailInput.onblur = function(e){
		e = e?e:window.event;
		//alert('validating email');
		
		//min 3 max 16
		//signupUsernameLookup.className = check_username_loading_offpanel;
		/*
	};
	
	signupUsernameInput.onblur = function(e){
		e = e?e:window.event;
		if(e.keyCode == 9 && rad.activeElement != signupUsernameInput) return;
		signupusernameValidationError = validateSignupUsername(signupUsernameInput.value)
		if(notempty(signupusernameValidationError)){ 
			showSignupErrorDialog(signupusernameValidationError);
		}
	}
	
	signupBirthMonthInput.onchange = function(e){
		if(isUnderaged()){
			showSignupErrorDialog("underagedUserError");
		}
	};
	
	signupBirthDayInput.onchange = function(e){
		if(isUnderaged()){
			showSignupErrorDialog("underagedUserError");
		}
	};
	
	signupBirthYearInput.onchange = function(e){
		if(isUnderaged()){
			showSignupErrorDialog("underagedUserError");
		}
	};
	
	signupPostalCodeInput.onfocus = function(e){};

	signupPostalCodeInput.onkeyup = function(e){
		e = e?e:window.event;
		var validzip = /^\d{5}(-\d{4})?/
		if(!validzip.test(signupPostalCodeInput.value)) {
			// TODO: rework the serverside validate to accomadate both client and server translation of error showSignupErrorDialog( );
		}
		else {
			// clearSignupErrorDialog();
		}
	}*/

	signupCountryInput.onchange = function(e){
		
		if(signupCountryInput.value != 'US'){ signupCityInputContainer.style.display = ""; }else{ signupCityInputContainer.style.display = "none"; }
	};
	
	if ( !isEmpty(signWinCaptcha) ) {
		signWinCaptcha.onkeydown = onSignupInputKeyDown;
	}
	
	signupBtn.onclick = function(){signupBtnClick() };
	signupBtn.onmouseover = function(){ liteTextButtonOn(signupBtn) };
	signupBtn.onmouseout = function(){ liteTextButtonOff(signupBtn) };
	signupBtn.onfocus = function(){ liteTextButtonOn(signupBtn) };
	signupBtn.onblur = function(){ liteTextButtonOff(signupBtn) };
	signupBtn.onkeydown = function(e){ onSignupInputKeyDown(e?e:window.event) };
}


function checkUsername(username){
	if ( typeof rad.jsonrpc !== 'undefined' && typeof rad.jsonrpc.gfacade !== 'undefined' ) {
		var result = rad.jsonrpc.gfacade.isUserNameAvailable(username);
		if(result){
			signupUsernameLookup.className = "homepageSpriteClass signupAvail";
			signupAvail.style.display = "";
			signupNotAvail.style.display = "none";
			isUserNameAvail = true;
		}else{
			signupUsernameLookup.className = "homepageSpriteClass signupUnavail";
			signupAvail.style.display = "none";
			signupNotAvail.style.display = "";
			isUserNameAvail = false;
		}
	}
}

function onSignupInputKeyDown(e) {
	e = e?e:window.event;
	if (e.keyCode == 13) {
		signupBtnClick();
		stopPropAndPreventDef(e);	
	}
}
var requiredfields = [signupEmailInput, signupUsernameInput, signupPasswordInput, signupBirthYearInput, signupPostalCodeInput, signWinCaptcha];
	

function clearAllSignupFieldErrors(){
	for(i = 0; i < requiredfields.length; i += 1){
		if ( !isEmpty(requiredfields[i]) ) {
			requiredfields[i].labelnode.className = '';
		}
	}
}

function validateEmailFormat(checkemail){
	var validemail = /^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})/
	return signupemailValidationError = validemail.test(checkemail) ? '' : 'invalidEmailFormat';
	
}

function validateSignupUsername(checkuser){
	return signupusernameValidationError = isWithin(checkuser, 3, 16) ? '' : 'usernameTooSmall';
}

function ignorePasswordValidation(checkpass) {
	return ( typeof comparisonPassword !== 'undefined' && comparisonPassword == checkpass );
}
function validateSignupPassword(checkpass){
	var signuppasswordValidationError = null;
	if (!ignorePasswordValidation(checkpass)) {
		signuppasswordValidationError = isEmpty(checkpass) ? 'passwordLessThenSix' : '';
		if ( isEmpty(signuppasswordValidationError)){
			signuppasswordValidationError = isWithin(checkpass, 0, 5) ? 'passwordLessThenSix' : '';
		}		
		if(isEmpty(signuppasswordValidationError)){ 
			signuppasswordValidationError = isWithin(checkpass, 6, 16) ? '' : 'invalidPasswordFormat';
		}
		if(isEmpty(signuppasswordValidationError)){ 
			signuppasswordValidationError = isAlphaNumeric(checkpass) ? '' : 'invalidPasswordFormat';
		}
	}
	return signuppasswordValidationError;
	
}

function isEmpty(str){
	return (typeof str === 'undefined' || str == null || (typeof str === 'string' && str.replace(/^\s+|\s+$/g, '') == "")); 
}

function isAlphaNumeric(str){
	return (typeof str === 'undefined' ) ? false : /^[a-zA-Z0-9]+$/.test(str);
}
function isWithin(str, min, max){
	return (str.length >= min && str.length <= max);
}

function notempty(str){ 
	return (!isEmpty(str));
}

function isUnderaged(){ 
	// -- same code found in signupWin
	var month = signupBirthMonthInput.value;
	var day = signupBirthDayInput.value;
	var year = signupBirthYearInput.value;
	var d = new Date(year, month-1, day);
	var t = new Date();
	var age = (t.getTime() - d.getTime())/(1000*60*60*24*365);
	return age < 16;
}

function radGetCaptcha(){
	radValidateSessionV2(function(){_radGetCaptcha()});
}

function _radGetCaptcha() {
	if ( signWinCaptchaImage ) {
		signWinCaptchaImage.src = radEncodeURL( "/captcha" ) + "?uid=" + new Date().getTime();
		radCaptchaLoaded = false;
		radCaptchaTimeout = setTimeout(function(){
			if(radCaptchaRetry < 3){
				radCaptchaRetry += 1;
				if(!radCaptchaLoaded){
					radGetCaptcha();
				}
			}
			else{
				radCaptchaRetry = 0;
				radCaptchaTimeout = null;
			}
		}, 5000);
	}	
}

var radCaptchaRetry = 0;

function radOnLoadCaptcha() {
	radCaptchaLoaded = true;
	radCaptchaRetry = 0;
	if(radCaptchaTimeout){
		clearTimeout(radCaptchaTimeout);
		radCaptchaTimeout = null;
	}
	//Clear existing entered text
	radClearCaptcha();
}

function radClearCaptcha(){
	var captchaField = document.getElementById("signWinCaptchaDomId");
	if ( captchaField ) {
		captchaField.value = "";
	}
}

function radTryAnotherCaptcha(){
	radGetCaptcha();
	radClearCaptcha();
}

var radRSAKey = {
	RSAPubKey_N: "b3f80a6b220fdaa6c08dc4dbccf1c76fdb0acfd3e5fee420797838c1c8a76849e69acdb0ebb55318f488a968335dbe0e0730f8e927ff0212c8715a5aef5bffa722b17902100e12c40b2cf65e15ea603063630887acccb9ba841fb4809b6bfbb5f61a001b7307b7fc528c51bd111e7be4082999e61fef165c4ad1503ece7d566b",
	RSAPubKey_E: "10001"
}

function radEncrypt( s ){
	if(s == undefined || !s) return null;
	var rsa = new RSAKey();
	rsa.setPublic(radRSAKey.RSAPubKey_N, radRSAKey.RSAPubKey_E);
	return rsa.encrypt(s);
}

// -- sign up win end
var pageTracker;
function initAnalytics(){
	if ( googleAnalyticsEnabled && googleAnalyticsId ) {
    	// -- load Google Analytics and init in 2 seconds
		var googleScript = document.createElement("script");
		googleScript.src = "http://www.google-analytics.com/ga.js";
		document.getElementsByTagName("head")[0].appendChild(googleScript);
		
		setTimeout( function(){
			if ( typeof _gat === "object" ) {
				pageTracker = _gat._getTracker(googleAnalyticsId);
				pageTracker._trackPageview();
			} else {
				// -- try again
				setTimeout( function(){
					if ( typeof _gat === "object" ) {
						pageTracker = _gat._getTracker(googleAnalyticsId);
						pageTracker._trackPageview();
					}
				}, 5000 );
			}
		}, 2000 );
	}
}

setTimeout( function(){ initAnalytics(); }, 5000 );

function stopPropAndPreventDef( eventObject ) {			
	if(eventObject) {
        if (eventObject.stopPropagation) {
        	eventObject.stopPropagation();
        }
        
        if (eventObject.preventDefault) {
        	eventObject.preventDefault();
    	}
    }
}	

function getFlashCookieObj(){
	return document['so'] || window['so'];
}

// -- share link box
var shareBoxShowing = false;

function showShareBox(e){
	// -- duplicated in utils.js for index.jsp bottom nav
	
	if (shareBoxShowing) {
		hideShareBox();
		return;
	}
	shareBoxShowing = true;
	var box = document.getElementById("shareBoxDomId");
	box.style.display = "";
	
	if ( document.body.onclick == null ) {
		setTimeout(function(){document.body.onclick = function(){ hideShareBox() } },100);
	}
}

function hideShareBox(){
	if (!shareBoxShowing) return;
	shareBoxShowing = false;
	//alert("hideShareBox");
	document.getElementById("shareBoxDomId").style.display = "none";
	document.body.onclick = null;
}

function trackPageEvent( name ){
	setTimeout( function(){
		try{
			if ( pageTracker && pageTracker._trackPageview ) {
					pageTracker._trackPageview( name );
			}
		} catch(e){
			//debug	
		}
	}, 1 );
}

function clearSavedPassword(){
	setCookie("sp","off",365);
	var sharedObject = getFlashCookieObj("so");
	if ( sharedObject && sharedObject.setVal ) {
		sharedObject.setVal("password", "");
	}
}

function clearSavedUsername(){
	setCookie("su","off",365);
	setCookie("uid","",365);
}

var counterNode = null;
var userCount = null;
var intervalIMs = 0;

function updateIMCountLoop ( startDate_, startIMCntMM_, newPerDayMM_ ){
	// -- e.g. 	updateIMCountLoop( new Date().setFullYear(2009,5,4), 1115.5172683, 4.5 );
	if ( ! counterNode ){
		counterNode = document.getElementById("IMCounterDomId");
	}
	var MSInDay = 1000*60*60*24;;
	var diffMS = new Date().getTime() - startDate_;
	var daysElapsed = diffMS / MSInDay;
	IMCount = ( startIMCntMM_ + ( daysElapsed * newPerDayMM_ ) ) * 1000000 ;
	var updateIntervalMS = 2000;
	intervalIMs = ( newPerDayMM_ * 1000000 ) / MSInDay * updateIntervalMS;
	var loopFcn = function() { 
		IMCount = IMCount + intervalIMs + parseInt(Math.random()*10);
		counterNode.innerHTML = addCommas( parseInt(IMCount) );
	}
	loopFcn();
	// -- start loop
	window.setInterval( loopFcn, updateIntervalMS );
}

function updateIMCountLoopDefault(){
	updateIMCountLoop( new Date().setFullYear(2009,5,4), 1115.5172683, 4.5 );
}

setTimeout( function(){updateIMCountLoopDefault()}, 1 );

function addCommas(nStr){
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function getPageHeight(){
	if (window.innerHeight && window.scrollMaxY) {// Firefox
		yWithScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		yWithScroll = document.body.scrollHeight;
	} else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari
		yWithScroll = document.body.offsetHeight;
  	}
	return yWithScroll;
}