var http_request = false;

function toggleLayer(whichLayer)
{
	if (document.getElementById)
	{
	// this is the way the standards work
	var style2 = document.getElementById(whichLayer).style;
	style2.display = style2.display? "":"block";
	}
	else if (document.all)
	{
	// this is the way old msie versions work
	var style2 = document.all[whichLayer].style;
	style2.display = style2.display? "":"block";
	}
	else if (document.layers)
	{
	// this is the way nn4 works
	var style2 = document.layers[whichLayer].style;
	style2.display = style2.display? "":"block";
	}
}

function getElement(psID) {
   if(document.all) {
      return document.all[psID];
   } else if(document.getElementById) {
      return document.getElementById(psID);
   } else {
      for (iLayer = 1; iLayer < document.layers.length; iLayer++) {
         if(document.layers[iLayer].id == psID)
            return document.layers[iLayer];
      }
   }
   return null;
}

function showLoginBox() {
	var theEle = getElement('usrOpts');
	theEle.innerHTML = "<div id='loginBox'><form name='loginForm' action='javascript:do_login()'>username:<br /><input type='text' size='14' maxlength='20' id='login_usrname' /><br />password:<br /><input type='password' size='14' maxlength='20' id='login_passwd' /><br /><input type='submit' value='Log In' onClick='javascript:do_login();' /></form></div>";
	theEle.innerHTML += '<div class="nav"><a class="usrNav" href="register.php">Register</a></div><div class="nav"><a href="forgot_pw.php">Forgot Password</a></div>';
}

function do_login() {
	validateLogin( document.loginForm.login_usrname.value, document.loginForm.login_passwd.value ); // == true )
}

function doLogout() {
	var url="logout.php";
	var params="";
	makeRequest("logout", url, params);	
}

function validateLogin( Uname, Pword ) {
	var url = "validate.php";
	var params = '?usr=' + Uname + '&pw=' + Pword;
	makeRequest('login', url, params);
}

function ratePic( pID, pR ) {
	var url = "ratepic.php";
	var params = "?id=" + pID + "&rate=" + pR;
	makeRequest('rate', url, params);
}

function setAvatar( avaID ) {
	var url = "setava.php";
	var params = "?i=" + avaID;
	makeRequest('avatar', url, params);
}

function createHttpRequest() {
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			// set type accordingly to anticipated content type
			//http_request.overrideMimeType('text/xml');
			http_request.overrideMimeType('text/html');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if (!http_request) {
		alert('Cannot create XMLHTTP instance - Sorry, but your web brower does not have the appropriate Javascript compatibility.');
		return false;
	}

	return http_request;
}

// type is 'GET' or 'POST'
function makeRequest(type, url, parameters) {
	http_request = false;
	var method = 'GET';

	http_request = createHttpRequest();

	if ( !http_request ) {
		alert('Mysterious Error!');
		return false;
	}

	if ( type == 'login' )
		http_request.onreadystatechange = processLogin;	// PHP will return everything and processLogin will fill it in
	else if ( type == 'logout' )
		http_request.onreadystatechange = processLogout;
	else if ( type == 'checkUSR' )
		http_request.onreadystatechange = checkUSR;
	else if ( type == 'checkEMA' )
		http_request.onreadystatechange = checkEMA;
	else if ( type == 'rate' )
		http_request.onreadystatechange = doRating;
	else if ( type == 'avatar' )
		http_request.onreadystatechange = setAva;
	else if ( type == 'comment' )
		http_request.onreadystatechange = doCommentPost;
	else if ( type == 'commentDelete' )
		http_request.onreadystatechange = doCommentDelete;
	else if ( type == 'clearProfImg' )
		http_request.onreadystatechange = doClearProfileImage;
	else
		http_request.onreadystatechange = alertContents;
	http_request.open(method, url + parameters, true);
	http_request.send(null);
}

function checkUSR() {
var theDiv = 'tableTop';
if (http_request.readyState == 4) {
	if (http_request.status == 200) {
			var target = getElement( theDiv );
			if ( http_request.responseText == 'bad') {
				target.innerHTML = '<span style="color:red;">Username is already in use.</span>';
				var t2 = getElement('signupUser');
				t2.select(); t2.focus();
			} else {
				target.innerHTML = '';
			}
		} else {
			alert('There was a problem with the request.');
		}
	}
}

function checkEMA() {
var theDiv = 'tableTop';
if (http_request.readyState == 4) {
	if (http_request.status == 200) {
			var target = getElement( theDiv );
			if ( http_request.responseText == 'bad') {
				target.innerHTML = '<span style="color:red;">Email address is already in use.</span>';
				var t2 = getElement('signupEmail1');
				t2.select(); t2.focus();
			} else {
				target.innerHTML = '';
			}
		} else {
			alert('There was a problem with the request.');
		}
	}
}

function alertContents() {
var theDiv = 'contentPane';
if (http_request.readyState == 4) {
	if (http_request.status == 200) {
			result = http_request.responseText;
			var target = getElement( theDiv );
			target.innerHTML = result;
		} else {
			alert('There was a problem with the request.');
		}
	}
}

function processLogin() {
var theDiv = 'usrOpts';
if (http_request.readyState == 4) {
	if (http_request.status == 200) {
			result = http_request.responseText;
			if ( result == 'ok' ) {
				location.reload(false);
			} else {
				var target = getElement( theDiv );
				target.innerHTML = "<div id='usrOpts'>Invalid Login.<br /><br /><a href='javascript:showLoginBox()'>Click to Retry</a></div>";
			}
	} else {
			alert('There was a problem with the login request.');
		}
	}
}

function doRating() {
if (http_request.readyState == 4) {
	if (http_request.status == 200) {
			result = http_request.responseText;
			var target = getElement('rateBox');
			if ( result == 'ok' ) {
				target.innerHTML = "Thanks for rating!";
			} else if ( result == 'already' ) {		
				target.innerHTML = "You've already rated this image!";
			} else {
				target.innerHTML = "Error rating image.  Quelle dommage!";
				target.innerHTML += "got ret: " + result;
			}
	} else {
			alert('There was a problem with the rating process.');
		}
	}
}

function processLogout() {
var theDiv = 'usrOpts';
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			location.reload(false);
		} else {
			alert('There was a problem with the logout request.');
			var ttarget = getElement('contentPane');
			ttarget.innerHTML = http_request.responseText;
		}
	}
}

function setAva() {
if (http_request.readyState == 4) {
	if (http_request.status == 200) {
			result = http_request.responseText;
			if ( result == 'ok' ) {
				alert("OK! This image is now your avatar on Glitter-City!");
			} else {
				alert("There was a problem setting your avatar");
			}
	} else {
			alert('There was a problem setting your avatar.');
		}
	}
}


function is_valid_email( string ) {
	var matchVar = 	$regCompare = '^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$';
	return string.match(matchVar);
}

function validateSignup() {
	var retValue = false;
	var errors = new Array();
	var username = getElement('signupUser');
	var pass1 = getElement('signupPass1');
	var pass2 = getElement('signupPass2');
	var ema1 = getElement('signupEmail1');
	var ema2 = getElement('signupEmail2');
	var comply = getElement('regConfirm');
	var usrCheck = getElement('usrExist');
	var emaCheck = getElement('emaExist');

	if ( username.value.length < 5 || username.value.length > 15) {
		if ( username.value.length == 0)		errors.push('No username specified.');
		else	errors.push('Username must be 5 to 15 characters.');
	}

	if ( pass1.value == pass2.value ) {
		if ( pass1.value.length == 0 )			errors.push('No password entered');
		if ( pass1.value.length < 5 )			errors.push('Password is too short: must be at least 5 characters');
	} else {
		errors.push('Passwords do not match.');
	}

	if ( ema1.value == ema2.value ) {
		if ( ema1.length == 0 )					errors.push('Email address not entered.');
		if ( !is_valid_email(ema1.value) ) 	errors.push('Invalid email address.');
	} else {
		errors.push('Email addresses do not match.');
	}

	if ( usrCheck.value == 1 )	errors.push('Username is already in use.');
	if ( emaCheck.value == 1 ) errors.push('Email address already in use.');

	if ( !comply.checked )						errors.push('You must agree to the <a href="terms.php" target="_blank">Terms and Conditions</a> to register as a member.');

	if ( errors.length > 0 ) {
		var target = getElement('tableTop');
		var errorString = '';
		for ( x=0; x < errors.length; x++ ) {
			errorString += errors[x] + '<br /><br />';
		}
		target.innerHTML = errorString;
	} else {
		retValue = true;
	}

	return retValue;
}

function validateSettings() {
	var retValue = false;
	
	var errors = new Array();
	
	var pass1 = getElement('sPass1');
	var pass2 = getElement('sPass2');
	var email = getElement('sEmail');
	
	if ( pass1.value != pass2.value ) {
		errors.push('Passwords do not match.');
	}
	
	if ( pass1.value.length > 0 ) { if ( pass1.value.length < 5 ) errors.push("Password is too short: must be at least 5 characters"); }

	if ( !is_valid_email(email.value) ) 	errors.push('Invalid email address.');

	if  ( errors.length > 0 ) {
		var target=getElement('tableTop');
		var errorString='';
		for ( x=0; x < errors.length; x++ ) {
			errorString += errors[x] + '<br /><br />';
		}
		target.innerHTML = errorString;
	} else {
		retValue = true;
	}
	
	return retValue;
}

function filterInput( target, mode ) {
   	var theString = target.value;

	for ( x in theString ) {
		if ( !validCharacter(theString[x], mode) ) {
			target.value = theString.substr(0,theString.length - 1);
		}
	}

}

function validCharacter( chr, mode ) {
	var retCode = true;
	
	if ( mode == 0 ) {
		switch ( chr ) {
			case '\\':
			case '/':
			case '<':
			case '>':
				retCode = false; break;
		}
	}
	
	if ( mode == 1 ) {
		switch ( chr ) {
			case '"':
			case '\'':
				retCode = false; break;
		}
	}
	
	if ( mode == 2 ) {
		switch ( chr ) {
			case '"':
			case '\'':
			case '\\':
			case '/':
			case ',':
			case '~':
			case '`':
			case '(':
			case ')':
			case '<':
			case '>':
				retCode = false; break;
		}		
	}

	return retCode;
}

function existingUsername(Username) {
	var url = "validate.php";
	var params="?usr=" + Username;
	makeRequest('checkUSR', url, params);
}

function checkUsername() {
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			alert( "got: " + http_request.responseText );
			var theTarget = getElement("usrExist");
			theTarget.value = 1;
		} else {
			alert('There was a problem with the username check request.');
			var ttarget = getElement('contentPane');
			ttarget.innerHTML = http_request.responseText;
		}
	}
}

function checkEmail(address) {
	var url = "validate.php";
	var params="?ema=" + address;
	makeRequest('checkEMA', url, params);
}

function chkAboutLen() {
	var about = getElement('pEditAbout');
	var theStr = about.value;
	if ( theStr.length > 1000 )   about.value = theStr.substr(0,1000);
    var tCount = getElement('pEditAboutCntr');
	var cLeft = (1000 - theStr.length);
	tCount.value = cLeft;
}

function postComment(imageID) {
	var url='addcomment.php';
	var params='?img=' + imageID + "&cmt=" + encodeURI(cmtBody.value);
	makeRequest("comment", url, params);
}

function delComment(cID){
	var url="delcomment.php";
	var params="?id="+cID;
	makeRequest("commentDelete",url,params);
}

function doCommentDelete() {
	if ( http_request.readyState == 4) {
		if ( http_request.status==200){
			var result = http_request.responseText;
			if ( result == 'ok' ) {
				location.reload();
			} else {
				alert("Sorry!  Error deleting comment...");
			}
		} else {
			alert("Sorry!  Error deleting comment.");
		}
	}

}

function doCommentPost() {
	var cmtBody = getElement("cmtBody");
	if ( http_request.readyState == 4) {
		if ( http_request.status==200){
			var result = http_request.responseText;
			if ( result == 'ok' ) {
				cmtBody.value='';
				location.reload();
			} else {
				cmtBody.value='sorry, error posting comment';
			}
		} else {
			cmtBody.value='sorry, error posting comment';
		}
	}
}

function removeProfileImage() {
	var url="clearprofileimage.php";
	var params="";
	makeRequest("clearProfImg", url, params);	
}

function doClearProfileImage() {
	if ( http_request.readyState == 4) {
		if (http_request.status==200){
			var result = http_request.responseText;
			if ( result == 'ok' ) {
				location.reload(true);
			} else {
				alert("Sorry!  Error removing profile image...");
			}
		}
	}
}