// Preload the animated standby gif:
var standbyImg = new Image();
standbyImg.src = "/www2/javascript/ajax_loading.gif";
var loginFormFirstTime = true;
var loginFormString = "";

function showHideScrim(showOrHide) {

	try {
		if (showOrHide == "" || showOrHide == null) {
			if (scrim.style.visibility == "hidden" || scrim.style.visibility == "") {
				var newVis = "visible";
			} else {
				var newVis = "hidden";
			}
		} else {
			newVis = showOrHide;
		}
		/* New code to hide select lists that might muck-up the dhtml layer in IE: */
		if (newVis == "visible") {
			var formVis = "hidden";
		} else {
			var formVis = "visible";
		}
		showHideFormFields(formVis);
		/* End IE layer hack */

		var scrim = document.getElementById("scrim");

		// It is necessary to resize the scrim each time - otherwise the invisible
		// scrim will hide flash elements on the page and prevent them from being
		// clickable in FF:
		if (newVis == "visible") {
			scrim.className = 'visibleScrim';
			//scrim.style.class = 'visibleScrim';
			//scrim.style.height = document.body.scrollHeight + "px";
			//scrim.style.width = document.body.scrollWidth + "px";
		} else {
			scrim.className = 'hiddenScrim';
			//scrim.style.class = 'hiddenScrim';
			//scrim.style.height = "1px";
			//scrim.style.width = "1px";
		}
		scrim.style.visibility = newVis;
	} catch (e) {
		alert(e);
	}
}

function doUserLogin() {
	try {
		var userNam = document.getElementById("uname").value;
		var userPassword = document.getElementById("userPassword").value;
		var memberMe = document.getElementById("remem").checked;
	} catch (e) {
		alert(e);
	}
	if (userNam.length < 1 || userPassword.length < 1) {
		alert("username and password are both required - please correct and resubmit");

	} else {

		try {
			var formWrap = document.getElementById("loginFormWrapper");
			var im = document.createElement("img");
			im.setAttribute("src", "images/user_profile_login/idj_login_ajax_loading.gif");
			im.setAttribute("alt", "Please standby");
			im.setAttribute("border", "0");

			formWrap.innerHTML = "";
			formWrap.appendChild(im);
		} catch (e) {}

		var reqUrl = "/www2/user_profile/ajax_requests/login_handler.php";
		var onSuccessFunc = function(req) { handleLoginResponse(req, userPassword, memberMe); }
		var onErrorFunc = function(req) { alert('Error!\nStatusText='+req.statusText+'\nContents='+req.responseText); }
		var onTimeOutFunc = function(req) { alert('Timed Out!'); }
		
		var req = AjaxRequest.post({'url':reqUrl, 'userName':userNam, 'userPassword':userPassword, 'onSuccess': onSuccessFunc, 'onError': onErrorFunc, 'timeout':6000, 'onTimeout': onTimeOutFunc });
	}
	//return false;
} // End doUserLogin() function

function handleLoginResponse(reqObj, passwordString, setLongtermCookie) {
	try {
		var returnedObj = eval("(" + reqObj.responseText + ")");
		var formWrap = document.getElementById("loginFormWrapper");
		var tmp = formWrap.innerHTML;
		/*
		var im = document.createElement("img");
		im.setAttribute("src", "/www2/javascript/ajax_loading.gif");
		im.setAttribute("alt", "Please standby");
		im.setAttribute("border", "0");

		formWrap.innerHTML = "";
		formWrap.appendChild(im);
		*/
		if (returnedObj.type == "userProfile" && returnedObj.updatesRequired == 0) {
			var domainStr = location.host;
			domainArray = domainStr.split(".");
			domainArray.reverse();
			domainStr = "." + domainArray[1] + "." + domainArray[0];
			document.cookie = "idjupsessId=" + returnedObj.sessionId + "; path=/; domain=" + domainStr;
			document.cookie = "idjupsess=" + returnedObj.cipher + "; path=/; domain=" + domainStr;

			if (setLongtermCookie == true) {
				var expiry = new Date();
				expiry.setYear(expiry.getFullYear() + 1);
				document.cookie = "idjupsessremember=" + returnedObj.cipher + "; expires=" + expiry + "; path=/; domain=" + domainStr;
				//alert('here');
			}
			var cooks = document.cookie.split(';');
			var len = cooks.length;
			var tmp = "";
			var searchFor = "idjupsessreturnto=";

			for (var i=0; i<len; i++) {
				if (cooks[i].indexOf(searchFor) > -1) {
					tmp = cooks[i].substring(cooks[i].indexOf("http"));
				}
			} // for
			
			if (tmp == "") {
				window.location.reload();
			} else {
				var domainStr = location.host;
				domainArray = domainStr.split(".");
				domainArray.reverse();
				domainStr = "." + domainArray[1] + "." + domainArray[0];
				document.cookie = "idjupsessreturnto=; path=/; domain=" + domainStr;
				window.location.href = tmp;
				/*
				if (tmp == window.location.href) {
					// alert('reload');
					window.location.reload();	
				} else {
					//alert(tmp + ' - ' + window.location.href);
					window.location.href = tmp;
					//var tmp = window.location.href;
					//var tmpArr = tmp.split(".com");
					//window.location.href = tmpArr[1]; // + "?reload";		
				}
				*/
			}
		} else if (returnedObj.type == "userProfile" && returnedObj.updatesRequired == 1) {

			var innerStr = '<form name="profileCorrectionForm" method="post" action="http://' + location.host + '/www2/user_profile/correct.php?siteId=' + getSiteId() + '">';
			//var innerStr = '<form name="profileCorrectionForm" method="post" action="profile_corrections/index.php">';
			innerStr += '<input type="hidden" name="userName" value="' + returnedObj.userName + '" />';
			innerStr += '<input type="hidden" name="userPassword" value="' + passwordString + '" />';
			innerStr += '<input type="hidden" name="siteId" value="' + getSiteId() + '" />';
			innerStr += "</form>";
			innerStr += "You need to update your profile before logging in.<br /><br /> <a href='#' onclick='document.profileCorrectionForm.submit(); return false;'>Click here</a> to update your profile."
			formWrap.innerHTML = innerStr;
		} else {
			// If the json string we got back is not a userProfile, it must be an error message:
			formWrap.innerHTML = returnedObj.message;
		} // if-else userProfile...
	} catch (e) {
		alert(e);
	}
} // End handleLoginResponse(reqObj) function

function loginRedirect() {
    if (!up_login_cookie_domain) {
        alert('Your login was accepted; however, your current URL domain "'
            + location.host + '" may not be compatible with the IDJ network.');
    }
    var going_to = getReturnToCookie();
    alert(going_to);
    if (going_to) {
        //alert("going to: " + going_to);
        //Going somewhere else -- re-set the return cookie to this page
        setReturnToCookie();
        location.href = going_to;
    } else location.reload();
}

function doUserLogout() {
	var domainStr = location.host;
	domainArray = domainStr.split(".");
	domainArray.reverse();
	domainStr = "." + domainArray[1] + "." + domainArray[0];

	document.cookie = "idjupsessId=; path=/; domain=" + domainStr;
	document.cookie = "idjupsess=; path=/; domain=" + domainStr;
	var date = new Date();
	date.setTime(date.getTime() + (-3*24*60*60*1000));
	var expiry = date.toGMTString();
	document.cookie = "idjupsessremember=; expires=" + expiry + " path=/; domain=" + domainStr;
	//showUnloggedState();
	location.reload();
} // End doUserLogout()

function showUnloggedState() {
	try {
		document.getElementById("login_type_area").innerHTML = notLoggedInString;
		/*
			$userProfLinksString = '<a href="#" onclick="' . $config->loginOnClick . 
		'">Log-in</a> | New User? <a href="' . $config->registerUrl . 
		'">Join</a> | <a href="' . $config->registerUrl . '">' . 
		$config->oneClickSignUpLabelString . '</a>';	
		*/
		
		//var writeEl = document.getElementById("userGreeting");
		//writeEl.innerHTML = 'You are not logged in - <a href="#" onclick="showLoginForm(); return false;">Login</a> | <a href="#" onclick="showNewRegistrationForm(); return false;">Register</a>';
	} catch (e) {
		//location.reload();	
	}
} // End showUnloggedState()

function showUnloggedInState() {
	showUnloggedState();	
}

function showLoginForm(returnToUrl) {
	showHideScrim("visible");
	setReturnToCookie(returnToUrl);
	var writeEl = document.getElementById("loginFormWrapper");

	if (loginFormFirstTime) {
		loginFormString = writeEl.innerHTML;
		loginFormFirstTime = false;
	}
	writeEl.innerHTML = loginFormString;
	writeEl = document.getElementById("loginBox");
	//positionLoginBox();
	writeEl.className = "visibleLoginBox";
	
	try {
		document.userLoginForm.uname.focus();
	} catch (e) {}
	//writeEl.style.visibility = "visible";
	/*
	if (window.innerWidth) {
		var newPos = (window.innerWidth/2) - (parseInt(writeEl.style.width)/2);
		writeEl.style.left = newPos + "px";
	}
	if (parseInt(window.pageYOffset) == 0) {
		var off = -100;
	} else {
		var off = Math.round(window.pageYOffset/2);
	}

	if (window.innerHeight) {
		writeEl.style.top = (window.innerHeight/2) + off + "px";
	}
	*/
}

function positionLoginBox() {
	var scrollPos = 0;
	thisEl = document.getElementById("loginBox");
	if (document.body.scrollTop) {
		scrollPos = document.body.scrollTop;
	} else if (window.pageYOffset) {
		scrollPos = window.pageYOffset;
	}
	var innerHeight = 0;
	if (scrollPos > 100) {
		if (window.innerHeight) {
			scrollPos += (window.innerHeight/2 - (thisEl.style.height + 100));
		} else if (document.body.offsetHeight) {
			scrollPos += (document.body.offsetHeight/2 - (thisEl.style.height + 100));
		}
	} else {
		scrollPos += 100;
	}
	thisEl.style.top = Math.round(scrollPos) + "px";
} // End positionLoginBox() function

function cancelShowLoginForm() {
	var tmp = document.getElementById("loginBox");
	tmp.className = "hiddenLoginBox";
	showHideScrim("hidden");
}

function showCorrectProfileFieldsForm() {
	location.href = "http://" + location.host + "/www2/user_profile/profile_corrections.php";
}

function showEditProfileForm(siteId) {
	if (siteId == "") {
		siteId = 0;
	}
	setReturnToCookie();
	location.href = "http://" + location.host + "/www2/user_profile/update.php?siteId=" + siteId;
}

function showNewRegistrationForm() {
	setReturnToCookie();
	location.href = "http://" + location.host + "/www2/user_profile/registration.php?siteId=" + getSiteId();
}

function showForgotInfoForm() {
	setReturnToCookie();
	location.href = "http://" + location.host + "/www2/user_profile/forgot.php?siteId=" + getSiteId();
}


function getSiteId() {
	if (!profileSiteId || parseInt(profileSiteId) == "NaN") {
		profileSiteId = 0;
	}
	return profileSiteId;
}

function setReturnToCookie(overRideValue) {
	if (overRideValue == "" || overRideValue == null) {
		var val = location.href;
	} else {
		var val = overRideValue;
	}
	var domainStr = location.host;
	domainArray = domainStr.split(".");
	domainArray.reverse();
	domainStr = "." + domainArray[1] + "." + domainArray[0];
	document.cookie = "idjupsessreturnto=" + val + "; path=/; domain=" + domainStr;
}

function showHideFormFields(newStyle) {
	var sels = document.getElementsByTagName("select");
	var selsLen = sels.length;

	for (var i=0; i<selsLen; i++) {
		sels[i].style.visibility = newStyle;
	}
}