 function playSound(soundfile) {
	try {
		document.getElementById("__notice").innerHTML= "<embed src=\"/freya/notice.aif\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";
	} catch (err) {}
 }

function trackEvent(category, action, label, value) {
	try {
		var z = "nope";
		if(value === undefined) {
			z = pageTracker._trackEvent(category, action, label);
		} else {
			z = pageTracker._trackEvent(category, action, label, value);
		}
		//alert("event tracked ="+z+" category="+category+"  action="+action+"   label="+label);
	} catch (err) {}
}

var _step = 0;
function updateStep(step) {
	_step = step;
	var server = $("__domain").value + "freya/updateStep.jsp";
	new Ajax.Request(server,
	{
		method:'get',
		parameters: {step: step},
		onSuccess: function(transport){ if(step == 9 || step == 109 || step == 207) {goToRegistrationUrl(true);} },
		onFailure: function(transport){ if(step == 9 || step == 109 || step == 207) {goToRegistrationUrl(true);} }
	});
}

function newWindow(url, width, height) {
	window.open(url, '','menubar=no,scrollbars=0,width=' + width + ',height=' + height + ',toolbar=no');
	return false;
}

function updateChat(unread, tstamp) {
	tstamp = trim(tstamp);
	
	var server = $("__domain").value + "freya/updateChat.jsp";

	new Ajax.Request(server,
			{
		method:'get',
		parameters: {uread: unread, ts: tstamp},
		onSuccess: function(transport){ },
		onFailure: function(transport){ }
			});
}

function delCurrentChat() {
	var server = $("__domain").value + "freya/updateChat.jsp";
	new Ajax.Request(server,
			{
		method:'get',
		parameters: {delcurrentchat: true},
		onSuccess: function(transport){ },
		onFailure: function(transport){ }
			});
}

function insertEvent(name, type) {
	var server = $("__domain").value + "freya/insertEvent.jsp";
	new Ajax.Request(server,
	{
		method:'get',
		parameters: {name: name, type: type},
		onSuccess: function(transport){ },
		onFailure: function(transport){ }
	});
}


function insertEventBlocking(name, type) {
	var server = $("__domain").value + "freya/insertEvent.jsp";
	new Ajax.Request(server,
	{
		asynchronous: false,
		method:'get',
		parameters: {name: name, type: type},
		onSuccess: function(transport){ },
		onFailure: function(transport){ }
	});
}

function deleteCampaignUserAndGoToUrl() {
	_step = -1;
	var server = $("__domain").value + "freya/deleteCampaignUser.jsp";
	new Ajax.Request(server,
	{
		method:'get',
		parameters: {},
		onSuccess: function(transport){ goToRegistrationUrl(false); },
		onFailure: function(transport){ goToRegistrationUrl(false); }
	});
}

function trim(string) {
    return string.replace(/^\s*/, "").replace(/\s*$/, "");
}


function loginUserFb(fromLogin) {
	
	if(fromLogin) {
		//$("fbLoader").style.visibility = "visible";
		//$("fbNoFbButton").disabled = true;
	}
	
//	ReturnStatus GCLoginUserFb(String apiKey, 
//    	 	String applicationCode, 
//    	 	String sessionId, 
//    	 	String fbSessionId, 
//    	 	long   fbSessionExpires, 
//     		long   fbUserId, 
//     		String useragent, 
//     		String ipaddress, 
//    		String ui)
	var url = $("loginUri").value;
	if(url.indexOf("?") > 0) {
		url = $("__uri").value+"&fblogin=1";
	} else {
		url = $("__uri").value+"?fblogin=1";
	}
	$("__uri").value = url;
	
	var sid = $("__sid").value;
	var acode = $("__acode").value;
	var server = $("__server").value + "GCLoginUserFb";

	var useragent = navigator.userAgent;
	
	var session = FB.Facebook.apiClient.get_session();
	var expires = session.expires;
	var fbuid = session.uid;
	var sessionKey = session.session_key;
	var applicationCode = session.application_code;
	
	if(!server) {
		alert("no session id and/or server found");
		
		if(fromLogin) {
			//$("fbLoader").style.visibility = "hidden";
			//$("fbNoFbButton").disabled = false;
		}
		
		return;
	}
	
	new Ajax.Request(server,
	  {
	    method:'post',
	    parameters: {apiKey: acode, applicationCode: acode, sessionId: sid, fbSessionId: sessionKey, fbSessionExpires: expires, fbUserId: fbuid, useragent: useragent, ipaddress: "", ui: "freya"},
		onSuccess: function(transport){ onLoginUserFbSuccess(transport.responseText, fromLogin); },
		onFailure: function(transport){ onLoginUserFbFail(transport.responseText); }
	  });
}


function onLoginUserFbSuccess(response, fromLogin) {
	var status = parseXML(response, "<ax([0-9])*:statusCode>", "</ax([0-9])*:statusCode>");
	var desc = parseXML(response, "<ax([0-9])*:description>", "</ax([0-9])*:description>");
	var sessionId = parseXML(response, "<ax([0-9])*:sessionId>", "</ax([0-9])*:sessionId>");

	if(sessionId) {
		$("__sid").value = sessionId;
	}
	
	var notificationId = $("notificationId").value;

	//done parsing	
	var STATUS_REGISTER = 2;
	var STATUS_SESSION_ERROR = -2;
	var STATUS_OK = 0;
	if(status == STATUS_REGISTER) {
		//user needs to register...
		if(fromLogin) {
			gotoRegistrationPage(4);
		} else {
			gotoRegistrationPage(4);
			resizeLW(370, 270);
			//show the /chat/ popup stuff
		}
	} else if(status == STATUS_OK) {
		//we are logged in, user should be redirected to... home?
		if(notificationId) {		
			gotoRegistrationPage(8);
			resizeLW(369, 273);
		} else if(fromLogin) {
			deleteCampaignUserAndGoToUrl();
		} else {
			window.location = $("__uri").value;
		}
	} else if(status == STATUS_SESSION_ERROR) {
		alert("FBLogin // session error, reload page?  desc="+description);
		if(fromLogin) {
			//$("fbLoader").style.visibility = "hidden";
			//$("fbNoFbButton").disabled = false;
		}
	} else {
		//this should never happen
		alert("FBLogin // how could this happen? status="+status+"      desc="+description);
		if(fromLogin) {
			//$("fbLoader").style.visibility = "hidden";
			//$("fbNoFbButton").disabled = false;
		}
	}
}

function onLoginUserFbFail(response) {
	alert("onLoginUserFbFail");

	window.location.reload();
}

function emailCheck() {
	var email = $("emailAfter").value;
	
	var pattern=/^([a-zA-Z0-9_.-@])+/;
	if(email.indexOf(" ") > -1 || !pattern.test(email)) {
		alert("Email must be a valid email address and can't contain spaces or special characters");
		return false;
	}	
	return true;
}

function testRegisterUserFb() {
	var email = $("fbRegEmail").value;
	
	var pattern=/^([a-zA-Z0-9_.-@])+/;
	if(email.indexOf(" ") > -1 || !pattern.test(email)) {
		alert("Email must be a valid email address and can't contain spaces or special characters");
		return false;
	}
	
	FB.Facebook.apiClient.users_hasAppPermission('offline_access', function(ok) { hasAppPermission(ok); });
}

function checkOfflineAccess() {
	FB.Facebook.apiClient.users_hasAppPermission('offline_access', function(ok) { hasOfflineAccess(ok); });
}

function hasOfflineAccess(ok) {
	if(!ok) {
		FB.Connect.showPermissionDialog('offline_access', function() {});	
	}
}

function hasAppPermission(ok) {
	if(ok) {
		if(_step < 100) {
			updateStep(6);
		} else {
			updateStep(106);
		}
		registerUserFb();
	} else {
		FB.Connect.showPermissionDialog('offline_access', function() {testRegisterUserFb();});
	}
}

function registerUserFb() {
//	ReturnStatus GCRegisterUserFb(
//			String apiKey,  
//    		String applicationCode, 
//    		String sessionId, 
//    		String fbSessionId, 
//    		long   fbSessionExpires, 
//    		long   fbUserId, 
//    		String email,
//    		String useragent, 
//    		String ipaddress, 
//    		String ui)
	

	var sid = $("__sid").value;
	var server = $("__server").value + "GCRegisterUserFb";

	var email = $("fbRegEmail").value;
	if(!email) {
		alert("You need to have a valid email");
		return false;
	}
	
	var useragent = navigator.userAgent;
	
	var session = FB.Facebook.apiClient.get_session();
	var expires = session.expires;
	var fbuid = session.uid;
	var sessionKey = session.session_key;
	
	if(!server) {
		alert("no session id and/or server found");
		return;
	}
	
	new Ajax.Request(server,
	  {
	    method:'post',
	    parameters: {apiKey: "freya", applicationCode: "freya", sessionId: sid, fbSessionId: sessionKey, fbSessionExpires: expires, fbUserId: fbuid, email: email, useragent: useragent, ipaddress: "", ui: "freya"},
		onSuccess: function(transport){ onRegisterUserFb(transport.responseText); },
		onFailure: function(transport){ failRegisterUserFb(transport.responseText); }
	  });
	
	//show loader
	$("fbEmailLoader").style.visibility = "visible";
	$("fbNextEmailButton").disabled = true;
}

function onRegisterUserFb(response) {
	var status = parseXML(response, "<ax([0-9])*:statusCode>", "</ax([0-9])*:statusCode>");
	var desc = parseXML(response, "<ax([0-9])*:description>", "</ax([0-9])*:description>");
	
	var notificationId = $("notificationId").value;
	
	var STATUS_SESSION_ERROR = -2;
	var STATUS_OK = 0;
	var STATUS_REGISTER = 2;
	
	if(status == STATUS_OK) {
		if(notificationId) {		
			gotoRegistrationPage(8);		
			resizeLW(369, 273);
		} else {
			deleteCampaignUserAndGoToUrl()
		}
	} else if(status == STATUS_REGISTER) {
		if(_step < 100) {
			updateStep(7);
		} else {
			updateStep(107);
		}
		readUserForFb();
	} else if(status == STATUS_SESSION_ERROR) {
		alert("live.js/onRegisterUserFb/an error occurred :: "+desc);
		$("fbEmailLoader").style.visibility = "hidden";
		$("fbNextEmailButton").disabled = false;
	} else {
		//this should never happen
		alert("Registration failed. "+desc);
		$("fbEmailLoader").style.visibility = "hidden";
		$("fbNextEmailButton").disabled = false;
	}
}

function failRegisterUserFb(response) {
	window.location.reload();
}

function readUserForFb() {
	 //public WichroUserReturnObject readUser(String sessionId)
	 var sid = $("__sid").value;
	 var server = $("__server").value + "readUser";
	 new Ajax.Request(server,
	  {
	    method:'post',
	    parameters: {sessionId: sid},
	    onSuccess: function(transport){ onReadUserForFb(transport.responseText); },
		onFailure: function(transport){ gotoRegistrationPage(5); }
	  });
}

function onReadUserForFb(response) {
	//fill in values
	var name = parseXML(response, "<ax([0-9])*:firstName>", "</ax([0-9])*:firstName>");
	$("regFbName").value = name;

	var locationXML = parseXML(response, "<ax([0-9])*:location", "</ax([0-9])*:location>");
	if(locationXML) {
		var city = parseXML(locationXML, "<ax([0-9])*:city>", "</ax([0-9])*:city>");
		var state = parseXML(locationXML, "<ax([0-9])*:state>", "</ax([0-9])*:state>");
		var country = parseXML(locationXML, "<ax([0-9])*:country>", "</ax([0-9])*:country>");
		
		$("regFbLocation").value = city+", "+state+" "+country;
	}
	
	var sex = parseXML(response, "<ax([0-9])*:sex>", "</ax([0-9])*:sex>");
	if(sex) {
		if(sex == "wichro.user_sex_male") {
			//inverse for interestedin
			$("regFbSex").selectedIndex = 1;
			$("regFbInterestedin").selectedIndex = 1;
		} else {
			$("regFbSex").selectedIndex = 0;
			$("regFbInterestedin").selectedIndex = 0;
		}
	}
	var birthday = parseXML(response, "<ax([0-9])*:birthDate>", "</ax([0-9])*:birthDate>");
	if(birthday) {
		var date = new Date();
		date.setTime(birthday * 1000);
		var month = date.getMonth();
		var day = date.getDate();
		var year = date.getFullYear();
		$("FBregisterDay").selectedIndex = day;
		$("FBregisterMonth").selectedIndex = month;
		$("FBregisterYear").selectedIndex = year - 1930;
	}
	//done
	gotoRegistrationPage(5);
}

function updateUserFb() {
	$("fbDoneLoader").style.visibility = "visible";
	$("fbDoneButton").disabled = true;
	
//	ReturnStatus GCUpdateUserFb(
//    		String apiKey, 
//    		String applicationCode, 
//    		String sessionId, 
//    		String name,
//    		String location,
//    		String sex,
//    		String interestedIn,
//    		long birthday,
//    		boolean allowSkoutToSaveFbData
	
	var name = $("regFbName").value;
	var location = $("regFbLocation").value;
	var sex = $("regFbSex").value;
	var interestedin = $("regFbInterestedin").value;
	var bday = $("FBregisterDay").value;
	var bmonth = $("FBregisterMonth").value;
	var byear = $("FBregisterYear").value;
	var savedata = $("fbSaveData").checked;
	
	var date = new Date();
	date.setFullYear(byear);
	date.setMonth(bmonth);
	date.setDate(bday);
	var bdayTime = date.getTime();
	
	//ajax update user
	//public WichroUserReturnObject readUser(String sessionId)
	var sid = $("__sid").value;
	var server = $("__server").value + "GCUpdateUserFb";
	new Ajax.Request(server,
	  {
	    method:'post',
	    parameters: {apiKey: "freya", applicationCode: "freya", sessionId: sid, name: name, location: location, sex: sex, 
		 			interestedIn: interestedin, birthday: bdayTime, allowSkoutToSaveFbData: savedata},
	    onSuccess: function(transport){ onUpdateUserFb(transport.responseText); },
		onFailure: function(transport){ goToRegistrationUrl(true); }
	});
}

function onUpdateUserFb(response) {
	var notificationId = $("notificationId").value;

	if(notificationId) {
		gotoRegistrationPage(8);
		resizeLW(369, 273);
	} else {
		if(_step < 100) {
			updateStep(9);
		} else {
			updateStep(109);
		}
	}
}

function removeFromHotlistServer(userid, hotlistLink, name) {	
	if (confirm('Are you sure you want to remove ' + name + ' from your hotlist?')) {
		var sid = $("__sid").value;
		var server = $("__server").value + "removeFromHotlist";
		
		if(!sid || !server) {
			alert("no session id and/or server found");
			return false;
		}
		
		$(hotlistLink+'').replace('<span style="color:#5b5;">user removed!</span>');
		
		new Ajax.Request(server,
		  {
		    method:'post',
		    parameters: {sessionId: sid, userId: userid}
		  });
		
		return true;
	}
}


function addToHotlistServer(userid, hotlistLink) {
	var sid = $("__sid").value;
	var server = $("__server").value + "addToHotlist";
	
	if(!sid || !server) {
		alert("no session id and/or server found");
		return;
	}
	
	$(hotlistLink+'').replace('<span style="color:#5b5;">user added!</span>');

	new Ajax.Request(server,
	  {
	    method:'post',
	    parameters: {sessionId: sid, userid: userid, message: ""} 
	    //onSuccess: function(transport){ onHotlistSuccess(transport.responseText); }
	  });
}

function onHotlistSuccess(response) {
	var success = parseXML(response, "<ax([0-9])*:success>", "</ax([0-9])*:success>");
	if(success == "false") {
		alert(getDescription(response));			
	} else {
		
	}
}

function updateSettings() {
	var sid = $("__sid").value;
	var serverPass = $("__server").value + "updateLogin";
	var serverEmail = $("__server").value + "updateSendEmailSummary";
	
	var username = $("__user_username").value;
	var newPass = $("pw1").value;
	var send = $("emailCheckbox").checked;
	var sendBefore = $("summaryChangeBefore").value;
	
	if(newPass.length > 0) {
		new Ajax.Request(serverPass,
		{
		    method:'post',
		    parameters: {sessionId: sid, param0: username, param1: "", param2: newPass},
		    onSuccess: function(transport){ 
		    	//alert("Password updated"); 
		    }
		});
	}
	
	if((!send && sendBefore == "true") || (send && sendBefore == "false")) {
		new Ajax.Request(serverEmail,
		{
			method:'post',
			parameters: {sessionId: sid, send: send},
			onSuccess: function(transport){ 
				//alert("Send email notifications updated"); 
			}
		});
	}
	
	var serverUpdateEmail = $("__server").value + "updateEmail";
	
	var emailAfter = $("emailAfter").value;
	var emailBefore = $("emailBefore").value;
	
	if(emailAfter && emailAfter.length>0 && emailAfter!=emailBefore) {
		new Ajax.Request(serverUpdateEmail,
		{
		    method:'post',
		    parameters: {sessionId: sid, email: emailAfter},
		    onSuccess: function(transport){ 
		    }
		});
	}

	myLightWindow.deactivate();
	try {
		trackEvent("button - settings", "click - settings save", "settings - settings save");
	} catch(err) {}
}

function updateEmail() {
	var sid = $("__sid").value;
	var serverEmail = $("__server").value + "updateEmail";
	
	var emailAfter = $("emailAfter").value;
	var emailBefore = $("emailBefore").value;
	
	if(emailAfter && emailAfter.length>0 && emailAfter!=emailBefore) {
		new Ajax.Request(serverEmail,
		{
		    method:'post',
		    parameters: {sessionId: sid, email: emailAfter},
		    onSuccess: function(transport){ 
		    }
		});
	}
	myLightWindow.deactivate();
}


function sendPasswordReminder() {
	var sid = $("__sid").value;
	var server = $("__server").value + "getAccountReminder";
	var email = $("loginEmail").value;
	
	if(!sid || !server) {
		alert("no session id and/or server found");
		return;
	}

	if(!email) {
		alert("you have to enter your email address");
		return;
	}
	
	new Ajax.Request(server,
	  {
	    method:'post',
	    parameters: {sessionId: sid, account: email},
	    onSuccess: function(transport){ alert("An email with your password has been sent to you"); }
	  });
}

function closeInfoPane(id) {
	if($("__sid")) {
		var sid = $("__sid").value;
		var server = $("__server").value + "GCCloseHelp";
		
		if(!sid || !server) {
			alert("no session id and/or server found");
			return;
		}
		
		new Ajax.Request(server,
		  {
		    method:'post',
		    parameters: {apiKey: "freya", applicationCode: "freya", sessionId: sid, helpId: id}
		  });
		
		
	} 
}

function wink(id, winkLink) {
	if($("__sid")) {
		var sid = $("__sid").value;
		var server = $("__server").value + "GCWink";
		
		if(!sid || !server) {
			alert("no session id and/or server found");
			return;
		}
		
		new Ajax.Request(server,
		  {
		    method:'post',
		    parameters: {apiKey: "freya", applicationCode: "freya", sessionId: sid, userId: id}
		  });
		
		
		$(winkLink+'').replace("<span style=\"color:#5b5;\">winked!</span>");
			
	} else {
		alert("You need to be logged in if you want to wink to other users");
	}
}




function register() {
	/* Disable the register button and show loader */
	setRegisterLoading(true);
	
	var sid = $("__sid").value;
	var server = $("__server").value + "GCCreateUserAndLogin";
	var acode = $("__acode").value;
	
	if(!sid || !server) {
		alert("no session id and/or server found");
		
		/* enable button, hide loader */
		setRegisterLoading(false);
		return;
	}
	
	var useragent = navigator.userAgent;
	var email = $("loginEmail").value;
	var password = $("loginPassword").value;
	var screenName = $("registerName").value;
	var location = $("registerLocation").value;
	
	var errorMessage = "";
	
	if (screenName.length == 0) {
		$("registerName").style.border="3px solid #f00";
		errorMessage += "- You must provide a screen name, i.e. 'Wonder Woman' or 'Clark'.\n\r";
	} else {
		$("registerName").style.border="0px none #fff";
	}
	
	var birthday = $("registerYear").value+"-"+$("registerMonth").value+"-"+$("registerDay").value;
	var limit = new Date();
	limit = new Date(limit.getYear()-18, limit.getMonth(), limit.getDate());
	var birth = new Date($("registerYear").value, $("registerMonth").value-1, $("registerDay").value);
	if(limit < birth) {
		$("bddiv").style.border="3px solid #f00";
		errorMessage += "- You must be over 18 to use this service.\n\r";
	} else {
		$("bddiv").style.border="0px none #fff";
	}
	
	
	var gender = "";
	if($("registerMan").checked) {
		gender = $("registerMan").value;
	} else {
		gender = $("registerWoman").value;
	}		
	
	
	var interestedIn = "";
	if($("registerLookMen").checked) {
		interestedIn = $("registerLookMen").value;
	} else if($("registerLookWomen").checked) {
		interestedIn = $("registerLookWomen").value;
	} else {
		interestedIn = $("registerLookBoth").value;
	}
	
	if (errorMessage.length > 0) {
		/* enable button, hide loader */
		setRegisterLoading(false);
		alert(errorMessage);
		return;
	} 
	
	updateStep(206); 
	
	new Ajax.Request(server,
	  {
	    method:'post',
	    parameters: {apiKey: acode, applicationCode: acode, sessionId: sid, param0: email, param1: password, useragent: useragent, ui: "Freya",  
		screenName: screenName, locationString: location, gender: gender, birthday: birthday, interestedIn: interestedIn},
	    onSuccess: function(transport){ onRegister(transport) },
	    onFailure: function(transport){ onRegisterFailure(transport) }
	  });
	
	return false;
}


function registerNew() {
	if ($('reg_continueButton_disabled').style.visibility == "visible") {
		return false;
	}
	
	enableOrDisableContinue();
	
	var sid = $("__sid").value;
	var server = $("__server").value + "createUserAndLogin";
	
	if(!sid || !server) {
		alert("no session id and/or server found");
		enableOrDisableContinue();
		return;
	}
	
	var useragent = navigator.userAgent;
	
	var email = $("reg_email").value;
	var screenName = $("reg_name").value;
	var password = $("reg_password").value;
	var location = $("reg_location").value;
	
	var errorBorderStyle = "1px dashed #f00";
	var errorTextColor = "#d00";
	var normalBorderStyle = "1px solid #666";
	var normalTextColor ="#333";
	
	var errorMessage = "";
	
	email = trim(email);
	var pattern=/^([a-zA-Z0-9_.-@])+/;
	if(email.indexOf(" ") > -1 || !pattern.test(email)) {
		$("reg_email").style.border = errorBorderStyle;
		$("reg_email").style.color= errorTextColor;
		errorMessage += "- You must enter a valid e-mail address.\n\r";
	} else {
		$("reg_email").style.border= normalBorderStyle;
		$("reg_email").style.color= normalTextColor;
	}
	
	if (screenName.length == 0) {
		$("reg_name").style.border = errorBorderStyle;
		$("reg_name").style.color= errorTextColor;
		errorMessage += "- You must provide a username, i.e. 'Wonder Woman' or 'Clark'.\n\r";
	} else {
		$("reg_name").style.border= normalBorderStyle;
		$("reg_name").style.color= normalTextColor;
	}
	
	if (password.length == 0) {
		$("reg_password").style.border = errorBorderStyle;
		$("reg_password").style.color= errorTextColor;
		errorMessage += "- You must provide a password.\n\r";
	} else {
		$("reg_password").style.border= normalBorderStyle;
		$("reg_password").style.color= normalTextColor;
	}
	
	if (location.length == 0) {
		$("reg_location").style.border = errorBorderStyle;
		$("reg_location").style.color= errorTextColor;
		errorMessage += "- You must provide the city you live in.\n\r";
	} else {
		$("reg_location").style.border= normalBorderStyle;
		$("reg_location").style.color= normalTextColor;
	}
		
	var gender = "";
	if($("registerMan").checked) {
		gender = $("registerMan").value;
	} else {
		gender = $("registerWoman").value;
	}		
	
	var interestedIn = "";
	if($("registerLookMen").checked) {
		interestedIn = $("registerLookMen").value;
	} else if($("registerLookWomen").checked) {
		interestedIn = $("registerLookWomen").value;
	} else {
		interestedIn = $("registerLookBoth").value;
	}
	
	var birthday = $("registerYear").value+"-"+$("registerMonth").value+"-"+$("registerDay").value;
	var limit = new Date();
	limit = new Date(limit.getYear()-18, limit.getMonth(), limit.getDate());
	var birth = new Date($("registerYear").value, $("registerMonth").value-1, $("registerDay").value);
	if(limit < birth) {
		$('registerMonth').style.color = errorTextColor;
		$('registerDay').style.color = errorTextColor;
		$('registerYear').style.color = errorTextColor;
		errorMessage += "- You must be over 18 to use this service.\n\r";
	} else {
		$('registerMonth').style.color = normalTextColor;
		$('registerDay').style.color = normalTextColor;
		$('registerYear').style.color = normalTextColor;
	}
	
	//checkin' the file input
	if ($('fileInput').value != "" || $('fileInput').value != null) {
		var extArray = new Array(".gif", ".jpg", ".jpeg", ".bmp", ".png");
		var file = $('fileInput').value;
	
		var allowSubmit = false;
		if (file) {
			while (file.indexOf("\\") != -1) {
				file = file.slice(file.indexOf("\\") + 1);
			}
		
			var ext = file.slice(file.indexOf(".")).toLowerCase();
			for (var i = 0; i < extArray.length; i++) {
				if (extArray[i] == ext) { 
					allowSubmit = true; break; 
				}
			}
		
			if (allowSubmit == false) {
				errorMessage += "- You may only upload files that end in: ";
				errorMessage += extArray.join(", ");
				errorMessage += ".\n\r";
			}
		}
	}
		
	if (errorMessage.length > 0) {
		/*display error message */
		alert(errorMessage);
		enableOrDisableContinue();
		return;
	} 
	
	updateStep(306); 
	
	new Ajax.Request(server,
	  {
	    method:'post',
	    parameters: {sessionId: sid, param0: email, param1: password, useragent: useragent, ui: "Freya",  
		screenName: screenName, locationString: location, gender: gender, birthday: birthday, interestedIn: interestedIn},
	    onSuccess: function(transport){ onRegisterNew(transport) },
	    onFailure: function(transport){ onRegisterFailureNew(transport) }
	  });
	
	return false;
}

function onRegisterNew(transport) {	
	var response = transport.responseText;
	
	var success = parseXML(response, "<ax([0-9])*:success>", "</ax([0-9])*:success>");
	var description = parseXML(response, "<ax([0-9])*:description>", "</ax([0-9])*:description>");
	
	if(success == "true") {
		
		//If an image have been selected, upload it and the user is redirected from there
		
		if ($('fileInput').value == "" || $('fileInput').value == null) {
			//send user to billing immediately, as an image have not been selected
			window.location = $("__sdomain").value + 'billing/index_v2.jsp?register=1';
		} else {
			displayRegisterLoader();
			$('uploadPictureForm').submit();
		}
		
		updateStep(307); 
	} else {
		alert("something went wrong::\n"+description);
		enableOrDisableContinue();
	}
}


function onRegister(transport) {	
	var response = transport.responseText;
	
	var success = parseXML(response, "<ax([0-9])*:success>", "</ax([0-9])*:success>");
	var description = parseXML(response, "<ax([0-9])*:description>", "</ax([0-9])*:description>");
	
	if(success == "true") {
		//go to the fine fine page you were going to
		//cancelLogin(); 
		updateStep(207); 
	} else {
		alert("something went wrong::\n"+description);
		setRegisterLoading(false);
	}
}

function onRegisterFailure(transport) {
	alert(transport.responseText);	
	setRegisterLoading(false);
}

function onRegisterFailureNew(transport) {
	alert(transport.responseText);
	enableOrDisableContinue();
}

function setRegisterLoading(isLoading) {
	var submitButton = $("submitButton");
	var loader = $("registrationLoader");
	var disableInputs;
	
	/* put all inputs and selects in the array "hidableItemsArray" */
	var hidableItemsArray = $$('input');
	var selectElements = $$('select');
	for (var index=0; index<selectElements.length; ++index) {
		hidableItemsArray[hidableItemsArray.length] = selectElements[index]; 
	}
	
	if (isLoading == true) {
		disableInputs = true;
		loader.style.visibility = "visible";
		submitButton.style.disabled = 'true';
	} else {
		disableInputs = false;
		loader.style.visibility = "hidden";
		submitButton.style.disabled = 'false';
	}
	
	for (var index = 0; index < hidableItemsArray.length; ++index) {
  		var item = hidableItemsArray[index];
  		item.disabled = disableInputs;
	}
}


function goToRegistrationUrl(register) {
	//this means we just logged in or registered, lets set a cookie that remembers this
	var email = $("loginEmail").value;
	var password = $("loginPassword").value;
	
	if(email && password) {
//		setCookie("uid", encodeURIComponent(email), 365*24*60*60, "/", ".skout.com");
//		setCookie("pwd", encodeURIComponent(password), 365*24*60*60, "/", ".skout.com");
		setCookie("uid", email, 365*24*60*60, "/", ".skout.com");
		setCookie("pwd", password, 365*24*60*60, "/", ".skout.com");
	}
	
	var u = $("__uri").value;
	if(u.indexOf("?") > 0) {
		u = $("__uri").value+"&sid="+$("__sid").value;
	} else {
		u = $("__uri").value+"?sid="+$("__sid").value;
	}
	u+= "&login=1";
	if(register) {
		u+= "&register=1";
	}
	window.location.href= u;
}

function goToGiftUrl(register) {
	var u = "/connect/gift.jsp?sid="+$("__sid").value;
	u+= "&login=1";
	if(register) {
		u+= "&register=1";
	}
	window.location.href= u;
}

function logout(fb, callback) { 
	var lg = callback;
	if(!lg) {
		lg = confirm("Are you sure you want to log out?");
	}

	if(lg) {
		if(fb && FB && FB.Connect && !callback) {
			FB.Connect.logout(   function(bool) { logout(true, true);  }    );
			return;
		}
		
		var sid = $("__sid").value;
		var server = $("__server").value + "logoutUser";
		
		if(!sid || !server) {
			alert("no session id and/or server found");
			return;
		}
		
		new Ajax.Request(server,
		  {
		    method:'post',
		    parameters: {sessionId: sid},
		    onSuccess: function(transport){ window.location.href = "/?logout=1"; },
		    onFailure: function(transport){ alert("LOGOUT FAILURE\n"+transport.responseText) }
		  });
		
		try {
			if(fb) {
				trackEvent("button - settings", "click - logout from facebook", "settings - logout from facebook");
			} else {
				trackEvent("button - settings", "click - logout", "settings - logout");
			}
		} catch(err) {}
	} else {
		//she said NO!
	}
}

function updateStatus(statusText) {
	var statusString = statusText+'';
	var sid = $("__sid").value; 
	var server = $("__server").value + "setUserExtendedStatus";
	if(!sid || !server) {
		alert("no session id and/or server found");
		return;
	}

	new Ajax.Request(server,
	{
		method:'post',
		parameters: {sessionId: sid, extendedStatus: statusString},
		onSuccess: function(transport){ onStatusPostSuccessful(); },
		onFailure: function(transport){ 
			alert("Could not update status. Please try again later. \n\n"+transport.responseText); 
			toggleWhatsUpSubmit(false);
		}
	});
}

/* COMMENT POSTING */

function postCommentServer(comment, eventId, postedFrom, newsId) {
	var sid = $("__sid").value; 
	var server = $("__server").value + "postEventCommentEx";//(String sessionId, String apiKey, long eventId, String comment)
	if(!sid || !server) {
		alert("no session id and/or server found");
		return;
	}
	
	new Ajax.Request(server,
	{
		method:'post',
		parameters: {sessionId: sid, apiKey: "", eventId: eventId, comment: comment},
		onSuccess: function(transport){ onPostComment(transport.responseText, eventId, postedFrom, newsId); },
		onFailure: function(transport){ onPostCommentFail(postedFrom); }
	});
}

function onPostComment(returnStatus, eventId, postedFrom, newsId) {
	var id = parseXML(returnStatus, "<ax([0-9])*:id>", "</ax([0-9])*:id>");
	var success = parseXML(returnStatus, "<ax([0-9])*:success>", "</ax([0-9])*:success>");
	var description = parseXML(returnStatus, "<ax([0-9])*:description>", "</ax([0-9])*:description>");
	
	if (postedFrom == 'news') {
		if(success == "true") {
			onCommentNewsPostSuccess(id, newsId);
		} else {
			onCommentNewsPostFail(description, newsId);
		}	
	} else if (postedFrom == 'mediaPopup') {
		if(success == "true") {
			onCommentMediaPost(id);
		} else {
			onCommentMediaPostFail(description);
		}
	} else { //posted from the picture viewer page
		if(success == "true") {
			onCommentPostFromPictureViewer(id);
		} else {
			onCommentPostFailFromPictureViewer(description);
		}
	}
}

function onPostCommentFail(postedFrom) {
	//live failure, reload the page
	if (postedFrom == 'news') {
		onCommentNewsPostFail("We're experiencing some problems, and your comment was not posted. Please reload the page and try again.")
	} else {
		onCommentMediaPostFail("We're experiencing some problems, and your comment was not posted. Please reload the page and try again.");
	}
}

/* COMMENT REMOVAL */

function removeCommentServer(id) {
	var sid = $("__sid").value; 
	var server = $("__server").value + "deleteEventComment";
	if(!sid || !server) {
		alert("no session id and/or server found");
		return;
	}
	
	//var status = $("statusText").value;
	
	new Ajax.Request(server,
	{
		method:'post',
		parameters: {sessionId: sid, commentId: id},
		onSuccess: function(transport){ onRemoveComment(transport.responseText); },
		onFailure: function(transport){ onRemoveCommentFail(transport); }
	});
}

function onRemoveComment(returnStatus) {
	//not so much...
}
function onRemoveCommentFail(transport) {
	//not so much
	alert('We\'re sorry. An error have occurred and the comment was not deleted. Please try again later.');
}

//copies the info in the registration-specific e-mail and password fields
//and pastes it in the login ones to avoid changes to loginOrRegister() which uses $("loginEmail").value etc
function correctInputFieldsAndRegister() {
	$('loginEmail').value = $('registerEmail').value;
	$('loginPassword').value = $('registerPassword').value;
	loginOrRegister();
}

function loginOrRegister() {
	var url = $("loginUri").value
	$("__uri").value = url
	
	var sid = $("__sid").value;
	var server = $("__server").value + "GCLoginOrCreateUser";
	var acode = $("__acode").value;
//			GCLoginOrCreateUser
//    	 	String applicationCode, 
//    	 	String sessionId, 
 
	var useragent = navigator.userAgent;
	var email = $("loginEmail").value;
	var password = $("loginPassword").value;
	
	if(!email || !password) {
		alert("email and/or password can't be empty");
		return false;
	}

	email = trim(email);
    var pattern=/^([a-zA-Z0-9_.-@])+/;
	if(email.indexOf(" ") > -1 || !pattern.test(email)) {
		alert("Email must be a valid email address and can't contain spaces or special characters");
		return false;
	}
	
	if(!server) {
		alert("no session id and/or server found");
		return false;
	}
	if(!sid) {
		sid = "";
	}
	
	new Ajax.Request(server,
	  {
	    method:'post',
	    parameters: {apiKey: acode, applicationCode: acode, sessionId: sid, param0: email, param1: password, useragent: useragent, ipaddress: "", ui: "Freya"},
	    onSuccess: function(transport){ onLogin(transport) },
	    onFailure: function(transport){ onLoginFailure(transport) }
	  });	
	//show loader
	$("loginOrRegisterButton").disabled=true;
	
	return false; //this makes the form not submit
}

function onLogin(transport) {
	var response = transport.responseText;
	
	//parse out session id and put it in var sid = $("__sid").value; 
	var returnStatus = parseXML(response, "<ax([0-9])*:returnStatus ", "</ax([0-9])*:returnStatus>");
	response = stripXML(response, "<ax([0-9])*:returnStatus ", "</ax([0-9])*:returnStatus>");
	var sessionId = parseXML(returnStatus, "<ax([0-9])*:sessionId>", "</ax([0-9])*:sessionId>");
	
	var success = parseXML(returnStatus, "<ax([0-9])*:success>", "</ax([0-9])*:success>");
 
	var shouldCreate = parseXML(response, "<ax([0-9])*:shouldCreate>", "</ax([0-9])*:shouldCreate>");
	response = stripXML(response, "<ax([0-9])*:shouldCreate>", "</ax([0-9])*:shouldCreate>");
	
	var userLoggedIn = parseXML(response, "<ax([0-9])*:userLoggedIn>", "</ax([0-9])*:userLoggedIn>");
	response = stripXML(response, "<ax([0-9])*:userLoggedIn>", "</ax([0-9])*:userLoggedIn>");

//done parsing	
	$("__sid").value = sessionId;
	if(shouldCreate == "true") {
		gotoRegistrationPage(3);
	} else if (userLoggedIn == "true") {
		deleteCampaignUserAndGoToUrl();
	} else {
		$("loginOrRegisterButton").disabled=false;
		incorrectPassword();
	}
}

function onLoginFailure(transport) {
	$("loginOrRegisterButton").disabled=false;
	alert("login failure\n"+transport.responseText);
}


function sendLiveRequest() {
	var sid = $("__sid").value;
	var server = $("__server").value + "getUpdateInfoBase";
	if(!sid || !server) {
		alert("no session id and/or server found");
		return;
	}
	var ts = getLiveTs();
	var params = null;
	if(ts == null || ts == 0) {
		params = {sessionId: sid};
	} else {
		server = $("__server").value + "getUpdateInfoWithTimestamp20";
		params = {sessionId: sid, timestamp: ts};
	}
	new Ajax.Request(server,
	  {
	    method:'post',
	    parameters: params,
	    onSuccess: function(transport){ onLive(transport) },
	    onFailure: function(transport){ onLiveFailure(transport) }
	  });
}

function getLiveTs() {
	var ts1 = 0;
	var chat = getCookie("chat");
	if(chat != null && chat.length > 0) {
		var x = chat.split(";");
		if(x.length > 1) {
			var z = x[1].split("=");
			if(z.length > 1) {
				ts1 = z[1];
			}
		}
	}
	var ret = null;
	var ts2 = $("__chat_ts").value;
	if(ts2 && ts2 > ts1) {
		ret = ts2;
	} else if (ts1 && ts1 > 0) {
		ret = ts1;
	} else {
		ret = null;
	}
	
	return ret;
}

function onLiveFailure(transport) {
	sendLiveRequest();
	//window.location.reload();
}

function removeFromChatListServer(userid, name) {
	//send to backend
	var sid = $("__sid").value;
	var server = $("__server").value + "deleteChatUser";
	
	if(!sid || !server) {
		alert("no session id and/or server found");
		return;
	}
	
	new Ajax.Request(server,
	  {
	    method:'post',
	    parameters: {sessionId: sid, apiKey: "freya", userId: userid}
	  });
}


function confirmMessage() {
	if(!$("chatInput")) {
		return;
	}
	
	if (confirm('We are a clean and friendly community for serious people and want to keep it that way. This is why we now ask for a small membership fee in order to allow chatting and flirting. Click OK to support this and quickly get back to the action.')) {
		window.location='/billing/';	
	}
}

function sendMessage() {
	if(!$("chatInput")) {
		return;
	}
	var description = $("chatInput").value;
	$("chatInput").value = "";
	if(!description) {
		alert("You cannot send an empty chat message!");
		return;
	}
	var sid = $("__sid").value;
	var server = $("__server").value + "postMessageDescription";
	
	if(!sid || !server) {
		alert("no session id and/or server found");
		return;
	}
	
	if($("chatUser")) {
		var currentChatUser = $("chatUser").value;

		new Ajax.Request(server,
		  {
		    method:'post',
		    parameters: {sessionId: sid, userId: currentChatUser, description: description}
		  });	
		
		var fromUserId = $("__user_id").value;
		printChatMessage(fromUserId, description);
		
		try {
			trackEvent("button - chat", "click - send message", "chat - send message");
		} catch(err) {}
	} else {
		//cant send message if not in chat
	}
}

function onLive(transport) {
	//alert('onLive');
	
	var response = transport.responseText;
	if(!response) {
		return;
	}
	
	//still logged in?
	var loggedIn = parseXML(response,"<ax([0-9])*:loggedIn>", "</ax([0-9])*:loggedIn>");
	if(!loggedIn || loggedIn == false || loggedIn == "false") {
		//alert("We're sorry, but the connection to the server was lost. The page will now reload to fix the problem - if it persists, please check your internet connection and/or try again later.");
		window.location.reload();
		return;
	}
	
	//parse the result
	var msg = parseMessage(response);
	response = stripMessage(response);
	var timestamp = 0;
	while(msg) {
		//handle message stuff
		
		var fromUserId = getFromUserId(msg);
		var description = getDescription(msg);
		timestamp = getDatetime(msg);
		if(fromUserId && description) {
			//should we put it in current chat or increase a counter
			if($("chatUser")) {
				var currentChat = $("chatUser").value;
				if(fromUserId == currentChat) {
					printChatMessage(fromUserId, description);
					markMessageRead(fromUserId);
				} else {
					increaseChatCounter(fromUserId);
					addNewMsg(timestamp); //changes the menu/chat header
				}
			} else {
				if($("__uri").value.search("/chat/") > -1) {
					increaseChatCounter(fromUserId);
				}
				addNewMsg(timestamp); //changes the menu/chat header
			}
		}

		msg = parseMessage(response);
		response = stripMessage(response);
	}

	if(timestamp > 0) {
		playSound('sound');		   		
		
		$("__chat_ts").value = timestamp;

		var x = $("menuNewMsgs").innerHTML;		

		//Trims the weird empty <a> tags...
		var pos1=x.indexOf("<a>");
		if (pos1>=0) {
			var pos2=x.indexOf("</a>");
			x = trim(x.substr(pos1+3, pos2));
		}
		x = parseInt(x);
		
		updateChat(x, timestamp);

		//var value = "unread=" +x+ ";ts=" +timestamp+ ";";
		//var expires = 2 * 60 * 60; //2 hours
		//setCookie("chat", encodeURIComponent(value), expires, "/", ".skout.com");
	} 

	
	//sends a new long polling request
	sendLiveRequest();
}

function markMessageRead(userId) {
	var sid = $("__sid").value;
	var server = $("__server").value + "markUserMessagesRead";
	
	if(!sid || !server) {
		alert("no session id and/or server found");
		return;
	}
	
	var currentChatUser = $("chatUser").value;
	new Ajax.Request(server,
	  {
	    method:'post',
	    parameters: {sessionId: sid, userId: userId}
	  });	
}

function getDatetime(response) {
	return parseXML(response, "<ax([0-9])*:dateTime>", "</ax([0-9])*:dateTime>");
}

function getDescription(response) {
	return parseXML(response, "<ax([0-9])*:description>", "</ax([0-9])*:description>");
}

function getSuccess(response) {
	return parseXML(response, "<ax([0-9])*:success>", "</ax([0-9])*:success>");
}

function getFromUserId(response) {
	return parseXML(response, "<ax([0-9])*:fromUserId>", "</ax([0-9])*:fromUserId>");
}

function parseXML(response, start, end) {
	var index1 = response.search(start);
	var description;

	if(index1 < 0) {
		return "";
	} else {
		description = response.substr(index1, response.length);
		index1 = description.indexOf(">");
		description = description.substr(index1+1, description.length);
	}

	var index2 = description.search(end);
	if(index2 < 0) {
		return "";
	}
	description = description.substr(0, index2);

	return description;
}

function stripXML(response, start, end) {
	var index1 = response.search(start);
	if(index1 < 0) {
		return "";
	} 
	
	var description = response.substr(index1, response.length);
	
	var index2 = description.search(end);
	if(index2 < 0) {
		return "";
	} else {
		var description2 = description.substr(index2, description.length);
		index2 += description2.indexOf(">")+1;
	}
	
	index2 += index1;
	
	var s = response.substr(0, index1);
	var e = response.substr(index2, response.length);
	
	return s+e;
}

function parseMessage(response) {
	var index1 = response.search("<ax([0-9])*:messageArray");
	if(index1 < 0) {
		return "";
	}
	index1 += "<ax21:messageArray".length;
	
	var description = response.substr(index1, response.length);
	index1 = description.indexOf(">");
	if(index1 < 0) {
		return "";
	}
	description = description.substr(index1+1, response.length);
	
	var index2 = description.search("</ax([0-9])*:messageArray>");
	if(index2 < 0) {
		return "";
	}
	description = description.substr(0, index2);
	
	return description;
}

function stripMessage(response) {
	return stripXML(response, "<ax([0-9])*:messageArray", "</ax([0-9])*:messageArray>");
}

function getTimestamp() {
	/* European standard, should be used when we let our users select which one to show
	var d = new Date();
	var hours = "";
	var minutes = "";
	if (d.getHours() < 10) {
		hours = "0" + d.getHours();
	} else {
		hours = "" + d.getHours();
	}
	if (d.getMinutes() < 10) {
		minutes = "0" + d.getMinutes();
	} else {
		minutes = "" + d.getMinutes();
	}
	
	return hours + "." + minutes;
	*/
	
	var d = new Date();
	var hours = "";
	var minutes ="";
	var suffix = "";
	
	if (d.getHours() < 12) {
		hours = "" + d.getHours();
		suffix = "AM";
	} else {
		hours = "" + d.getHours() - 12;
		suffix = "PM";
	}
	
	if (d.getMinutes() < 10) {
		minutes = "0" + d.getMinutes();
	} else {
		minutes = "" + d.getMinutes();
	}
	
	return hours + ":" + minutes + " " + suffix;
}



/*
//creates a form on the fly in order to update user picture directly after registering
//Run this after the user have been logged in
function createAndSubmitUploadForm(elementValue){
	if (elementValue != "" && elementValue != null) {
		var submitForm = document.createElement("FORM");
	 	document.body.appendChild(submitForm);
	 	
	 	submitForm.method = "POST";
	 	submitForm.action= "/support/updateUserPicture.jsp";
	 	submitForm.encoding = "multipart/form-data";
	 	
	 	//create a file input element
	 	var inputElement = document.createElement("<input id=\"fileInput\" type=\"file\" name=\"Filedata\" accept=\"image/bmp,image/gif,image/jpeg,image/png\" style=\"visibility:hidden;\">"); 
	 	
	 	inputForm.appendChild(inputElement);
	 	inputElement.value = elementValue;
	 	
	 	alert('OK, submitting the form with value:' + inputElement.value +' and action'+ submitForm.action +'.');
	 	
	 	//submits the form
	 	submitForm.submit();
	}
}
*/

function copyFileInfo() {
	$('fakeInput').value = $('fileInput').value;
}

function continueHover(isOver) {
	if ($('reg_continueButton_disabled').style.visibility == "visible") {
		return false;
	}
	
	if (isOver == 'true') {
		$('reg_continueButton').style.visibility = 'hidden';
		$('reg_continueButton_hover').style.visibility = 'visible';
	} else {
		$('reg_continueButton_hover').style.visibility = 'hidden';
		$('reg_continueButton').style.visibility = 'visible';
	}
}

function enableOrDisableContinue() {
	if ($('reg_continueButton_disabled').style.visibility=="hidden") {
		$('reg_continueButton').style.visibility="hidden";
		$('reg_continueButton_hover').style.visibility="hidden";
		$('reg_continueButton_disabled').style.visibility="visible";
	} else {
		$('reg_continueButton').style.visibility="visible";
		$('reg_continueButton_hover').style.visibility="hidden";
		$('reg_continueButton_disabled').style.visibility="hidden";
	}
}

function displayRegisterLoader() {
	$('fileInput').style.visibility = 'hidden';
	$('loadingInfo').style.visibility = 'visible';
	$('loadingBar').style.visibility = 'visible';
}

function printNameAge() {
	var s = '';
	s+= '<a href="/profile/id?='+$("__user_id").value+'">';
	s+= $("__user_username").value;
	//s+= ', ';
	//s+= $("__user_sex").value;
	s+= '</a>';
}









/* COMMENT POSTING FROM NEWS -- MAY BE IN AN OWN JS FILE COVERING HOME AND PROFILE... */

function toggleCommentInput(newsId) {
	try {
		var inputElementId = 'commentInputElement_' + newsId;
		var inputElement = $(inputElementId);

		if (inputElement.style.display == 'none') {
			//$(inputElementId+'').style.height = '36';
			$(inputElementId+'').style.display = 'block';
			//Effect.BlindDown(inputElementId+'', { duration: 0.5 });			
		} else {
			$(inputElementId+'').style.display = 'none';
			//Effect.BlindUp(inputElementId+'', { duration: 0.5 });			
		}
	} catch(err) {}
}

function postCommentFromNews(newsId, eventId) {
	var postButton = Element.extend($('commentPostButton_' + newsId));
	var textArea = Element.extend($('commentTextArea_' + newsId));
	var postElement = Element.extend($('commentInputElement_' + newsId));
	
	//disable button and textfield until comment is successfully posted
	postButton.disabled = true;
	textArea.disabled = true;
	
	//post comment to the server
	var comment = textArea.value;
	postCommentServer(comment, eventId, 'news', newsId);
	
	//TODO: Don't add a comment if there's already an element with the same id - i.e. a comment is posted after a database addition have failed
	
	var id = new Date().getTime()+"_status";
	var c = '';

	c+= '<div id=\"newCommentFromNews\" class=\"postedCommentElement\">';
		c+= '<img class=\"commentFromImage thumb32\" src=\"' + $("__user_pictureUrl").value + '_tn32.jpg\"/>';
		c+= '<div class=\"commentMain\">';
			c+= '<strong>' + $("__user_firstName").value + '</strong>: ' + comment;
		c+= '</div>';
		c+= '<div class=\"infoRow\">';
			c+= getTimestamp() + ' &middot; right here';
		c+= '</div>';
	c+= '</div>';
	
    Element.insert(postElement, {'before': c});
    //Effect.BlindUp(postElement, { duration: 0.5 });
}

function onCommentNewsPostSuccess(commentId, newsId) {
	//get the button, input and remove link
	var postButton = $("commentPostButton_"+newsId);
	var textArea = $("commentTextArea_"+newsId);
	//var removeLink = $("REMOVELINKNAME");
	
	//give the remove button of the new comment its correct onclick behaviour, and visually "activate" it
	//removeLink.onclick = function() {removeComment(commentId);}
	
	//remove the id of the button to avoid id clashes when multiple comments are posted
	//$("newCommentRemoveBtn").id = '';
	
	//give correct id to the new comment in the list
	$("newCommentFromNews").id = commentId;

	//enable button and textArea, clear the textArea to allow more comments
	textArea.value = "";
	postButton.disabled = false;
	textArea.disabled = false;
	
	//limitTextArea();
}

function onCommentNewsPostFail(description) {
	//remove the fail
	//removeComment("newComment");
	
	//enable input again
	//var postButton = $("postButton");
	//var textArea = $("commentInput");
	//textArea.value = "";
	//postButton.disabled = false;
	//textArea.disabled = false;
	
	//limitTextArea();
	
	//explain why
	alert('Your comment was not posted: \n\r\n\rReason: '+description);
}
















/* Upload popup scripts */
function limitAttach() {
	var extArray = new Array(".gif", ".jpg", ".jpeg", ".bmp", ".png");
	var form = $('uploadPictureForm');
	var file = form.fileInput.value;
	
	var allowSubmit = false;
	
	if (!file) return;
	while (file.indexOf("\\") != -1) {
		file = file.slice(file.indexOf("\\") + 1);
	}
	var ext = file.slice(file.indexOf(".")).toLowerCase();
	for (var i = 0; i < extArray.length; i++) {
		if (extArray[i] == ext) { 
			allowSubmit = true; break; 
		}
	}
	
	if (allowSubmit) {
		form.submit();
		saveButtonClicked();
		try {trackEvent('button - add photo', 'click - add photo save', 'add photo - add photo save');} catch (err) {}
	} else {
		alert("Please only upload files that end in types:\n  " + (extArray.join("  ")) + "\nPlease select a new " + "file to upload and submit again.");
	}
}

function uploadProfileCheckChange(checkbox) {
	if (checkbox.checked) {
		$('uploadPictureForm').action = '/support/updateUserPicture.jsp';
	} else {
		$('uploadPictureForm').action = '/support/postEventComplete.jsp';
	}
}

function saveButtonClicked() {
	$('imageUploadSaveButton').disabled = true;
	$('loadingImage').style.visibility='visible';
}







function newsCommentTextAreaClick(ta) {
	if (ta.value == 'Write a comment...') { ta.value = ''; }
	ta.style.color = '#333';
}
/*
function newsCommentTextAreaKeyUp(ta) {
	var MAX_LENGTH = 500;
	if (ta.value.length > MAX_LENGTH) { ta.value = ta.value.substr(0, MAX_LENGTH); }
	else ()
}
*/







/* Append the FB stylesheet if viewed inside facebook */ 
function doFacebookCheck() {
	//alert('parent.frames.length: ' + parent.frames.length + ' ||| frames.top==frames.self: ' + (frames.top == frames.self));
	
	if (!(frames.top == frames.self)) {
		//alert('In facebook, running resize...');
		FB_RequireFeatures(["XFBML"], function(){ FB.CanvasClient.startTimerToSizeToContent(); });
		//alert('In facebook, will change stylesheet...');
		var i, a;
		for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
			if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
				a.disabled = true;
				if(a.getAttribute("title") == "facebookCSS") { a.disabled = false };
			}
		}
/*
		for(i=0; (a = document.getElementsByTagName('link')[i]); i++) {
			if(a.getAttribute('title') == 'freyaCSS') { alert('disabling freya css'); a.disabled = true; }
			if(a.getAttribute('title') == 'facebookCSS') { alert('enabling fb css'); a.disabled = false; }
		}
*/
		//alert('Facebook mode: ON.');
	} else {
		//alert('No facebook found');
	}
}


/* --- */




function toggleGiftModule() {
	if ($('giftModule').style.display == 'none') {
		$('giftModule').style.display = 'block';
	} else {
		$('giftModule').style.display = 'none';
	}
}

function giftMO(id, isOver, stock, points) {
	//alert('isOver' + isOver);
	if (isOver) {
		$(id+'_text').update(stock + ' in stock'); //CHANGE: GIFTS IN STOCK
	} else {
		$(id+'_text').update(points + ' Points'); //CHANGE: GIFT PRICE
	}
}

function userGiftMO(id, isOver, stock, name) {
	if (isOver) {
		$(id+'_text').update(name); //CHANGE: GIFTS IN STOCK
	} else {
		$(id+'_text').update('x'+stock); //CHANGE: GIFT PRICE
	}
}

function selectProfileGift(id, name) {
	deselectAllGifts();
	$('sendGiftButton').style.color='#FF00CC';
	$('sendGiftButton').value = 'Send ' + name +'!';
	$(id).style.borderColor = '#FF00CC';
	$(id).className='giftSelected';
}

function deselectAllGifts() {
	var allGifts = $$('.giftsTable td');
	for (var index=0; index<allGifts.length; ++index) {
		var item = allGifts[index];
		item.style.borderColor = '#f6f6f6';
		item.className='gift';
	}
}


function sendStoreGift() {
	var giftId;
	var gifts = $$('.giftSelected');
	if( gifts.length==0 ) {
		alert('Please select a gift!');		
	} else {
		giftId = gifts[0].id;
		giftId = trim(giftId.substr(5,giftId.length));
	}
		
	//$('sendGiftButtonDisabled').style.visibility='visible';
	//$('sendGiftButton').style.display='none';
	$('sendGiftButton').disabled = true;
	$('sendGiftLoader').style.visibility='visible';
	
	
	makeSendGiftCall(giftId);
}

function makeSendGiftCall(giftId) {
	//alert('1');

	var fromPage = $('giftSentFromWhere').value;
	var profileId = $("profileid").value;
	if($("__sid")) {
		//alert('2');	
		var sid = $("__sid").value;
		var server = $("__server").value + "GCSendStoreGift";

		if(!sid || !server) {
			alert("no session id and/or server found");
			return;
		}

		//alert('sessionId:'+sid+' userId:'+profileId+' giftId:'+giftId);	
		new Ajax.Request(server, {
		    method:'post',
		   	parameters: {apiKey: "freya", applicationCode: "freya", sessionId: sid, userId: profileId, giftId: giftId},
		    onSuccess: function(transport){ sendStoreGiftDone(transport.responseText, fromPage) },
		    onFailure: function(transport){ sendStoreGiftFailure(transport.responseText) }
		});
	  
  	} else {
		alert("You need to be logged in to purchase a gift");
	}
}

function makeSendGiftTeaserCall(giftId) {
	//alert('1');

	var fromPage = $('giftSentFromWhere').value;
	var profileId = $("profileid").value;
	if($("__sid")) {
		//alert('2');	
		var sid = $("__sid").value;
		var server = $("__server").value + "GCSendStoreGift";

		if(!sid || !server) {
			alert("no session id and/or server found");
			return;
		}

		//alert('sessionId:'+sid+' userId:'+profileId+' giftId:'+giftId);	
		new Ajax.Request(server, {
		    method:'post',
		   	parameters: {apiKey: "freya", applicationCode: "freya", sessionId: sid, userId: profileId, giftId: giftId},
		    onSuccess: function(transport){ sendStoreGiftTeaserDone(transport.responseText, fromPage, giftId) },
		    onFailure: function(transport){ sendStoreGiftFailure(transport.responseText) }
		});
	  
  	} else {
		alert("You need to be logged in to purchase a gift");
	}
}
function sendStoreGiftDone(response, fromPage) {
	//alert('sendStoreGiftDone :: frompage: ' + fromPage + 'response: ' + response);
	var success = parseXML(response, "<ax([0-9])*:success>", "</ax([0-9])*:success>");
	var desc = parseXML(response, "<ax([0-9])*:description>", "</ax([0-9])*:description>");
	
	var profileId = $("profileid").value;

	if(success == "false") {
		var gifts = $$('.giftSelected');
		if( gifts.length==0 ) {
			alert('Please select a gift!');		
		} else {
			var giftid = gifts[0].id;
			giftid = trim(giftid.substr(5,giftid.length));
			var billingUrl = '/billing/points/?backUrl='+encodeURIComponent('/profile/'+profileId+'/?sendStoreGift='+giftid);
			billingUrl+='&cancelUrl='+encodeURIComponent('/profile/'+profileId+'/');
			billingUrl+='&message='+encodeURIComponent('You do not have enough points to send this gift. <a href="javascript:history.go(-1);" style="border-bottom:1px solid #fff;">Go back</a>, or top up your account to continue to play.');
			document.location.href=billingUrl;
		}
	} else {
		if (fromPage == "chat") {
			window.location.reload();
		} else {
			document.location.href='/profile/'+profileId+'/?message='+encodeURIComponent('Well done! Your gift has been sent!');
		}
		
	}
}

function sendStoreGiftTeaserDone(response, fromPage, giftid) {
	//alert('sendStoreGiftDone :: frompage: ' + fromPage + 'response: ' + response);
	var success = parseXML(response, "<ax([0-9])*:success>", "</ax([0-9])*:success>");
	var desc = parseXML(response, "<ax([0-9])*:description>", "</ax([0-9])*:description>");
	
	var profileId = $("profileid").value;

	if(success == "false") {
		var billingUrl = '/billing/points/?backUrl='+encodeURIComponent('/profile/'+profileId+'/?sendStoreGift='+giftid);
		billingUrl+='&cancelUrl='+encodeURIComponent('/profile/'+profileId+'/');
		billingUrl+='&message='+encodeURIComponent('You do not have enough points to send this gift. <a href="javascript:history.go(-1);" style="border-bottom:1px solid #fff;">Go back</a>, or top up your account to continue to play.');
		document.location.href=billingUrl;
	} else {
		if (fromPage == "chat") {
			window.location.reload();
		} else {
			document.location.href='/profile/'+profileId+'/?message='+encodeURIComponent('Well done! Your gift has been sent!');
		}		
	}
}
function sendStoreGiftFailure(response) {
	alert("We're sorry, but there was a technical problem with sending your gift. You have not been charged, so please try again shortly.");
	//enable button clicks and show loader again
	//$('sendGiftButtonDisabled').style.visibility='hidden';
	//$('sendGiftButton').style.display='block';
	$('sendGiftButton').disabled='false';
	$('sendGiftLoader').style.visibility='hidden';
	
}

function onStoreGifts(transport) {	
	var response = transport.responseText;
	$('giftModule').update(response);
}

function onStoreGiftsFailure(transport) {	
	var response = transport.responseText;
}			

function getStoreGifts(p, c, o) {
	var server = $("__domain").value + "profile/storeGifts.jsp";

	if(!server) {
		alert("no server found");
		return;
	}
	
	new Ajax.Request(server, {
	    method:'post',
	    parameters: {categoryId: c, offset: o, profileId: p},
	    onSuccess: function(transport){ onStoreGifts(transport) },
	    onFailure: function(transport){ onStoreGiftsFailure(transport) }
	  });
}

function onStoreGifts(transport) {	
	var response = transport.responseText;
	$('giftModule').update(response);
}

function onStoreGiftsFailure(transport) {	
	var response = transport.responseText;
}			

function getUserGifts(p, c, o) {
	var server = $("__domain").value + "profile/userGifts.jsp";

	if(!server) {
		alert("no server found");
		return;
	}

	new Ajax.Request(server, {
	    method:'post',
	    parameters: {categoryId: c, offset: o, profileId: p},
	    onSuccess: function(transport){ onUserGifts(transport) },
	    onFailure: function(transport){ onUserGiftsFailure(transport) }
	  });				
}

function onUserGifts(transport) {
	var response = transport.responseText;
	$('userGiftModule').update(response);
}

function onUserGiftsFailure(transport) {	
	var response = transport.responseText;
}			

function storeCategoryChanged() {
	getStoreGifts($("profileid").value,$('storeCategoryInput').value,0);
}


function toggleShowAllGifts() {
	var rows = $$('.invisibleGiftRow');
	
	var display = '';
	if (rows[0].style.display=='none') {
		display = 'table-row';
	} else {
		display = 'none';
	}
	
	for (var index=0; index<rows.length; ++index) {
		rows[index].style.display=display; 
	}
}

/* ------------------------ */
/* Placing bids, look at me */
/* ------------------------ */

function placeBidFromAd() {
	//disable confirm and back buttons
	$('goBackButton').onclick = null;
	$('confirmButton').style.display = 'none';
	$('confirmButtonDisabled').style.visibility = 'visible';
	$('confirmButtonLoader').style.visibility = 'visible';
	isLookAtMe($('bidInput').value);
}

function isLookAtMe(bid) {
	var sid = $("__sid").value;
	var server = $("__server").value + "GCIsLookAtMe";

	if(!server) {
		alert("no session id and/or server found");
		return;
	}
	
	new Ajax.Request(server,
	  {
	    method:'post',
	    parameters: {apiKey: "d46dbe487d5baaa0b176cb55d3bc452c", applicationCode: "d46dbe487d5baaa0b176cb55d3bc452c", sessionId: sid},
		onSuccess: function(transport){ onIsLookAtMeSuccess(transport.responseText, bid); },
		onFailure: function(transport){ onIsLookAtMeFail(transport.responseText); }
	  });
}

function onIsLookAtMeSuccess(response, bid) {
	var success = parseXML(response, "<ax([0-9])*:success>", "</ax([0-9])*:success>");
	var desc = parseXML(response, "<ax([0-9])*:description>", "</ax([0-9])*:description>");
	var overwriteBidOK = false;

	if(success == "false") { // user is not on the "look at me" board
		overwriteBidOK = true;
	} else { // user has already a bid on look at me board, ask for overwriting permission
		if(confirm('You already have an active bid. Would you like to overwrite it?')) {
			overwriteBidOK = true;
		}
	}
	
	if (overwriteBidOK) { // send another SOAP call to check if he has enough points	
		sendLookAtMe(bid);
	} else {
		window.location='/lookAtMe/';
	}
}

function onIsLookAtMeFail(response) {
	window.location='/lookAtMe/?messageFromAd=Sorry! Something went wrong and your bid was not placed. No points was charged, so please try again later!';
}

function sendLookAtMe(points) {
	var sid = $("__sid").value;
	var server = $("__server").value + "GCSendLookAtMe";

	if(!server) {
		//alert("no session id and/or server found");
		window.location='/lookAtMe/?messageFromAd=Sorry! Something went wrong and your bid was not placed. No points was charged, so please try again later!';
		return;
	}
	
	new Ajax.Request(server,
	  {
	    method:'post',
	    parameters: {apiKey: "d46dbe487d5baaa0b176cb55d3bc452c", applicationCode: "d46dbe487d5baaa0b176cb55d3bc452c", sessionId: sid, points:points},
		onSuccess: function(transport){ onSendLookAtMeSuccess(transport.responseText, points); },
		onFailure: function(transport){ onSendLookAtMeFail(transport.responseText); }
	  });
}

function onSendLookAtMeSuccess(response, bid) {
	var success = parseXML(response, "<ax([0-9])*:success>", "</ax([0-9])*:success>");
	var desc = parseXML(response, "<ax([0-9])*:description>", "</ax([0-9])*:description>");
	if (success == "true") {
		window.location='/lookAtMe/?messageFromAd=Cool, your bid has been placed! Good luck!';
	} else {
		window.location='/billing/points/?backUrl='+encodeURIComponent('/lookAtMe/')+'&message=Not enough points! :( Please refill your account to start bidding.';
	}
}

function onSendLookAtMeFail(response) {
	window.location='/lookAtMe/?messageFromAd=Sorry! Something went wrong and your bid was not placed. No points was charged, so please try again later!';
}


function formatTimeLeft(secondsRemaining) {
	var out;
	var minutes;
	var hours;
   	minutes = Math.floor((secondsRemaining/60)%60);
   	hours = Math.floor(secondsRemaining/3600);
   
   	if (hours>0) {
   		out+="0"+hours;
   	} else {
   		out+="00";
   	}
   	out+=":";
   	if (minutes>9) {
   		out+=""+minutes;
   	} else if (minutes<1) {
   		out+="00";
   	} else {
   		out+="0"+minutes;
   	}
   	return out;
}



function highlightLAM(id, isOver) {
	if (isOver) {		
		$('LAMImage_'+id).style.borderColor='#fff';
		$('LAMRow_'+id).style.color = '#fff';
		//$('LAMRow_'+id).backgroundImage = 'url(/images2/freya/framework/lookAtMeBackgroundRowHighlight.png)';
		//$('LAMRow_'+id).className = 'LAMRowHighlight';
		$('LAMRow_'+id).style.backgroundColor='#888';		
	} else {
		$('LAMImage_'+id).style.borderColor='#222';
		$('LAMRow_'+id).style.color = '#333';
		//$('LAMRow_'+id).backgroundImage = '';
		//$('LAMRow_'+id).className = '';
		//$('LAMRow_'+id).style.borderColor='#'+rowBgColor;
		$('LAMRow_'+id).style.backgroundColor='#fff';
	}
}

function toggleSetLocation() {
	if ($('setLocationBox').style.display == 'none') {
		$('setLocationBox').style.display = 'block';
	} else {
		$('setLocationBox').style.display = 'none';
	}
}

function showRemoveAccountBox() {
	$('removeAccountBox').style.display='block';
}

function removeAccount() {
	if (confirm('Are you sure you want to remove your account? This action cannot be undone.')) {
		window.location='/accountRemoval.jsp?reasonId='+$('reasonId').value;
	}
}



/* Commenting on pictures */
function checkFirstFocus() {
	var textArea = $("commentInput");
	if (textArea.value == "Write a comment!") {
		textArea.value = "";
	}
	textArea.style.color = "#333333";
	limitTextArea();
}

function limitTextArea() {
	var textArea = $("commentInput");
 	var maxChars = 500;
	var charsRemainingBox = $("charsRemaining");
 	var postButton = $("postButton");
 	postButton.disabled = false;
	if (textArea.value.length > maxChars){
		textArea.value = textArea.value.substring(0, maxChars);
	} else if (textArea.value.length <= 0) {
		postButton.disabled = true;
	} else{
		charsRemainingBox.update(maxChars - textArea.value.length);
	}
}

function postComment(eventId) {
	var postButton = $("postButton");
	var textArea = $("commentInput");
	var commentsHolder = $("commentsHolder");
	
	//disable button and textfield until comment is successfully posted
	postButton.disabled = true;
	textArea.disabled = true;
	
	//post comment to the server
	var comment = textArea.value;
	postCommentServer(comment, eventId, 'pictureViewer', '');
	
	//add a comment to the list
	//TODO: Don't add a comment if there's already an element with the same id - i.e. a comment is posted after a database addition have failed
	var c = '<div style="margin-top:6px;" id="newComment">';
		c+= '<a href="/profile/?id='+$("__user_pictureUrl").value+'">';
			c+=	'<img src="'+$("__user_pictureUrl").value+'_tn50.jpg" style="float:left; width:50px; height:50px;" />';
		c+= '</a>';
		c+= '<div style="background:#ddd; -moz-border-radius:0px 5px 5px 5px; padding:5px; margin-left:60px; ">';
			c+= '<a href="/profile/?id='+$("__user_pictureUrl")+'">';
			c+= '<span style="font-weight:bold;">'+$("__user_firstName").value+'</a>:</span>';
			c+= '&nbsp;'+comment;
		c+= '</div>';	
		
		c+= '<div style="padding:5px; margin-left:60px; font-size:10px;">';
			c+= getTimestamp();
			c+= '&nbsp;&middot;&nbsp;';	
			c+= '<span id="newCommentRemoveSpan">remove comment</span>';	
		c+= '</div>';
	c+= '</div>';
	
	var nl = Element.extend($("newsList"));
    
    //If it's the first comment, remove the "be the first one to comment"; i.e. use update instead of insert.
   // alert('is first comment: ' + commentsHolder.firstDecendant().hasClassName('commentsHolderInner');
    if (commentsHolder.firstDescendant().hasClassName('commentsHolderInner')) {
    	commentsHolder.update(c);
    } else {
    	Element.insert(commentsHolder, {'top': c});
    }
    
    Effect.BlindDown('newComment', { duration: 0.5 });
}

function onCommentMediaPost(commentId) {
	var postButton = $("postButton");
	var textArea = $("commentInput");
	
	//give the new comment's remove button its correct onclick behaviour 
	$("newCommentRemoveBtn").onclick = function() {removeComment(commentId);}
	$("newCommentRemoveBtn").src = '/images/freya/common/icons/removeComment24.png';
	
	//remove the id of the button to avoid id clashes when multiple comments are posted
	$("newCommentRemoveBtn").id = '';
	
	//give correct id to the new comment in the list
	$("newComment").id = commentId;

	//enable button and textArea, clear the textArea to allow more comments
	textArea.value = "";
	postButton.disabled = false;
	textArea.disabled = false;
	
	limitTextArea();
}

function onCommentMediaPostFail(description) {
	//remove the fail
	removeComment("newComment");
	
	//enable input again
	var postButton = $("postButton");
	var textArea = $("commentInput");
	textArea.value = "";
	postButton.disabled = false;
	textArea.disabled = false;
	
	limitTextArea();
	
	//explain why
	alert('We\'re sorry, but your comment was not posted. Please try again later! \n\r\n\rReason: '+description);
}

function onCommentPostFromPictureViewer(commentId) {
	var postButton = $('postButton');
	var textArea = $("commentInput");
	
	//give the new comment's remove button its correct onclick behaviour 
	$("newCommentRemoveSpan").onclick = function() {removeComment(commentId);}
	$("newCommentRemoveSpan").style.color = '#0055aa';
	$("newCommentRemoveSpan").style.cursor = 'pointer';
	//remove the id of the button to avoid id clashes when multiple comments are posted
	$("newCommentRemoveSpan").id = '';
	//give correct id to the new comment in the list
	$("newComment").id = commentId;

	//enable button and textArea, clear the textArea to allow more comments
	textArea.value = "Write a comment!";
	
	postButton.disabled=false;
	//postButton.removeAttribute('disabled');
	textArea.disabled=false;
	
	limitTextArea();
}

function onCommentPostFailFromPictureViewer(commentId) {
	//remove the fail
	removeComment("newComment");
	
	//enable input again
	var postButton = $("postButton");
	var textArea = $("commentInput");
	textArea.value = "";
	postButton.disabled = false;
	textArea.disabled = false;

	limitTextArea();
	
	//explain why
	alert('We\'re sorry, but your comment was not posted. Please try again later! \n\r\n\rReason: '+description);
}



function displayReportReasonChat() {
	if ($('reportReasonHolder').style.display == 'none') {
		Effect.BlindDown('reportReasonHolder', { duration: 0.5 });
	} else {
		Effect.BlindUp('reportReasonHolder', { duration: 0.5 });
	}
}

function reportProfile(userId, reasonId) {
	var sid = $("__sid").value;
	var server = $("__server").value + "GCReportUser";

	if(!server) {
		alert("no session id and/or server found");
		return;
	}
	$('reportReasonHolder').style.color = '#000';
	$('reportReasonHolder').update('The profile have been reported and will be reviewed by our staff shortly. Thank you!');
	
	new Ajax.Request(server,
	  {
	    method:'post',
	    parameters: {apiKey: "d46dbe487d5baaa0b176cb55d3bc452c", applicationCode: "d46dbe487d5baaa0b176cb55d3bc452c", sessionId: sid, userId: userId, reasonId: reasonId},
		onSuccess: function(transport){ onReportProfileSuccess(); },
		onFailure: function(transport){ onReportProfileFail(transport.responseText); }
	  });
}

function onReportProfileSuccess() {
	//$('reportReasonHolder').style.color = '#000';
	//$('reportReasonHolder').update('The profile have been reported and will be reviewed by our staff shortly. Thank you!');
}
function onReportProfileFail(transport) {
	alert('Something went wrong: ' + transport.responseText);
}








function removeComment(id) {
	if(confirm("Are you sure you want to remove this comment?")) {
		$(id+'').blindUp({ duration: 1 });
		removeCommentServer(id);
	}
}

/* Getting all the user's images */
function getAllImagesGrid(uid, eventId) {
	var server = $("__domain").value + "photo/allImagesGridModule.jsp?eventId="+eventId;

	if(!server) {
		alert("no server found");
		return;
	}
	
	new Ajax.Request(server, {
	    method:'post',
	    parameters: {userId: uid},
	    onSuccess: function(transport){ onGetAllImagesGrid(transport) },
	    onFailure: function(transport){ onGetAllImagesGridFailure(transport) }
	  });
}

function onGetAllImagesGrid(transport) {	
	var response = transport.responseText;
	$('allImagesGridHolder').update(response);
}

function onGetAllImagesGridFailure(transport) {	
	var response = transport.responseText;
}

function removeFromImageGrid(eventId) {
	var gridImages = $$('#allImagesGridHolder img');
	for (var index=0; index<gridImages.length; ++index) {
		if (gridImages[index].name == eventId) {
			gridImages[index].remove();
		}
	}
}

/* Getting comments for the image */
function getComments(i, o) {
	if (i == 0) {
		$('commentsHolderInner').style.background = '#fcc';
		$('commentsHolderInner').style.color = '#333';
		$('commentsHolderInner').update('An error occurred when fetching the comments :(');
		return;
	}
	
	var server = $("__domain").value + "photo/commentsModule.jsp";
	if(!server) {
		alert("no server found");
		return;
	}
	
	new Ajax.Request(server, {
	    method:'post',
	    parameters: {offset: o, id: i},
	    onSuccess: function(transport){ onGetComments(transport, i) },
	    onFailure: function(transport){ onGetCommentsFailure(transport) }
	  });
}

function onGetComments(transport, commentsEventId) {
	//Sanity check if the the found comments are to the right image
	
	var mainImages = $$('#mediaHolder img');
	for (var index=0; index<mainImages.length; ++index) {
		if (mainImages[index].style.display != 'none') {
			if (mainImages[index].name == commentsEventId) { //comments and visible image are matching
				var response = transport.responseText;
				$('commentsHolder').update(response);
				//break;
				return;			
			} else { //wrong comments have been fetched. Re-fetch.
				getComments(mainImages[index].name, 0);
			}	 
		}
	}
}

function onGetCommentsFailure(transport) {	
	var response = transport.responseText;
	alert('Could not load comments.');
}

function switchMainImage(picUrl, eventId) {
	//main image
	$('mainImage').src = picUrl+'_bg.jpg';
}

function displayReportReason() {
	$('clickToReport').style.display='none'; 
	$('reportFinished').style.display='none';
	$('reportDetails').style.display='inline';
}

function displayReportReasonProfile() {
	$('reportReasonHolder').style.display='block';
}

function revertReportReason() {
	if ($('clickToReport') != null) {
		$('clickToReport').style.display='inline'; 
		$('reportDetails').style.display='none';
		$('reportFinished').style.display='none';
	}
}

function reportImage(eventId) {
	var reasonId = $('reportReason').value;
	var sid = $("__sid").value;
	var server = $("__server").value + "GCReportPicture";

	if(!server) {
		alert("no session id and/or server found");
		return;
	}
	
	//$('reportImageButton').disabled = true;
	$('clickToReport').style.display = 'none';
	$('reportDetails').style.display = 'none';
	$('reportFinished').style.display = 'inline';
	
	new Ajax.Request(server,
	  {
	    method:'post',
	    parameters: {apiKey: "d46dbe487d5baaa0b176cb55d3bc452c", applicationCode: "d46dbe487d5baaa0b176cb55d3bc452c", sessionId: sid, eventId: eventId, reasonId: reasonId},
		onSuccess: function(transport){ onReportImageSuccess() },
		onFailure: function(transport){ onReportImageFail(transport.responseText) }
	  });
}

function onReportImageSuccess() {
	alert('The image with id '+eventId+' was reported!');
}

function onReportImageFail(transport) {
	revertReportReason();
	alert('Something went wrong and the picture was not reported. Please try again later, or send a message to support@skout.com.');
}

function removeImage(eventId) {
	if (confirm('Are you sure you want to remove this picture?')) {
		var sid = $("__sid").value;
		var server = $("__server").value + "GCDeleteEvent";

		if(!server) {
			alert("no session id and/or server found");
			return;
		}
		
		new Ajax.Request(server,
		  {
		    method:'post',
		    parameters: {apiKey: "d46dbe487d5baaa0b176cb55d3bc452c", applicationCode: "d46dbe487d5baaa0b176cb55d3bc452c", sessionId: sid, eventId: eventId},
			onSuccess: function(transport){ onRemoveImageSuccess(eventId) },
			onFailure: function(transport){ onRemoveImageFail(transport.responseText) }
		  });
	}
}

function onRemoveImageSuccess(eventId) {
	removeFromImageGrid(eventId)
	gotoNextImage();
}

function onRemoveImageFail(transport) {
	alert('Something went wrong and the picture was not deleted. Please try again later or contact support@skout.com.');
}

function addBigImageYeah(url, eventId, isActive) {
	// if the image you're about to add is the same as the one that's on top of the canvas, move the top one to the right place instead
	// of adding a new element of the same kind
	  
	var e;
	if (isActive) {
		e = $('mediaHolder').firstDescendant();
		$('mediaHolder').firstDescendant().remove();
	} else {
		var urlFull = url+'_bg.jpg';
		e = new Element('img', {src: urlFull+'', name: eventId+''});
		e.style.display='none';
	}
	
	$('mediaHolder').insert({bottom: e});
	
	e.onclick = function() { gotoNextImage(); }
}

function adminRemoveImage(eventId) {
	if (confirm('Are you sure you want to remove this image?')) {
		var mainImages = $$('#mediaHolder img');
		var image;
		var foundCurrent = false;
		
		for (var index=0; index<mainImages.length; ++index) {
			image = mainImages[index];
			if (foundCurrent == true) {
				foundCurrent = false;
				window.location = '/photo/'+image.name+'/?admindeleteid='+eventId;
				return;
			}
			if (image.style.display != 'none') {
				foundCurrent = true;
			}
		}	
		
		if (foundCurrent == true) {
			foundCurrent = false;
			window.location = '/photo/'+image.name+'/?admindeleteid='+eventId;
			return;
		}
	}
}

function gotoNextImage() {
	var mainImages = $$('#mediaHolder img');
	var image;
	var foundCurrent = false;
	
	for (var index=0; index<mainImages.length; ++index) {
		image = mainImages[index];
		if (foundCurrent == true) {
			foundCurrent = false;
			image.style.display = 'inline';
			image.onclick = function() { gotoNextImage(); }
			handleImageChangeFunctions(image.name);
			break;
		}
		if (image.style.display != 'none') {
			image.style.display = 'none';
			//image.fade({ duration: 0.5 });
			foundCurrent = true;
		}
	}	
	
	//the loop is over and foundCurrent is still true - the final image was the visible one and we should show the first one again
	if (foundCurrent == true) {
		mainImages[0].style.display = 'inline';
		foundCurrent = false;
	}
}

function gotoPreviousImage() {
	var mainImages = $$('#mediaHolder img');
	var image;
	var foundCurrent = false;
	
	for (var index=mainImages.length-1; index>=0; --index) {
		image = mainImages[index];
		
		if (foundCurrent == true) {
			foundCurrent = false;
			image.style.display = 'inline';
			image.onclick = function() { gotoNextImage(); }
			handleImageChangeFunctions(image.name);
			break;
		}
		
		if (image.style.display != 'none') {
			image.style.display = 'none';
			//image.fade({ duration: 0.5 });
			foundCurrent = true;
		}
	}	
	
	//the loop is over and foundCurrent is still true - the first image was the visible one and we should show the last one again
	if (foundCurrent == true) {
		mainImages[mainImages.length-1].style.display = 'inline';
		foundCurrent = false;
	}
}

function gotoImage(eventId) {
	var mainImages = $$('#mediaHolder img');
	var image;
	for (var index=0; index<mainImages.length; ++index) {
		image = mainImages[index];
		if (image.name == eventId) {
			image.style.display = 'inline';
			image.onclick = function() { gotoNextImage(); }
			handleImageChangeFunctions(image.name);
			//break;
		} else {
			image.style.display = 'none';
		}
	}	
}

function handleImageChangeFunctions(eventId) {
	//comments
	$('commentsHolder').update('<div class=\"commentsHolderInner\"><img src=\"/images2/freya/general/loader_ontransparent.gif\" /></div>');
	getComments(eventId, 0);
	$('postButton').onclick = function() { postComment(eventId) }
	
	//report & delete
	revertReportReason();
	if ($('reportImageButton') != null) {
		$('reportImageButton').onclick = function() { reportImage(eventId) }
	} else {
		$('removeImageButton').onclick = function() { removeImage(eventId) }
	}
}

function showAllPicturesInGrid() {
	var allGridImages = $$('#allImagesGridHolder img');
	var gridImage;
	for (var index=0; index<allGridImages.length; ++index) {
		allGridImages[index].style.display = 'inline';
	}
}

function setNextPreviousVisible(isVisible) {
	if (isVisible) {
		$('loadingMoreImagesHolder').style.display = 'none';
		$('previousAndNextLinksHolder').style.display = 'inline';
	} else {
		$('loadingMoreImagesHolder').style.display = 'none';
		$('previousAndNextLinksHolder').style.display = 'none';
		var s = "<div class=\"allImagesPaddingDiv\">";
		s +=    "There are no more pictures to display :(";
		s +=    "</div>";
		$('allImagesGridHolder').update(s);
	}
}

function reportComment(commentId, eventId, reasonId) {
	if (confirm('Are you sure you want to report this comment?')) {
		var sid = $("__sid").value;
		var server = $("__server").value + "GCReportPictureComment";
		if(!server) { alert("no session id and/or server found"); return; }
		var divId = commentId+'_actionDiv';
		$(divId+'').update('Sending report...');
		
		new Ajax.Request(server,
		  {
		    method:'post',
		    parameters: {apiKey: "d46dbe487d5baaa0b176cb55d3bc452c", applicationCode: "d46dbe487d5baaa0b176cb55d3bc452c", sessionId: sid, eventId: eventId, commentId: commentId, reasonId: reasonId},
			onSuccess: function(transport){ onReportCommentSuccess(divId); },
			onFailure: function(transport){ onReportCommentFail(transport.responseText); }
		  });
	}
}

function onReportCommentSuccess(divId) {
	$(divId+'').update('Reported. Thanks!');
}

function onReportCommentFail(transport) {
	alert('Something went wrong and the comment was not reported. Please try again later or contact support@skout.com.');
}

function reportUserNote(userId, noteId, reasonId) {
	if (confirm('Are you sure you want to report this message?')) {
		var sid = $("__sid").value;
		var server = $("__server").value + "GCReportUserNote";
		if(!server) { alert("no session id and/or server found"); return; }
		
		$(noteId+'_actionDiv').update('Sending report...');
		
		new Ajax.Request(server,
		  {
		    method:'post',
		    parameters: {apiKey: "d46dbe487d5baaa0b176cb55d3bc452c", applicationCode: "d46dbe487d5baaa0b176cb55d3bc452c", sessionId: sid, userId: userId, noteId: noteId, reasonId: reasonId},
			onSuccess: function(transport){ onReportUserNoteSuccess(noteId); },
			onFailure: function(transport){ onReportUserNoteFail(transport.responseText); }
		  });	
	}
}

function onReportUserNoteSuccess(noteId) {
	$(noteId+'_actionDiv').update('Report sent successfully. Thanks!');
}

function onReportUserNoteFail(transport) {
	alert('Something went wrong and the text was not reported. Please try again later or contact support@skout.com.');
}