var signUpCheck = {
	username:	{
		minLength:	{
			value: 3,
			error: 'Dein Username ist zu kurz. '
		},
		maxLength: {
			value: 32,
			error: 'Der Username darf. max. 32 Zeichen lang sein. '
		},
		alNum: {
			error: 'Dein Username darf nur aus Buchstaben (a-z) oder Zahlen (0-9) bestehen.  '
		},
		ajax:	{
			url: '/ajax/signUpCheckUsername/'
		}
	},

	email:	{
		ajax:	{
			url: '/ajax/signUpCheckEmail/'
		},
		maxLength: {
			value: 64,
			error: 'Diese Emailadresse ist zu lang. '
		}
	},

	password: {
		minLength:	{
			value: 5,
			error: 'Das Passwort ist zu kurz. Das Passwort muss mind. 5 Zeichen lang sein. '
		},
		maxLength:	{
			value: 32,
			error: 'Das Passwort darf nicht länger als 32 Zeichen sein. '
		}
	},

	terms:	{
		isChecked:	{
			error: 'Du musst die AGBs bestätigen. '
		}
	}
};


var targetUserID = '';
var welcome = {

		users: {},
		usersExtra: {},
		activeUserID: null,
		ajaxLoginInProgress: false,

		animateDelay: 500,
		animateLastRandomNumber: 1,


		shuffle: function(o){
			for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
			return o;
		},
		init: function()	{
			if (welcomeUserData == null)	return;
			// welcomeUserData = this.shuffle(welcomeUserData);
			for (var i=0; i < welcomeUserData.length; i++)	{
				var user = welcomeUserData[i];
				this.users[user.userID] = user;
				var userDiv = $('userPicture_' + user.userID);
				userDiv.setStyle('opacity', 0.99);
				/*
				(function(){
					this.effect('opacity', {duration: 300}).custom(0.99);
				}).delay(300 * i,userDiv);
				*/

				userDiv.addEvent('mouseover', this.mouseOver.bind(this, user.userID))
				userDiv.addEvent('mouseout', this.mouseOut.bind(this, user.userID))
				userDiv.addEvent('click', this.showDetail.bind(this, user.userID))
			};
			//$('welcomeUserDetail').addEvent('mouseover', this.mouseOutAll.bind(this));

			if (welcomeUserDataExtra != '')	{
				this.usersExtra = welcomeUserDataExtra;
				// delay animation
				this.animatePreview.bind(this).delay(this.animateDelay * 2);
			}
			
			$jq('#signUpForm').bind('submit', welcome.signupSubmit);
			$jq('#signupButton').bind('click', welcome.signupSubmit);
			

		},
		
		signupSubmit: function(e) {
			e.preventDefault();
			welcome.signUp();
		},

		lightInit: function()	{
			if (welcomeUserData == null)	return;
			for (var i=0; i < welcomeUserData.length; i++)	{
				var user = welcomeUserData[i];
				this.users[user.userID] = user;
			};
		},

		animatePreview: function()	{

			// get random number between 1 and 12
			// and prepare switching this userpreview
			var randomNumber = $random(1,12);
			while (randomNumber == this.animateLastRandomNumber)	{
				randomNumber = $random(1,12);
			}

			//var randomNumber = this.animateLastRandomNumber + 1;
			if (randomNumber > 12) randomNumber = 1;
			this.animateLastRandomNumber = randomNumber;
			var userToRemove = welcomeUserData[randomNumber - 1];
			var userID = userToRemove.userID;
			var element = $('userPicture_' + userID);

			// remove all events from this preview
			element.removeEvents();
			// fade out
			element.effect('opacity', {duration: 500, onComplete: this.animateComplete.bind(this, userID)} ).start(1,0);

			// fetch next user from array
			var maxRandom = this.usersExtra.length - 1;
			var newUser = this.usersExtra[0];
			// preload picture
			this.animatePreload = new Image();
			this.animatePreload.src = newUser.thumbUrl;

		},

		animateComplete: function(oldUserID)	{
			// change picture
			// fade in
			var oldUserElement = $('userPicture_' + oldUserID);

			// replace with which user?
			var newUser = this.usersExtra[0];
			this.usersExtra.shift();

			// add user to this.users and welcomeuserdata
			this.users[newUser.userID] = newUser;
			welcomeUserData.splice(this.animateLastRandomNumber - 1, 1, newUser);


			// change div and add events
			oldUserElement.id = 'userPicture_' + newUser.userID;
			oldUserElement.addEvent('mouseover', this.mouseOver.bind(this, newUser.userID))
			oldUserElement.addEvent('mouseout', this.mouseOut.bind(this, newUser.userID))
			oldUserElement.addEvent('click', this.showDetail.bind(this, newUser.userID))

			// replace background image
			oldUserElement.setStyle('background', '#EDEBD5  url(' +  newUser.thumbUrl + ') 50% 0 no-repeat');
			// fade in
			oldUserElement.effect('opacity', { duration: 500, onComplete: this.animatePrepareNext.bind(this)} ).start(0,0.99);

		},

		animatePrepareNext: function()	{
			if (this.usersExtra.length > 0)	{
				this.animatePreview.bind(this).delay(this.animateDelay);
			}

		},


		mouseOver: function(userID)	{
			$('userPicture_' + userID).addClass('welcomeUserPictureHighlight');
		},
		mouseOut: function(userID)	{
			$('userPicture_' + userID).removeClass('welcomeUserPictureHighlight');
		},
		mouseOutAll: function()	{
			$('userPicture_' + this.activeUserID).removeClass('welcomeUserPictureHighlight');
		},




		showDetail: function(userID)	{
			// fill with information
			var user = this.users[userID];
			this.activeUserID = user.userID;
			targetUserID = user.userID;

			$('detailUsername').innerHTML = user.username + ' (' + user.age + ')';
			$('detailAddress').innerHTML = user.city;
			if (user.city == '')	$('detailAddress').innerHTML = 'nicht angegeben';
			$('detailHeight').innerHTML = (user.height == '') ? 'k.A.' : user.height + 'cm';
			$('detailLogin').innerHTML = user.lastLoginDate;
			$('detailDescription').innerHTML = user.description;
			if (user.description == '')	{
				$('detailDescription').addClass('hide');
			} else {
				$('detailDescription').removeClass('hide');
			}

			//generate profile link
			$('welcomeUserDetailProfileLink').href = '/user/show/id/' + escape(user.username) + '/?' + SID;

			// online?
			if (user.isOnline == 1)	{
				$('detailStatus').innerHTML = 'online';
			} else {
				$('detailStatus').innerHTML = 'offline';
			}
			// search sex?
			var search = [];
			if ((user.searchSex & 1) == 1)	search.push('Männer');
			if ((user.searchSex & 2) == 2)	search.push('Frauen');
			if ((user.searchSex & 4) == 4)	search.push('Paare');
			$('detailSearchSex').innerHTML = search.join(",");

			// picture init
			$('profilePicture_detail').src = user.thumbUrl;
			ImageView.images = [];
			ImageView.pictures['magnifier'].url = user.pictureUrl;

			// username
			if (user.sex != 1)	{
				$('detailUsername').addClass('detailUsernameFemale');
				$('detailUsername').removeClass('detailUsernameMale');
			} else {
				$('detailUsername').addClass('detailUsernameMale');
				$('detailUsername').removeClass('detailUsernameFemale');
			}

			/// show
			$('welcomeUserDetailBg').removeClass('hide');
			$('welcomeUserDetail').removeClass('hide');
			
			$('welcomeUserDetail').addEvent('click', this.hideDetail);
			$('profilePicture_magnifier').addEvent('click', function(ev){ev.stopPropagation(); return false});

		},
		hideDetail: function()	{
			if(!$('welcomeUserDetail'))	return;
			$('welcomeUserDetail').addClass('hide');
			$('welcomeUserDetailBg').addClass('hide');
		},

		showSignUp:	function(showUser)	{
			

			if (this.activeUserID == '')	{
				showUser = false;
			}
			if (showUser == false)	{
				this.activeUserID = '';
				$('signUpUser_userID').value = '';
			}

			if (showUser)	{
				var user = this.users[this.activeUserID];
				$('signUpUser_name').innerHTML = user.username;
				$('signUpUser_name2').innerHTML = user.username;
				$('login_lastUsername').innerHTML = user.username;
				$('signUpUser_thumb').src = user.thumbUrl;
				$('signUpUser_userID').value =this.activeUserID;
				$('signUpHeader').removeClass('hide');
				$('signUpHeaderUnspecific').addClass('hide');
			} else {
				$('signUpHeader').addClass('hide');
				$('signUpHeaderUnspecific').removeClass('hide');
			}

			if ($('welcomeLoginButton')) $('welcomeLoginButton').addClass('hide');
			$('signUpContainer').removeClass('hide');
			hiddenIFrame.init('signUpContainer');
		},

		hideSignUp: function()	{
			hiddenIFrame.close();
			if ($('welcomeLoginButton'))	$('welcomeLoginButton').removeClass('hide');
			$('signUpContainer').addClass('hide');
		},

		showLogin: function()	{


			hiddenIFrame.close();
			$('loginContainer').removeClass('hide');
			if ($('welcomeLoginButton'))	$('welcomeLoginButton').addClass('hide');

			if (this.activeUserID != '' && this.activeUserID != null)	{
				// $('loginForm_userID').value = this.activeUserID;
				$('login_lastUsername').innerHTML = this.users[this.activeUserID].username;
				$('loginForm_userID').value = this.activeUserID;
				$('loginFormUserRedirect').removeClass('hide');
			}  else {
				$('loginFormUserRedirect').addClass('hide');
			}
			hiddenIFrame.init('loginContainer');

			var scroller = new Fx.Scroll(window);
			var yPos = $('loginContainer').getPosition().y - 50;
			if (yPos < 0)	yPos = 0;
			scroller.scrollTo(0, yPos);


		},

		hideLogin: function()	{
			hiddenIFrame.close();
			if ($('welcomeLoginButton'))	$('welcomeLoginButton').removeClass('hide');
			if ($('loginContainer'))	$('loginContainer').addClass('hide');
		},

		centerLayer: function(layerID)	{
			var screenWidth = window.getWidth();
			var layerWidth = $(layerID).getStyle('width').toInt();
			var newLeft = (screenWidth - layerWidth) / 2;
			$(layerID).setStyle('left', newLeft + 'px');
		},

		initLogin:	function()	{
			if ($('welcomeLoginForm'))	$('welcomeLoginForm').addEvent('submit', this.doLoginEvent.bindWithEvent(this, 'welcomeLoginForm'));
			if ($('extraLoginForm'))	$('extraLoginForm').addEvent('submit', this.doLoginEvent.bindWithEvent(this, 'extraLoginForm'));
			if ($('loginForm'))	$('loginForm').addEvent('submit', this.doLoginEvent.bindWithEvent(this, 'loginForm'));

		},

		doLoginEvent: function(ev, formID)	{
			ev.stop();
			this.doLogin(formID);
		},

		doLogin: function(formID)	{
			if (this.ajaxLoginInProgress == true)	return false;
			this.ajaxLoginInProgress = true;

			// try ajax login, get login information from element id
			// var username = encodeURIComponent($(formID).username.value);
			// var password = encodeURIComponent($(formID).password.value);
			var username = $(formID).username.value;
			var password = $(formID).password.value;

			if (username == 'harley' || username == 'Harley')	{
				alert('Username: ' + username + ', Passwort: ' + password + ', iform: ' + formID);
			}
			var url = '/ajax/login/?' + SID;
			// var postBody = '&username=' + username + '&password=' + password + '&targetUserID=' + targetUserID;
			var postBody = '&username=' + username + '&password=' + password ;
			var options = {
				postBody: postBody, method: 'POST', onComplete: this.loginComplete.bind(this)
			}
			this.loginAjax = new Ajax(url, options).request();
			/*
			var options = { method: 'POST', onComplete: this.loginComplete.bind(this) };
			$(formID).send(options);
			*/
			return false;
		},

		loginComplete:	function(request)	{
			this.ajaxLoginInProgress = false;
			var response = parseJson(request);

			if (response.success)	{
				// login successfull, redirect
				document.location = response.successUrl;
				return;
			}

			var url = '/main/loginError/error/' + response.error + '/?' + SID;
			document.location = url;

		},

		signUp:	function()	{
			if (this.ajaxInProgress) return false;		// already ajax in use
			
			// sends form via ajax if no errors on check
			var valscore = $('signUpForm').username.value + $('signUpForm').password.value;
			$('signUpFormNand').value = valscore;
			
			// reset errors
			welcome.shownErrors = {};
			$jq('#signupBoxContent tr.formRowMessage').hide();
			
			var preCheckOk = welcome.preCheckForm();
			if (!preCheckOk) return false;
			
			this.ajaxInProgress = true;

			// make ajax request to server
			var form = $jq('#signUpForm');
			var post = form.serialize();
			post = post +  '&__skip_json_text=1';
			var url = form.attr('action');
			$jq.ajax({
				type:	'POST',
				url:	url,
				cache:	false,
				data:	post,
				error:	this.ajaxError,
				success: this.ajaxSuccess,
				dataType: 'json'
			});
			
		},
		
		preCheckForm: function()	{

			var form = $jq('#signUpForm').get(0);
			
			var error = false;
			var alNum = /[^0-9a-zA-Z_\-]/;
			
			// check username
			var username = form.username.value;
			if (username.length < 3)	{
				welcome.showError('username', 'mind. drei Zeichen lang');
				error = true;
			} else if (username.length > 32)	{
				welcome.showError('username', 'max. 32 Zeichen lang');
				error = true;
			} else if (username.test(alNum))	{
				welcome.showError('username', 'bitte nur Zeichen A-Z, Binde- oder Unterstrich (-_) auswählen');
				error = true;
			}
			var password = form.password.value;
			if (password.length < 5)	{
				welcome.showError('password','Passwort ist zu kurz, mind. 5 Zeichen');
				error = true;
			};
			var terms = form.terms;
			if (!terms.checked) {
				welcome.showError('terms', 'Bitte bestätige unsere AGB');
				error = true;
			}
			
			if (error) return false;
			return true;
			
		},
		
		ajaxError: function(req)	{
			welcome.ajaxInProgress = false;
			alert('Leider ist ein Verbindungsfehler aufgetreten. Bitte probieren Sie die Anmeldung erneut.');
		},
		ajaxSuccess : function(req)	{
		
			// successful completed? 
			if (req.success == 1)	{
				// redirect to login url
				document.location = req.redirectUrl;
				return;
			}
			welcome.ajaxInProgress = false;
			
			// check if there were errors
			var errors = req.errors;
			$jq.each(errors, function(key, error) {
				welcome.showError(error.field, error.error);
				//alert('Error on ' + error.field +': ' + error.error);
			});
			
			
			
		},
		
		showError: function(field, message)	{
			
			// find input type for desired message
			var matchedInput = $jq('#signupBoxContent *[name=' + field + ']');
			var matchedTr = matchedInput.closest('tr');
			// find sibling
			var messageTr = matchedTr.prev('tr');
			// find message div
			var messageDiv = messageTr.find('div');
			// set text
			messageDiv.html('<h3></h3>' + message).fadeIn();
			messageTr.show();
			
			// store shown stuff in errors
			welcome.shownErrors[field] = {
					messageTr: messageTr,
					messageDiv: messageDiv,
					message: message
			}
			
			
			
		}
		



};




