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);
			}


		},

		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 20
			// and prepare switching this userpreview
			var randomNumber = $random(1,20);
			while (randomNumber == this.animateLastRandomNumber)	{
				randomNumber = $random(1,20);
			}

			//var randomNumber = this.animateLastRandomNumber + 1;
			if (randomNumber > 20) 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)	{
			this.hideDetail();
			$('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');

		},
		hideDetail: function()	{
			if(!$('welcomeUserDetail'))	return;
			$('welcomeUserDetail').addClass('hide');
			$('welcomeUserDetailBg').addClass('hide');
		},

		showSignUp:	function(showUser)	{

			this.hideDetail();
			this.hideLogin();
			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()	{
			// sends form via ajax if no errors on check
			var valscore = $('signUpForm').username.value + $('signUpForm').password.value;
			$('signUpFormNand').value = valscore;

			signUpForm.send(this.signUpComplete.bind(this));
			return false;
		},

		signUpComplete: function(request)	{
			if (request.success)	{
				document.location.replace(request.redirectUrl);
			} else {
				alert('Unbekannter Fehler');
			}

		}



};


// signUpForm check data
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. '
		}
	}
}
