/**
 * Finya.de JS Library
 * Author: GWI Media Technologies GmbH (GW interactive), http://www.gw-interactive.com
 * Copyright: Finya GmbH & Co. KG
 */

var Finya = new Object({Settings:{}});
var ssEngaged = false;
var isOldIE = ($.browser.msie) && ($.browser.version <= '6.0')
var tnav, tnav2;

function init() {

	// Always do:
	_implementNav();
	_implementStickySky();
	_implementOptionSwitches();
	_initSidebar();
	setInterval('updateMsgCenter()',  20000);
	setInterval('updateListVisits()', 180000);
	setInterval('updateListOnline()', 170000);

	$('#fq')
		.focus(function() {
			if ($(this).hasClass('void'))
				$(this).val('').removeClass('void');
		})
		.blur(function() {
		if ($(this).val() == '')
			$(this).addClass('void').val($(this).attr('title'));
		});

	// Implement page-specific functions:
	pageId = document.body.id;

	switch (pageId)
	{
		case 'pg-1-1':

			setTimeout("self.location.href = '/'", 900000);
			_implementFormLogic(pageId);
			break;

		case 'pg-0-3':
		case 'pg-0-10':
			_implementCaptcha();
			break;

		case 'pg-0-5':
			setTimeout("self.location.reload()", 900000);
			_implementFormLogic(pageId);
			break;

		case 'pg-1-3':
		case 'pg-1-3-1-1':
			_implementFormLogic(pageId);
			_implementCaptcha();
			break;

		case 'pg-1-13':
			setTimeout("self.location.reload()", 900000);
			_implementFormLogic(pageId);
			break;

		case 'pg-1-14':
			$('#em1').html('\x3C\x61\x20\x68\x72\x65\x66\x3D\x22\x6D\x61\x69\x6C\x74\x6F\x3A\x62\x6C\x6F\x67\x40\x66\x69\x6E\x79\x61\x2E\x64\x65\x22\x3E\x62\x6C\x6F\x67\x40\x66\x69\x6E\x79\x61\x2E\x64\x65\x3C\x2F\x61\x3E');
			break;

		case 'pg-1-2':
		/* Registration init */

			checkNickname = function() {
				$('#nnavail').attr('class', 'avail-check');
				self.tnn1 = setTimeout("$.post('/Registration/checkNickname',{n:$('#username').val()},handleAjaxRsp)", 700);
			}

			// Prevent some browsers (FF) from keeping the form values after a soft page reload (Ctrl-R, F5)
			$('#frmRegistration').get(0).reset();

			$('#gender-opt1,#gender-opt2').click(function(){
				if (! $('#seeking-opt1').attr('checked') && ! $('#seeking-opt2').attr('checked')) {
					opt = $(this).attr('id') == 'gender-opt1' ? $('#seeking-opt2') : $('#seeking-opt1');
					opt.attr('checked', true);
				}
			});

			$('#ssel-country').bind('__ssel_onchange', function() {
				self.cityMode = (c_req_zip.indexOf($('#ssel-country-value').val()) > -1) ? 'id' : 'txt';
				$('#location-inputmode').removeClass().addClass('mode-' + self.cityMode);
			});

			$('#data-zip').change(function() {
				reloadLocationList(2, $('#ssel-country-value').val(), this.value);
			})

			$('#email2,#captcha-reg').attr('autocomplete', 'off');

			$('#username').keyup(function(){

				if (self.tnn1) clearTimeout(tnn1);
				if (self.tnn2) clearTimeout(tnn2);

				if ($.trim($(this).val()).length < 4) {
					$('#nnavail').attr('class', 'avail-syntax');
					return;
				}

				self.tnn2 = setTimeout("checkNickname()", 1000);
			});

			_implementFX_SleekSelect($('#frmRegistration'));
			_implementFormLogic(pageId);
			_implementExpSwitches();
			_implementCaptcha();

			break;

		case 'pg-1-4-1':

			$('#btn-vote1,#btn-vote0').click(function(){
				v = this.id.match(/(\d+)$/)[1];
				$('#helpful').load('/Help/vote/', {i: $('#topicid').val(), v: v});
			});
			break;

		case 'pg-2-1':
			/* MyFinya Channel */

			_implementRefreshableSections();

			$('#h-journal a').data('callback', function(){
				$('#section-journal').load('/MyFinya/refreshJournal', function(){
					$('#h-journal').removeClass('loading');
				});
			});

			setInterval("$('#h-journal a').trigger('click')", 90000);

			$('a.showmore').live('click', function(){
				this.blur();
				t = this.id.match(/\-(.+)$/)[1];
				$('#' + t).removeClass('eventlist-short');
				$(this).hide();

				return false;
			});

			$('select.chmood').change(function(){
				m = this.id.match(/\-(.+)$/)[1];
				$('#mood').removeClass('updating-mood updating-feelslike').addClass('updating-' + m);
				$.post('/MyFinya/changeMoods', {f: $('#chmood-feelslike').val(), m: $('#chmood-mood').val()}, function(){
					setTimeout("$('#mood').removeClass('updating-mood updating-feelslike')", 150);

					if ($('#chmood-feelslike').val() > 0) {
						$('#options-feelslike').css('visibility', 'visible')
						$('#lnk-match-feelslike').attr('href', $('#lnk-match-feelslike').attr('href').replace(/&fl=\d+/, '&fl=' + $('#chmood-feelslike').val()));
					} else {
						$('#options-feelslike').css('visibility', 'hidden')
					}
				});
			});
			$('#msg-success-close').click(function() { $('#msg-success').fadeOut() });
			$('#sysmessages-close a').click(function() {
				if (lastSysmsgId > 0) {
					$.post('/MyFinya/setlastSysMsg/', {id: lastSysmsgId});
				}
				$('#sysmessages').fadeOut()
			});
			$('#lnk-sysmsg-next').click(function() {
				if ((msgTransProcess) || (curSysMsg + 1 > maxSysMsg))
					return;

				msgTransProcess = true;

				$('#sysmsg' + curSysMsg).fadeOut('fast', function(){
					curSysMsg++;
					$('#sysmsg-pos').text(curSysMsg);
					$('#sysmsg' + curSysMsg).fadeIn();
					msgTransProcess = false;
				});
			});
			$('#lnk-sysmsg-prev').click(function() {
				if ((msgTransProcess) || (curSysMsg - 1 < 1))
					return;

				msgTransProcess = true;

				if (curSysMsg-1 > 0) {
					$('#sysmsg' + curSysMsg).fadeOut('fast', function(){
						curSysMsg--;
						$('#sysmsg-pos').text(curSysMsg);
						$('#sysmsg' + curSysMsg).fadeIn();
						msgTransProcess = false;
					});
				}
			});

			break;

		case 'pg-2-2-1':
		/* MyProfile: data */

			_implementSliderLists();

			handleSaveResponse = function(response) {
				if (response.success) {
					section = response.context;
					$('#' + section + '_response').show();
					f = function() {
						$('#' + section + '_response').fadeOut('slow', function(){
							$('#' + section + '_btnSave').get(0).disabled = false;
						});
					}
					setTimeout("f()", 800);
				}
			}

			$('#frmData ul.list-slide>li').each(function(){
				// Apply callback function to list-item (will be executed by _implementSliderLists())
				$(this).data('callback', function() {
					$('#' + this.attr('id') + ' div.li-content').load('/MyProfile/populate/' + this.attr('id'));
				});
			});
			break;

		case 'pg-2-2-2':
		/* MyProfile: photos */

			reloadPg = function() {
				parent.location.href = '/MyProfile/photos/?' + Math.round(Math.random() * 100000000) + '#pics';
			}

			if ($('#frmUpload').length) {
				$('#frmUpload').get(0).reset();

				_implementExpSwitches();

				initZoomBox('#uploadInterface', '#pgcontent .imgwrapper a.lnk-upload', '#uploadInterface #closeUIF');

				$('#state1-content input[type=file]').change( function() {
					$('#btnUploadSubmit').get(0).disabled = (! (this.value.length > 0));
				});

				$('#state1-content input[type=file]').click( function() {
					$(this).trigger('change');
				});

				$('#uploadInterface #closeUIF').click( function() {
					$('#uploadInterface').removeClass('uif-state3').removeClass('uif-state4').addClass('uif-state1');
					return false;
				});

				$('#uploadHandler').html('<iframe src="" name="uploadHandler" id="uploadHandler" frameborder="0"></iframe>');
				$('#pgcontent .imgwrapper a.lnk-upload').click( function() {
					$('#frmUpload').attr('action', this.href);
					$('#frmUpload').attr('target', 'uploadHandler');
					return false;
				});

				$('#btnUploadSubmit').click( function() {
					$('#uploadInterface').css('cursor', 'wait');
					$('#uploadInterface').removeClass('uif-state1').addClass('uif-state2');
				});

				$('#btnActivateVoting').click( function() {
					$.post('/Voting/enable', null, function(){
						self.location.reload();
					});
				});

				startOver = function() {
					$('#frmUpload').get(0).reset();
					$('#uploadInterface').attr('class', 'uif-state1');
					$('errlist').attr('class', 'errlist');
					$('sollist').attr('class', 'sollist');
					return false;
				}

				dropPic = function(s,i) {
					if (confirm('BITTE BEST\u00c4TIGEN\n\nKlicken Sie auf \'OK\', um dieses Foto (und ggf. dessen Voting-Punkte) zu l\u00f6schen.')) {
						$.getScript('/MyProfile/photos/' + s + '/drop/' + i, function(){
							reloadPg();
						});
					}
				}
				movePic = function(s1,dir) {
					s2 = s1 + dir;
					if ((s2 >= 2) && (s2 <= 5) && (s2 != s1)) {
						$.getScript('/MyProfile/photos/' + s1 + '/swap/' + s2, function(){
							reloadPg();
						});
					}
				}
				makeMain = function(s,has1) {

					if (confirm('BITTE BEST\u00c4TIGEN\n\nKlicken Sie auf \'OK\', um dieses Foto zu Ihrem Hauptfoto zu machen.'
						+ (has1 ? '\nIhr bestehendes Profil-Hauptfoto r\u00fcckt dann an diese Stelle.' : '')
						+ '\n\n(Alle jeweiligen Voting-Punkte bleiben erhalten.)'))	{
							$.getScript('/MyProfile/photos/' + s + '/makemain', function(){
							reloadPg();
						});
					}
				}
			}

			break;


		case 'pg-2-2-3':
		/* MyProfile: tags */

			_implementFormLogic(pageId);

			break;

		case 'pg-2-2-4':
			/* My QnA */
			_implementSleekTextarea($('.qna-entry textarea'), 500);
			_implementSliderLists();

			save = function(id, gid) {
				$.post('/MyProfile/update/qna/' + id + '/' + gid, {c: $('#entry' + id + '-textarea').val()}, handleAjaxRsp);
			}

			break;

		case 'pg-2-2-5':
			/* My Brands */
			_implementSliderLists();

			handleSaveResponse = function(response) {
				if (response.success) {
					section = response.context;
					$('#' + section + '_response').show();
					f = function() {
						$('#' + section + '_response').fadeOut('slow', function(){
							$('#' + section + '_btnSave').get(0).disabled = false;
							$('#' + section + '-content').parents('li:first').removeClass('dirty');

						});
					}
					setTimeout("f()", 800);
				}
			}

			$('ul#brandslist>li').each(function(){
				// Apply callback function to list-item (will be executed by _implementSliderLists())
				$(this).data('callback', function() {
					grp = this.attr('id').match(/(\d+)$/)[1];
					$('#brands' + grp + '-content').load('/MyProfile/populate/brands/' + this.attr('id').match(/(\d+)$/)[1]);
				});
			});

			$('ul#brandslist>li input:checkbox').live('click', function() {
				$(this).parents('li:first').addClass('dirty');
				$(this).parent().toggleClass('brand-selected');
			});

			break;

		case 'pg-2-2-6':
			_implementFormLogic(pageId);

			break;

		case 'pg-2-2-7':
			_implementFormLogic(pageId);
			_implementExpSwitches();
			break;

		case 'pg-2-2-8':
		/* My Account */

			_implementFormLogic(pageId);
			_implementExpSwitches();

			$('#resendConfirmation').click(function(){
				this.value = 'Bitte warten...';
				this.disabled = true;
				$.post('/MyProfile/resendConfirmation', {}, handleAjaxRsp);
			});
			break;

		case 'pg-2-2-9':
		/* Requalify data */

			_implementFX_SleekSelect($('#frmRequalify'));

			$('#btnSubmit').click(function(){
				self.cityMode = (c_req_zip.indexOf($('#ssel-country-value').val()) > -1) ? 'id' : 'txt';

				$('#frmRequalify').submit();
			});

			$('#ssel-country').bind('__ssel_onchange', function() {
				self.cityMode = (c_req_zip.indexOf($('#ssel-country-value').val()) > -1) ? 'id' : 'txt';
				$('#location-inputmode').removeClass().addClass('mode-' + self.cityMode);
			});

			$('#data-zip').keyup(function() {
				if (this.value.length >= 5)
					reloadLocationList(2, $('#ssel-country-value').val(), this.value, null, function() {
						$('#btnSubmit')[0].disabled = false;
					});
			});

			$('#location').keyup(function() {
				$('#btnSubmit')[0].disabled = (!(this.value.length >= 1));
			});
			$('#location').change(function() {
				$(this).trigger('keyup');
			});

			break;


		case 'pg-2-3-1-1':
		/* Message */

			setTimeout('updateMsgCenter()', 2000);

			_implementExpSwitches();
			_implementSleekTextarea($('#msg1-textarea'), 5000);

			var historyLoaded = false;

			$('#link-relatedmsgs span').click( function() {
				if (! historyLoaded) {
					try {
						pageTracker._trackPageview('/Profil/Verlauf');
						ivwTrack('Profil_Verla');
					} catch(e) {}
					setTimeout("$('#rmlist').load('/Mailbox/getExchange', {u: $('#ui').val(), c: $('#mid').val()})", 10);
				}

				historyLoaded = true;
			} );

			_implementFormLogic(pageId);
			break;

		case 'pg-2-4-1':
		/* My Guestbook */
			// updateMsgCenter();
			_implementExpSwitches();
			_implementFormLogic(pageId);
			_implementSleekTextarea($('.gbreply textarea:not(:disabled)'), 500);

			save = function(id) {
				$.post('/Guestbook/setComment/' + id, {c: $('#reply' + id + '-textarea').val()}, handleAjaxRsp);
			}
			break;

		case 'pg-2-5':
		/* My Favorites */
			_implementExpSwitches();
			_implementSleekTextarea($('.favcard textarea'));

			save = function(id) {
				$.post('/Favorites/setComment/' + id, {c: $('#fav' + id + '-textarea').val()}, handleAjaxRsp);
			}

			$('#btnRename').click(
				function() {
					$('#frmFavs').attr('action', '/Favorites/renameGroup').submit();
				} );

			$('#optonline').click(
				function() {
					self.location.href = this.value + (this.checked ? '1' : '0');
				} );

			break;

		case 'pg-2-6':
		/* Blacklist */

			_implementFormLogic(pageId);
			break;

		case 'pg-2-3-1':
		case 'pg-2-3-2':
		case 'pg-2-3-3':
		/* Mailboxes */
			_implementFormLogic(pageId);

			/* Implement delete msg */
			$('#tbl-mailbox .c6 a[class*=icon-s-delxs]').click(function(){
				if (confirm('Diese Nachricht wirklich l\u00f6schen?')) {
					$(this).parents('tr:first').find('.c2 input:checkbox').each(function(){
						this.checked = true; sel(this);
						$('#frmMails').get(0).submit();
					})
				}
				return false;
			});

			/* Routines for multiple mails selections */
			sel = function(chk) {
				if (chk.checked)
					$(chk).parents('tr:first').addClass('sel');
				else
					$(chk).parents('tr:first').removeClass('sel');
			}
			$('#tbl-mailbox .c2 input:checkbox').click(function(){
				sel(this);
			});
			$('#mailbox-sel select').change(function(){
				switch (this.value) {
					case 'all':
						$('#tbl-mailbox .c2 input:checkbox').each(function(){ this.checked = true; sel(this); });
						break;
					case 'none':
						$('#tbl-mailbox .c2 input:checkbox').each(function(){ this.checked = false; sel(this); });
						break;
					case 'inv':
						$('#tbl-mailbox .c2 input:checkbox').each(function(){ this.checked = !this.checked; sel(this); });
						break;
					case 'obs':
						$('#tbl-mailbox .c2 input:checkbox').each(function(){ this.checked = false; sel(this); });
						$('#tbl-mailbox .c4 span[class*=ml-s0]').each(function(){
							$(this).parents('tr:first').find('td.c2 input:checkbox').each(function(){
								this.checked=true; sel(this); })
						});
						break;
				}
			});
			break;

		case 'pg-3-1':
		/* Search'n'Browse Channel */

			_implementRefreshableSections();

			$('#btn-suggst').click(function() {
				this.disabled = true;
				try {
					pageTracker._trackPageview('/SearchAndBrowse/refreshSuggestions');
					ivwTrack('SearchAndBro');
				} catch(e) {}
				$('#suggestions').load('/SearchAndBrowse/getSuggestions', {'new': 1});
			})

			_implementFX_SleekSelect($('#frmSearch'));
			_implementFormLogic(pageId);

			$('#h-newbies a').data('callback', function(){
				$('#newbies').load('/SearchAndBrowse/refreshNewbies', function(){
					$('#h-newbies').removeClass('loading');
				});
			});

			var ibClickable = $('#pgcontent div[class*=ib-][class*=-clickable]');

			if (isOldIE) {
				ibClickable.hover(function(){
					$(this).addClass('ib-hover');
				}, function(){
					$(this).removeClass('ib-hover');
				})
			}

			ibClickable.click(
				function() { self.location = $(this).find('a[id]').get(0).href; }
			);

			break;

		case 'pg-3-2':
		/* Gallery */
			hideBubble = false;
			_implementFX_SleekSelect($('.displayoptions'));

			$('#gallery-result').load('/Gallery/fetch');

			$('#btn-nexthit').click(function() {
				try {
					pageTracker._trackPageview('/Fotogalerie');
					ivwTrack('Fotogalerie');
				} catch(e) {}
				$('#gallery-result').load('/Gallery/next');

				// If a bubble is shown, hide it on click
				$('#dyk-profileinnewwindow').hide();
				hideBubble = true;
			});

			$('#ssel-region').bind('__ssel_onchange', function() { rv(); });
			$('#ssel-gender').bind('__ssel_onchange', function() { rv(); });
			$('#ssel-agerange').bind('__ssel_onchange', function() { rv(); });
			$('#ssel-voting').bind('__ssel_onchange', function() { rv(); });
			$('#lbl-online input').click(function() { rv(); });
			$('#lbl-single input').click(function() { rv(); });

			showSmallPoolBubble = function() {
				$('#ib1').hide(function() { $('#ib-smallpool').show(); });
			}
			reloadSmallPool = function() {
				self.location.href = '/Gallery/?v1=&si=&o=&r=';
			}

			rv = function() {
				// build new query string:
				params = [];
				params.push("g=" + $('#ssel-gender-value').val().substring(0, 1));
				params.push("se=" + $('#ssel-gender-value').val().substring(1, 2));
				params.push("ar=" + $('#ssel-agerange-value').val());
				params.push("v1=" + $('#ssel-voting-value').val());
				params.push("si=" + ($('#lbl-single input')[0].checked ? 1 : ''));
				params.push("o=" + ($('#lbl-online input')[0].checked ? 1 : ''));
				params.push("r=" + $('#ssel-region-value').val());
				self.location.href = encodeURI('/Gallery/?' + params.join('&'));
			}

			break;

		case 'pg-3-3':
		/* Voting */
			$('#va').load('/Voting/fetch');

			$('#btnActivateVoting').click(function() {
				$.post('/Voting/enable', null, function(){
					self.location.reload();
				});
			});

			break;

		case 'pg-3-4':
		/* MatchClick */
			populateTagCloud = function(context, gender) {
				$('#tagcloud-' + context).addClass('loading');
				$('#tagcloud-' + context + ' .tagcloud-content').load('/MatchClick/refresh', {c: context, g: gender || 0}, function(){
					$('#tagcloud-' + context).removeClass('loading');
				});
			}
			populateTagCloud(1);
			populateTagCloud(2);
			populateTagCloud(3);

			$('.tagcloud .button').click(
				function() {
					context = (id = $(this).parent().attr('id')).substring(id.indexOf('-') + 1);
					populateTagCloud(context);
				}
			);
			break;

		case 'pg-3-5':
		/* Lists (Charts) */
			populateList = function(context, gender) {
				$('#list-' + context).addClass('loading');
				$('#list-' + context + ' .listcontent').load('/Lists/refresh', {c: context, g: gender || 0}, function() {
					$('#list-' + context).removeClass('loading');
					try {
						pageTracker._trackPageview('/Rankings/refresh');
						ivwTrack('Rankings');
					} catch(e) {}
				});
			}

			$('.chartslist .button').click(
				function() {
					context = (id = $(this).parent().attr('id')).substring(id.indexOf('-') + 1);
					populateList(context);
				}
			);

			break;

		case 'pg-3-6'
		/* Matching */ :
			$("#slider-agerange").slider({
				range: true,
				min: 18,
				max: 66,
				values: slider1_preset,
				slide: function(event, ui) {
					updateAgeRange(ui.values);
				}
			});

			$("#slider-shape").slider({
				range: false,
				min: 0,
				max: 5,
				value: slider2_preset,
				slide: function(event, ui) {
					updateShape(ui.value);
				}
			});

			$("#slider-height").slider({
				range: true,
				min: 150,
				max: 210,
				values: slider3_preset,
				slide: function(event, ui) {
					updateHeight(ui.values);
				}
			});

			$("#slider-voting").slider({
				range: false,
				min: 5,
				max: 90,
				value: slider4_preset,
				slide: function(event, ui) {
					updateVoting(ui.value);
				}
			});

			self.updateAgeRange = function(values) {
				$('#a1-cleartext').html(values[0]);
				$('#a2-cleartext').html(values[1] > 65 ? '66+' : values[1]);
				$('#opt-a1').val(values[0] > 18 ? values[0] : '');
				$('#opt-a2').val(values[1] > 65 ? '' : values[1]);
			}

			self.updateShape = function(value) {
    			$('#sh-cleartext span').hide();
    			$('#sh-cleartext-' + value).show();
    			$('input#opt-sh').val(value == 0 ? '' : value);
			}

			self.updateHeight = function(values) {
    			$('input#opt-h1').val( values[0] < 155 ? '' : values[0] );
    			$('input#opt-h2').val( values[1] > 205 ? '' : values[1] );

    			if ((values[0] == 150) && (values[1] == 210)) {
    				ct = '(beliebig)';
    			} else {
    				ct = (values[0] > 150 ? 'ab ' + values[0] : '') +
    					 (values[1] < 210 ? ' bis ' + values[1] : '') + ' cm';
    			}

    			$('#h-cleartext').html( ct );
			}

			self.updateVoting = function(value) {
    			$('input#opt-v1').val( value > 5 ? value : '' );
    			ct = value > 5 ?
    					('mind. ' + (value/10+'').replace(/\./, ',') + ' Punkt' + (value==10 ? '' : 'e')) :
    					'(beliebig)';

    			$('#v1-cleartext').html( ct );
			}

			$('#link-opensearches').click(function(){
				$('#link-opensearches-container').slideToggle('fast');
				return false;
			});
			$('#link-opensearches-container .edittag a.x').click(function(){
				return confirm('Diese Suche l\u00f6schen?');
			});

			// City autocomplete
			$("#opt-region-city").autocomplete('/Matching/getCity/de/', { autoFill: true, minChars: 2 });

			function setSaveSearchOptions() {
				$('#btnSave').attr('disabled', (! (($('#data-srchname').val().length > 0) && ($('#slotnr').val() > 0))));
 			}
 			$('#data-srchname').change(function(){
 				setSaveSearchOptions();
 			});
 			$('#slotnr').change(function(){
 				setSaveSearchOptions();
 				if (($('#data-srchname').val().length == 0) && ($(this).val() > 0))
 					$('#data-srchname').val('Unbenannt-' + $(this).val());
 			});
 			$('#btnSave').click(function(){
 				if ($('#slotnr option:selected').hasClass('option-occupied') && !confirm('Suche \u00fcberschreiben?'))
 					return false

 				$('#frmSearch').attr('action', '/Matching/');
 			});

			/*
			 * Setup color samples
			 */
			function setColorPicker(context) {
				selectedSample = $('#colorsamples-' + context + ' div[class*=colorsample-selected]:first');
				$('#' + context + '-cleartext').html(selectedSample.attr('title'));
				$('input#opt-' + context).val(selectedSample.find('input:first').val());
			}

			$('.colorsample').click(function() {
				context = $(this).parent('div').attr('id').match(/-([a-z]+)$/)[1];
				$(this).siblings('.colorsample').removeClass('colorsample-selected');
				$(this).addClass('colorsample-selected');

				setColorPicker(context);
			});

			var regionalSearch;

			function setRegionOptions() {
				curOptionName = 'opt-regionbase-' + $('#opt-regionbase').val();

				if ($('select#opt-rc').val() == 'de') {
					regionalSearch = $('#opt-regionbase').val();
					$('#region-options-unsupported').hide(function() {
					$('#region-options').show();
					});
				} else {
					regionalSearch = false;
					$('#region-options').hide('slow', function(){
					$('#region-options-unsupported').show();
					});
				}

				$('#region-options .region-options').each(function(){
					if ($(this).hasClass(curOptionName))
						$(this).show();
					else
						$(this).hide();
				});
			}

			function setGenderHighlight() {
				$('#search-what label').removeClass('checked');
				$('#search-what input:radio:checked').parent('label').addClass('checked');
			}

			$('#load-search').change(function(){
				searchId = $(this).val();
				if (searchId > 0)
					self.location.href = '/Matching/load/' + searchId;
			});

			// Define 'onchange' triggers for some form elements
			$('#search-what input:radio').click(function(){ setGenderHighlight(); });
			$('#opt-regionbase,select#opt-rc').change(function(){ setRegionOptions(); });


			// Trigger 'onchange' events on page load
			setGenderHighlight();
			setRegionOptions();
			setColorPicker('hc');
			setColorPicker('ec');
			setSaveSearchOptions();

			// Adjust options for regional search
			$('#frmSearch').submit(function(){

				region_str = $('#opt-rc').val();
				if (regionalSearch == false) { // country search
					region_str += ',,,';
				} else {
					switch (parseInt(regionalSearch)) {
						case 1:		// Distance search based on ZIP
							$('#opt-distance').attr('name', 'di');		// submit this field
							$('#opt-distance-zip').attr('name', 'db');	// submit this field
							region_str += ',,,';
							break;
						case 3:		// State search
							region_str += ',' + $('#opt-region-state').val() + ',,';
							break;
						case 2:		// City search
							region_str += ',,,' + $('#opt-region-city').val();
							break;
					}
				}
				$('#region').val(region_str);
			});

			break;

		case 'pg-3-8-1':
			_implementProfileSubnav();
			_implementExpSwitches();
			self.brandsLoaded = false;
			$('#x73x72x63').attr('\x73\x72\x63', u.x73x72x63);
			$('#userpics .thumbs img').click(
				function(ev, notrack) {
					$('#userpics .thumbs img').each(function(){$(this).removeClass('thumb-active');});
					$(this).addClass('thumb-active');
					newSrc = 'http://www.finya-images.com/img/u/' + this.id.substring(2,3) + '/' + this.id.substring(3,4) + '/' + this.id.substring(2) + '_4.jpg';
					$('#x73x72x63').attr('src', newSrc);
					if (!notrack)
						try {
							pageTracker._trackPageview('/Profil/Fotozoom');
							ivwTrack('Profil');
						} catch(e) {}
				}
			);

			anchor = document.location.hash;
			if (a = anchor.match(/^\#pic(\d)$/)) {
				// Trigger click on picture
				$('#userpics .thumbs img:nth-child(' + (parseInt(a[1])+1) + ')').trigger('click', true);
			}

			break;

		case 'pg-3-8-2':
		/* User: contact */
			_implementProfileSubnav();
			_implementExpSwitches();
			_implementSleekTextarea($('#msg1-textarea'), 5000);
			_implementFormLogic(pageId);
			break;

		case 'pg-3-8-3':
			_implementProfileSubnav();
			break;

		case 'pg-3-8-4':
		/* User: guestbook */
			_implementProfileSubnav();
			_implementExpSwitches();
			_implementFormLogic(pageId);
			_implementSleekTextarea($('#newentry0-textarea'), 500);
			break;

		case 'pg-2-2-10':
		/* MyProfile: Places */

			searchLocation = function() {
				if ($('#lq').val() == $('#lq').attr('title'))
					$('#lq').val('');

				if (($('#lq').val() == '') && ($('#li').val() == '') && ($('#lc').val() == '')) {
					alert('Bitte geben Sie mindestens einen Suchbegriff oder\neine Rubrik oder eine Region an.');
				} else {
					// Clear previous results:
					$('#search-result').html('');
					$('#locationfinder').addClass('loading');

					$('#search-result').load('/MyProfile/searchLocation', { q: $.trim($('#lq').val()), i: $('#li').val(), c: $('#lc').val() }, function() {
						$('#locationfinder').removeClass('loading');
						$('#search-result').addClass('active');
					});
				}
			}

			linkLocation = function(id, grp, pos) {
				btn = $('#found-location-' + pos + ' input.btnAddLocation');
				btn.get(0).disabled = true;

				$.getScript('/MyProfile/linkLocation/?i=' + id + '&g=' + grp, function() {
					btn.get(0).disabled = false;
				});
			}

			unlinkLocation = function(id, grp) {
				if (confirm('Diesen Ort (inkl. Kommentar) wirklich entfernen?')) {
					$.getScript('/MyProfile/unlinkLocation/?i=' + id + '&g=' + grp, function() {
					});
				}
			}

			showResult = function(n) {
				$('#locationlist .show-location').removeClass('show-location');
				$('#found-location-' + n).addClass('show-location');
			}

			$('.location .loc-data').live('mouseover', function() {
				$(this).find('h3 a.del').css('visibility', 'visible');
			});

			$('.location .loc-data').live('mouseout', function() {
				$(this).find('h3 a.del').css('visibility', 'hidden');
			});


			// Activate tabs
			$("#present-locations").tabs();

			$('#lq')
				.click(function(){
					$(this).removeClass('default');
					if (this.value == this.title) {
						this.value = '';
					}})
				.blur(function(){
					if (this.value == '') {
						$(this).addClass('default');
						this.value = this.title;
					}});

			$('.loc-pic>a,.loc-data h3 a[class!=del]').live('click', function(){
				window.open(this.href);
				try {
					pageTracker._trackPageview('/ExternalLink/Prinz');
					ivwTrack('ExternalLink');
				} catch(e) {}
				return false;
			});

			_implementSleekTextarea($('.comment-self textarea'), 250);

			saveOwnLocationComment = function(id) {
				$.post('/MyProfile/saveOwnLocationComment/', {l: id, c: $.trim($('#lc' + id + '-textarea').val())}, function(data){
					if (data.success) {
						$('#lc' + id + '-wrapper').removeClass('TA-dirty').addClass('TA-saved');
					}
				}, "json");
			}

			break;

		case 'pg-3-8-6':
		/* User: locations */

			$('.location-collapsed').attr('title', 'aufklappen');

			$('#pgcontent a.toggle').click(function() {
				this.blur();
				$(this).parents('div.location:first').toggleClass('location-collapsed');
				return false;
			});

			$('#pgcontent .location-collapsed').click(function() {
				$(this).removeClass('location-collapsed')
					   .attr('title', '');
			});

			$('.pic-expanded>a,.loc-data h3 a').click(function(){
				window.open(this.href);
				try {
					pageTracker._trackPageview('/ExternalLink/Prinz');
					ivwTrack('ExternalLink');
				} catch(e) {}
				return false;
			});

			break;

		case 'pg-3-10':
		/* Abuse form */
			_implementFormLogic(pageId);
			_implementCaptcha();
			break;

		case 'pg-1-12':
			$('#ea1').html('\x3C\x61\x20\x68\x72\x65\x66\x3D\x22\x6D\x61\x69\x6C\x74\x6F\x3A\x73\x61\x6C\x65\x73\x40\x66\x69\x6E\x79\x61\x2E\x64\x65\x22\x3E\x73\x61\x6C\x65\x73\x40\x66\x69\x6E\x79\x61\x2E\x64\x65\x3C\x2F\x61\x3E');
			_implementExpSwitches();
			_implementFX_SleekSelect($('#mailform'));
			_implementSleekTextarea($('#message0-textarea'), 2000);
			_implementFormLogic(pageId);
			_implementCaptcha();
			break;

		case 'pg-2-7':
			_implementFX_SleekSelect($('#frmOptions'));
			_implementSliderLists();
			$('#numMails1-daily').blur( function() {
				if (! ((this.value >= 1) && (this.value <= 99))) {
					this.value = '';
					$('#optMail1').removeAttr('checked');
				}
			});
			$('#numMails1-daily').focus( function() { $('#optMail1').attr('checked', 'checked'); } );
			$('#optMail1').click(function(){
				if ((this.checked) && (! (($('#numMails1-daily').val() >= 1) && ($('#numMails1-daily').val() <= 99))))
					$('#numMails1-daily').val('5');
			});
			break;

		case 'pg-1-5':
			$('.switchable a').click(function(){
				$(this).parent().toggleClass('switch');
				return false;
		    });
			break;

		case 'pg-4-1':
			/* Shop */
			$('.shopad a').click(function(){ window.open($(this).attr('link')); return false; })
						  .each(function(){ $(this).attr('link', this.href).attr('href', ''); });
			break;
	}
}

function _implementStickySky() {
	$(document).ready(function() {

		if ($('#ad-globalsky-content *').length > 0) {
			adContainer = $('#ad-globalsky');
			ad = $('#ad-globalsky-content');
			adContainerHeight = adContainer.height();
		    adContainerY = adContainer.offset().top;
			adY = ad.offset().top;
			adTop = ad.position().top
			$(window).scroll(function(){
				bodyHeight = $('body').height();
				scrollTop = $(window).scrollTop();
				maxTop = bodyHeight - adContainerHeight;

				if (scrollTop < maxTop && scrollTop > adTop) {
					adContainer.css('top', scrollTop-adTop);
				} else if (scrollTop < adTop) {
					adContainer.css('top', '0');
				} else if (scrollTop > maxTop) {
					adContainer.css('top', maxTop-adTop);
				}
			});
		}
	});
}

function _implementCaptcha()
{
	if ($('#captcha-wrapper').length)
	{
		setNewSrc = function() {
			$('#captcha-wrapper img').get(0).src = '/Captcha/get/?nc=' + Math.round(Math.random() * 100000000)
		}

		$('#captcha-wrapper')
			.find('input[type=button]').click( function() {
				$(this).siblings('img').get(0).src = '/img/void.gif';
				setTimeout("setNewSrc()", 100);
				$('#captcha').val('').focus();
			} );

		setTimeout("setNewSrc()", 100);
	}
}

function _implementSleekTextarea(jq_objColl, /*optional: */maxlength)
{
	// jq_objColl 	is a collection of <textarea> elements

	// Loop through the textareas
	jq_objColl.each(function()
	{
		TA = $(this);

		// Check if the textarea has an id and if it matches the pattern (ex. 'entry1234-textarea').
		// Parse the integer value and the base name:

		if ((TA_id = TA.attr('id')) && ((m = TA_id.match(/^([a-z]+([0-9]+))\-textarea/)) != null))
		{
			TA_basename = m[1];	// contains e.g. 'entry1234'
			TA_entryid = m[2];  // contains e.g. '1234'
			TA_wrappername = TA_basename + '-wrapper';

			TA_maxlen = (maxlength == undefined ? 0 : maxlength);

			// Implement default bahaviors to TA's wrapper:
			TA.parents('#' + TA_wrappername).each( function(i, w){

				if (TA.attr('readonly'))
					return;

				TA.mouseover( 	function() { $('#' + w.id).addClass('TA-over'); });
				TA.mouseout( 	function() { $('#' + w.id).removeClass('TA-over'); });
				TA.focus( 		function() { $('#' + w.id).removeClass('TA-saved')
														  .addClass('TA-focus'); });
				TA.blur( 		function() { $('#' + w.id).removeClass('TA-focus'); });
				TA.change( 		function() { $('#' + w.id).removeClass('TA-saved')
														  .addClass('TA-dirty'); });
				TA.keydown( 	function() { $('#' + w.id).removeClass('TA-saved')
												 		  .addClass('TA-dirty'); });

				TA.keyup(		function() { implementMaxLength(this, TA_maxlen, w); } );
			});

			// Implements optional character limitation
			implementMaxLength = function(TA_obj, n, w) {
				if (! (n > 0)) return;

				if ((TA_val = $(TA_obj).val()).length > n) {
					$(TA_obj).val(TA_val.substring(0, n));
				}

				// If present, update the graphical char counter:
				$(w).find('.charcounter:first').each( function() {
					avail = ((d = (n - TA_val.length)) < 0 ? 0 : d).toString()
					fill = ((fv = Math.round((TA_val.length * 100) / n)) > 100 ? 100 : fv).toString();
					barStyle = fill < 67 ? 3 : fill < 90 ? 2 : 1;

					$(this).find('.chars-avail').html(_addThousandsSeparator(avail));
					$(this).find('.bar:first div').removeClass().addClass('bg' + barStyle).css('width', fill + 'px');
				});
			}

			// Trigger maxlength and char counter redraw
			TA.keyup();
		}
	});
}

function showAds()
{
	$('div.ad-content').addClass('ad-loaded').each(function() {
		try {
			$('#' + this.id.replace(/-content$/, '')).get(0).appendChild(this);
		} catch(e) {}
	});
}


// -----------------------------------------------
// ---- private ----------------------------------

function _implementFX_SleekSelect(parentObj)
{
	parentObj.find('div[class^=sleekselect]')
		.hover(
			function() {
				if (ssEngaged == false)
					$(this).addClass('ssel-active');
			},
			function() {
				if (!ssEngaged)
					$(this).removeClass('ssel-active').find('select').get(0).blur();
			}
		)
		.bind('__ssel_set', function(e, newSelIndex) {
			// Custom event to set the select to a specific list index
			$(this).find('select').get(0).selectedIndex = newSelIndex;
			$(this).find('select').trigger('change', [false]);
		})
		.find('select')
			.focus(function() {
				ssEngaged = true;
			})
			.change(function(e, trigger_custom_event) {
				// On change, the SleekSelect's span element will also retrieve the same classes
				// as the selected option element.
				$(this).parent().find('span')
					.text($(this).find('option:selected').text())
					.attr('class', '')
					.attr('class', $(this).find('option:selected').attr('class'));

				$(this).trigger('blur');

				// Trigger custom onchange event, unless prohibited:
				if (! (trigger_custom_event == false))
					$(this).parent().trigger('__ssel_onchange');
			})
			.blur(function() {
				$(this).parent().removeClass('ssel-active');
				ssEngaged = false;
			})
			.each(function(k,srcObj) {
				// Trigger change() event on object init, so that the selected option will be
				// displayed on page load.
				$(this).trigger('change', [false]);
			})
	;
}

/* _implementOptionSwitches */
function _implementOptionSwitches() {

	$('#canvas li[id^=opt-] a').click( function() {

		$(this).parent().siblings('li').removeClass('item-active').end().addClass('item-active');

		test = $(this).parent().get(0).id.match(/^opt\-(.+)\-\-(.+)$/);
		optionBasename = test[1];
		optionValue = test[2];

		// perform UI actions (ajax calls etc.):
		switch (optionBasename) {

			case 'msgbodystyle':
				$('#msgbody').removeClass('textstyle-1 textstyle-2 textstyle-3').addClass('textstyle-' + optionValue);
				break;

			case 'visitorstype':
				Finya.Settings.listVisitors.mode = optionValue;
				updateListVisits();
				break;

			case 'visitorsgender':
				Finya.Settings.listVisitors.gender = optionValue;
				updateListVisits();
				break;

			case 'visitorsview':
				Finya.Settings.listVisitors.viewtype = optionValue;
				updateListVisits();
				break;

			case 'onlineview':
				Finya.Settings.listOnline.viewtype = optionValue;
				updateListOnline();
				break;

			case 'onlinegender':
				Finya.Settings.listOnline.gender = optionValue;
				updateListOnline();
				break;

			case 'citiesgender':
			case 'zodiacgender':
			case 'wordsgender':
				context = (id = $(this).parents('div:eq(1)').attr('id')).substring(id.indexOf('-') + 1);
				populateTagCloud (context, optionValue);
				break;

			case 'list1gender':
			case 'list2gender':
				context = (id = $(this).parents('div:eq(1)').attr('id')).substring(id.indexOf('-') + 1);
				populateList (context, optionValue);
				break;
		}
		return false;
	});
}

function _implementSliderLists()
{
	$('ul.list-slide li>h2>a').click(function() {
		this.blur();

		$(this).parent().next('div.li-content').slideToggle('fast', function() {
			LI = $(this).parents('li:first');

			if ($(this).css('display') == 'block') {
				LI.addClass('item-expanded');

				// See if a function is attached to the LI's data attribute, and, if so, execute it.
				if (typeof LI.data('callback') == 'function') {
					LI.data('callback').call(LI /* scope, relevant for 'this' in the callback function, now refering to the LI. */);

					// Detach the function so it won't be executed again!
					LI.data('callback', null);
				}
			} else {
				LI.removeClass('item-expanded');
			}
		});

		return false;
	});
}

/* _implementExpSwitches() */
function _implementExpSwitches() {
	$('#pgcontent a[class*=switch][id]').click(
		function() {
			$('#' + this.id + '-container').toggleClass('item-expanded');
			this.blur();
			if (! $(this).hasClass('followlink'))
				return false;
		}
	)
}

function _implementFormLogic(pageId) {

	RE_EMAIL 	= /^[a-z0-9\._%+-]+@[a-z0-9.-]+\.[a-z]{2,6}$/i;
	RE_NICKNAME	= /^[a-zäáàëéèöóòüúùß0-9_-]{4,14}$/i;
	RE_PASSWORD	= /^.{6,20}$/;

	map_gs		= new Array();
	map_gs[1]	= ['1', ''];
	map_gs[11]	= ['1', '1'];
	map_gs[12]	= ['1', '2'];
	map_gs[2]	= ['2', ''];
	map_gs[21]	= ['2', '1'];
	map_gs[22]	= ['2', '2'];

	switch (pageId) {

		case 'pg-1-1':

			if ($('#nickname').length > 0)
			{
				$('#nickname').attr('autocomplete', 'off');
				$('login-pwd').val('');

				if ($('#nickname').val() == '') {
					setTimeout("$('#nickname').focus()", 1000);
					$('#nickname').addClass('hint');
				} else {
					setTimeout("$('#login-pwd').focus()", 1000);
				}

				$('#login-pwd')
						.addClass('hint')
						.bind('click keyup', function(){ $(this).removeClass('hint'); })
						.blur(function(){ if ($(this).val() == '') $(this).addClass('hint'); })

				$('#nickname')
						.bind('click keyup', function(){ $(this).removeClass('hint'); })
						.blur(function(){ if ($(this).val() == '') $(this).addClass('hint'); })
			}

			if ($('#frmLogin').length) {
				$('#frmLogin').submit(function() {
					$('#loginmsg').hide();
					$('#login-res').val(hh($('#login-c').val(), shftw($('#login-pwd').val())));
				});
			}
			break;

		case 'pg-0-5':
		case 'pg-1-13':
			if ($('#nickname').length)
				$('#nickname').focus();

			if ($('#frmLogin').length) {
				$('#frmLogin').get(0).reset();
				$('#frmLogin').submit(function() {
					$('#login-res').val(hh($('#login-c').val(), shftw($('#login-pwd').val())));
				});
			}
			break;

		case 'pg-1-12':
			$('#btnSend').click(function(){
				this.disabled = true;

				// Clear previous form errors:
				$(this).parents('form:last').find('.inputset').removeClass('inputset-err');

				// Collect current form errors:
				formErrors = new Array();
				if (! ($('#data-title input:radio:checked').val() > 0))
					formErrors.push('title');
				if ($.trim($('#name1').val()) == '')
					formErrors.push('name1');
				if ($.trim($('#name2').val()) == '')
					formErrors.push('name2');
				if ($('#email').val().match(RE_EMAIL) == null)
					formErrors.push('email');
				if (! ($('#ssel-topic-value').val() > 0))
					formErrors.push('topic');
				if ($.trim($('#message0-textarea').val()) == '')
					formErrors.push('message');

				// Pass rest of the form processing to the server:
				$.post('/Legal/validateContactSubmit', {c: $('#captcha').val()}, function(data) {
					eval(data);
					if (formErrors.length == 0)
					{
						$('#mailform').attr('action', '/Legal/contact/submit').submit();
						return;
					}
					// Active error messages for each field:
					$.each(formErrors, function() {
						$('#data-' + this).addClass('inputset-err');
					});
				});
				return false;
			}); // $('#btnSend').click
			break;

		case 'pg-1-2':
			$('#btnSend').click(function() {
				this.value = 'Bitte warten...';
				this.disabled = true;

				// Clear previous form errors:
				$(this).parents('form:last').find('.inputset').removeClass('inputset-err');

				// Collect current form errors:
				formErrors = new Array();
				if (!$('#gender-opt1').is(':checked') && !$('#gender-opt2').is(':checked'))
					formErrors.push('gender');
				if (!$('#seeking-opt1').is(':checked') && !$('#seeking-opt2').is(':checked') && !$('#seeking-opt3').is(':checked'))
					formErrors.push('seeking');
				if (($('#ssel-dobday-value').val() == '') || ($('#ssel-dobmonth-value').val() == '') || ($('#ssel-dobyear-value').val() == ''))
					formErrors.push('dob');
				if ($('#email1').val().match(RE_EMAIL) == null) {
					formErrors.push('email1');
					formErrors.push('email2');
					$('#email2').val('');
				} else if ($('#email1').val() != $('#email2').val()) {
					formErrors.push('email2');
				}
				if (($('#location-inputmode').hasClass('mode-id')) && ($('#ci')[0] && (!($('#ci').val() > 0))) ) {
					formErrors.push('location-zip');
				}
				if ($('#ssel-country-value').val() == '')
					formErrors.push('country');
				if (($('#location-inputmode').hasClass('mode-txt')) && (($('#location').val() == '')))
					formErrors.push('location-city');
				if ($('#username').val().match(RE_NICKNAME) == null)
					formErrors.push('username');
				if ($('#pwd1').val().match(RE_PASSWORD) == null) {
					formErrors.push('pwd1');
					formErrors.push('pwd2');
					$('#pwd2').val('');
				} else if ($('#pwd1').val() != $('#pwd2').val()) {
					formErrors.push('pwd2');
					$('#pwd2').val('');
				}
				if ($('#captcha-reg').val() == '')
					formErrors.push('captcha');
				if (!$('#terms1').is(':checked'))
					formErrors.push('privacy');
				if (!$('#terms2').is(':checked'))
					formErrors.push('terms');

				$('#ck').val( shftw($('#pwd1').val()) );
				$('#dob').val( $('#ssel-dobyear-value').val() + '-' + $('#ssel-dobmonth-value').val() +  '-' + $('#ssel-dobday-value').val() );

				// Pass rest of the form processing to the server:
				$.post('/Registration/validateRegSubmit', {c: $('#captcha').val(), dob: $('#dob').val(), nn: $('#username').val(), em: $('#email1').val()}, function(data) {
					eval(data);
					if (formErrors.length == 0)
					{
						$('#frmRegistration').attr('action', '/Registration/process').submit();
						return true;
					}
					// Active error messages for each field:
					$.each(formErrors, function() {
						$('#inputset-' + this).addClass('inputset-err');
					});
					// Jump to error:
					self.location = '#erranchor-' + formErrors[0];
					// Re-activate button
					$('#btnSend').get(0).disabled = false;
					$('#btnSend').get(0).value = 'Jetzt registrieren';
				});
				return false;
			});
			break;

		case 'pg-1-3':
			/* Recover pwd */

			$('#btnSubmit').click( function() {

				this.disabled = true;

				// Clear previous form errors:
				$(this).parents('form:last').find('.inputset').removeClass('inputset-err');

				// Collect current form errors:
				formErrors = new Array();
				if ($('#email').val().match(RE_EMAIL) == null)
					formErrors.push('email');

				// Pass rest of the form processing to the server:
				$.post('/Registration/validateRecoverSubmit', {c: $('#captcha').val()}, function(data) {
					eval(data);
					if (formErrors.length == 0)
					{
						$('#frmRecover').attr('action', '/Registration/recover/send').submit();
						return;
					}
					// Active error messages for each field:
					$.each(formErrors, function() {
						$('#inputset-' + this).addClass('inputset-err');
					});
					// Jump to error:
					self.location = '#erranchor-' + formErrors[0];
					// Re-activate button
					$('#btnSubmit').get(0).disabled = false;
				});
				return false;
			});

			break;

		case 'pg-1-3-1-1':
			$('#btnSubmit').click( function() {

				this.disabled = true;

				// Clear previous form errors:
				$(this).parents('form:last').find('.inputset').removeClass('inputset-err');

				// Collect current form errors:
				formErrors = new Array();
				if ($('#pwd1').val().match(RE_PASSWORD) == null) {
					formErrors.push(['pwd1']);
					formErrors.push(['pwd2']);
					$('#pwd2').val('');
				} else if ($('#pwd1').val() != $('#pwd2').val()) {
					formErrors.push(['pwd2']);
					$('#pwd2').val('');
				}

				if (formErrors.length == 0)
				{
					$('#np').val( shftw($('#pwd1').val()) );
					$('#frmChPwd').attr('action', '/Registration/changePwd').submit();
					return true;
				}

				// Active error messages for each field:
				$.each(formErrors, function() {
					$('#inputset-' + this).addClass('inputset-err');
				});
				// Jump to error:
				self.location = '#erranchor-' + formErrors[0];
				// Re-activate button
				$('#btnSubmit').get(0).disabled = false;

				return false;
			});

			break;

		case 'pg-2-2-1':

			$('#btnSubmit').click(function()
			{
				this.disabled = true;

				// Clear previous form errors:
				$(this).parents('form:last').find('.inputset').removeClass('inputset-err');

				// Collect current form errors:
				formErrors = new Array();
				switch (self.c_mode) {
					default:
					case 'id':
						if (!($('#ssel-ci-value').val() > 0))
							formErrors.push(['citybyid']);
						break;
					case 'txt':
						if ($('#location').val().match(/^[\w]{2}/) == null)
							formErrors.push(['citybytext']);
						break;
				}

				if (formErrors.length == 0)
				{
					$('#frmData').attr('action', '/MyProfile/update/data').submit();
					return;
				}

				// Active error messages for each field:
				$.each(formErrors, function() {
					$('#inputset-' + this).addClass('inputset-err');
				});
				// Jump to error:
				self.location = '#erranchor-' + formErrors[0];
				// Re-activate button
				$('#btnSubmit').get(0).disabled = false;

				return false;
			});
			break;

		case 'pg-2-2-3':
			/* My Profile tags */

			$('#newtag').keyup(function() {
				$("#btnAdd")[0].disabled = (! ($.trim(this.value).length > 2));
				if ($('#newtag').val() == '')
					$('#syntaxhint').css('display', 'none');

			});

			$('#frmTags').submit(function() {
				$("#btnAdd").attr('disabled', 'disabled');
				$('#newtag').val($.trim($('#newtag').val()));

				newTag = $('#newtag').val();
				if (isValidTag(newTag))
				{
					$("#newtag").attr('disabled', 'disabled');
					$('#usertags').load('/MyProfile/matchclick/addtag', {t: newTag, i: $('#tagid').val()});
				}
				else
				{
					$('#syntaxhint').html('Ihr MatchClick-Wort ist nicht gültig. Bitte entfernen Sie bspw. überflüssige Sonderzeichen.');
					$('#syntaxhint').css('display', 'block');
					return false;
				}
			});

			function isValidTag(tagVal) {
				return (tagVal.match(/^[a-zäáàëéèöóòüúù0-9][a-zäáàëéèöóòüúùß0-9 '-]{1,38}[a-zäáàëéèöóòüúùß0-9]$/i) != null)
					&& (tagVal.match(/[^a-zäáàëéèöóòüúùß0-9]{2,}/i) == null)
			}

			unlinkTag = function(i) {
				$('#usertags').load('/MyProfile/matchclick/unlinktag', {i: i});
			}

			break;

		case 'pg-2-2-6':
		/* mail settings */

			$('#btnNewAddressConfirm').click(function()
			{
				$('#frmMail').find('.inputset').removeClass('inputset-err');

				formErrors 	= new Array();

				if ( (($('#data-newmail1').val().match(RE_EMAIL) == null) || ($('#data-newmail2').val().match(RE_EMAIL) == null))
					 || ($('#data-newmail1').val() != $('#data-newmail2').val())
					 || ($('#data-newmail1').val() == $('#data-current-email').html()) )
				{
					$('#data-newmail2').val('');
					formErrors.push(['mail']);
				}

				if (formErrors.length == 0) {
					$('#actionpane').addClass('status-sending');
					$.post('/MyProfile/email/update', {e:$('#data-newmail1').val()}, function(){
						self.location.href = '/MyProfile/email/?emmsg=confirm';
					});
					return;
				}

				// Active error messages for each field:
				$.each(formErrors, function() {
					$('#data-' + this).addClass('inputset-err');
				});
				// Jump to error:
				self.location = '#erranchor-' + formErrors[0];
				return false;
			});

			$('#btnCancelPending').click(function() {
				$.post('/MyProfile/email/cancelPending', null, function() {
					self.location.href = '/MyProfile/email/?emmsg=canceled';
				});
				return;
			});
			break;

		case 'pg-2-2-7':
		/* change pwd */

			if ($('#frmPwd').length)
				$('#frmPwd').get(0).reset();

			$('#btnNewPwdConfirm').click(function()
			{
				$('#frmPwd').find('.inputset').removeClass('inputset-err');

				formErrors 	= new Array();

				if (($('#pwd-new1').val().match(RE_PASSWORD) == null)
					|| ($('#pwd-new1').val() != $('#pwd-new2').val())
					|| ($('#pwd-new1').val() == $('#pwd-current').val()))
					formErrors.push(['comp']);

				resp = hh($('#pwd-c').val(), shftw($('#pwd-current').val()));

				$.post('/MyProfile/passwd/validate', {res:resp}, function(data) {
					eval(data);
					if (formErrors.length == 0) {
						$.post('/MyProfile/passwd/update', {res:resp, n:shftw($('#pwd-new1').val())}, handleAjaxRsp);
						return true;
					}

					// Active error messages for each field:
					$.each(formErrors, function() {
						$('#inputset-' + this).addClass('inputset-err');
					});

					// Jump to error:
					self.location = '#erranchor-' + formErrors[0];
				});
				return false;
			});
			break;

		case 'pg-2-2-8':

			$('#txtConfirm').keyup(function(){
				$('#btnTerminate').get(0).disabled = (this.value != 'JA');
			});
			$('#btnTerminate').click(function(){
				this.disabled = true;
				$.post('/MyProfile/account', {rq: $('#frmTerminate input:radio:checked').val()}, handleAjaxRsp);
			});

			break;

		case 'pg-2-3-1':
		case 'pg-2-3-2':
			/* Inbox/outbox form handling */
			$('#frmMails').get(0).reset();
			$('#frmMails').submit(function() {
				msgConfirm	= '';
				msgAbort	= '';
				numChecked 	= $('#tbl-mailbox tbody input:checkbox:checked').length;

				if (! (numChecked > 0)) {
					msgAbort = 'Sie haben keine Nachrichten ausgew\u00e4hlt.';
				} else {
					msgConfirm = 'L\u00d6SCHEN von Nachrichten best\u00e4tigen:\n\nSie beabsichtigen, ' + numChecked + (numChecked == 1 ? ' Nachricht' : ' Nachrichten') + ' zu l\u00f6schen.\nKlicken Sie auf \'OK\', um fortzufahren.';
				}

				switch (true) {
					case (msgAbort != ''):
						alert(msgAbort);
						return false;

					case (msgConfirm != ''):
						return confirm(msgConfirm);

					default:
						return false;
				}
			});

			break;

		case 'pg-2-4-1':
			/* Guestbook form handling */

			$('#data-date').focus( function() {
				$(this).parent().find('input:radio').attr('checked', true);
			})

			$('#frmItems').submit(function()
			{
				msgConfirm	= '';
				msgAbort	= '';
				numChecked 	= $('.gbentry input:checkbox:checked').length;

				switch (parseInt($('#useraction input:radio:checked').val()))
				{
					case 1:	/* delete selected entries */

						if (!(numChecked > 0)) {
							msgAbort = 'Sie haben keine G\u00e4stebucheintr\u00e4ge ausgew\u00e4hlt.';
						} else {
							msgConfirm = 'L\u00d6SCHEN von G\u00e4stebucheintr\u00e4gen best\u00e4tigen:\n\nSie beabsichtigen, ' + numChecked + (numChecked == 1 ? ' G\u00e4stebucheintrag' : ' G\u00e4stebucheintr\u00e4ge') + ' zu l\u00f6schen.\nKlicken Sie auf \'OK\', um fortzufahren.';
						}
						break;

					case 2:	/* delete by date */

						if (dat = $('#data-date').val().match(/^(\d{1,2})\.(\d{1,2}).(\d{4})$/))
						{
							$('#data-date-xmit').val(dat[3] + '-' + dat[2] + '-' + dat[1]);

							msgConfirm = 'L\u00d6SCHEN von G\u00e4stebucheintr\u00e4gen best\u00e4tigen:\n\nSie beabsichtigen, alle G\u00e4stebucheintr\u00e4ge zu l\u00f6schen, die \u00e4lter sind als der ' + $('#data-date').val() + '.\nKlicken Sie auf \'OK\', um fortzufahren.'
									   + ((numChecked > 0) ?
									   			'\n\n(HINWEIS: Sie haben auch ' + numChecked + (numChecked == 1 ? ' G\u00e4stebucheintrag' : ' G\u00e4stebucheintr\u00e4ge') + ' markiert. Markierungen haben bei diesem Vorgang keine Funktion.)'
									   			: '');
						} else {
							msgAbort = 'Bitte geben Sie ein Datum im Format TT.MM.JJJJ ein.';
						}
						break;

					case 3:	/* delete entries from inactive users */

						msgConfirm = 'Bitte best\u00e4tigen:\n\nSie beabsichtigen, alle G\u00e4stebucheintr\u00e4ge zu l\u00f6schen, deren Absender\nnicht mehr Mitglied bei Finya.de sind.\nKlicken Sie auf \'OK\', um fortzufahren.'
									   + ((numChecked > 0) ?
								   			'\n\n(HINWEIS: Sie haben auch ' + numChecked + (numChecked == 1 ? ' G\u00e4stebucheintrag' : ' G\u00e4stebucheintr\u00e4ge') + ' markiert. Markierungen haben bei diesem Vorgang keine Funktion.)'
								   			: '');

						break;
				}

				if (msgAbort) {
					alert(msgAbort);
					return false;
				}

				if (msgConfirm)
					return confirm(msgConfirm);

				return false;
			});

			break;

		case 'pg-2-6':
		/* Blacklist */

			$('#btnEdit').click(function() {
				$('#frmBlacklist').attr('action', '/Blacklist/edit').submit();
			});

			$('#btnCleanup').click(function() {
				$('#frmBlacklist').attr('action', '/Blacklist/cleanup').submit();
			});

			break;

		case 'pg-3-1':
			/* 'Search And Browse' Channel */

			$('#btnExtSrch').click(function() {
				$('#qs').val(2);
				$('#frmSearch').attr('action', '/SearchAndBrowse/search');
				$('#frmSearch').submit();
			});

			$('#ssel-gender').bind('__ssel_onchange', function() {
					gs = $('#ssel-gender-value').val();
					$('#gender').val('');
					$('#seeks').val('');
					$('#gender').val(map_gs[gs][0]);
					$('#seeks').val(map_gs[gs][1]);
			});

			$('#ssel-location').bind('__ssel_onchange', function() {
				if (locval = $('#ssel-location-value').val().match(/^(Z?)(\d+)$/)) {
					$('#home_state').val((locval[1] == 'Z') ? '' : locval[2]);
					$('#home_zip').val((locval[1] == 'Z') ? locval[2] : '');
				} else {
					$('#home_state,#home_zip').val('');
				}
			});

			break;

		case 'pg-2-3-1-1':
			/* Message reply dialog */
		case 'pg-3-8-2':
			/* Profile: contact */

			if ($('#frmMsg').length)
				$('#frmMsg').get(0).reset(); // Prevent FF from using old form values

			$('#btnSubmit,#btnPreview').click(function() {
				if ((is_prv = (this.id == 'btnPreview')) || true)
				{
					// Disable all form-related buttons
					$(this).parents('.actionbar:last').find('input:button').attr('disabled', true);

					// Set the correct form action and submit the form
					$('#frmMsg').attr('action', '/User/sendMessage/' + $('#ui').val() + '/' + $('#uh').val() + (is_prv ? '/?pv=1' : '')).submit();
				}
			});

			$('#btnChange').click(function() {
				history.go(-1);
			});

			$('#lnkDelete').click(function() {
				if(confirm('Diese Nachricht l\u00f6schen?')) {
					$('#mh').attr('name', 'chk[' + $('#mid').val() + ']');
					$('#frmMsg').attr('action', '/Mailbox/cleanup').submit();
				}
				return false;
			});

			$('#btnUnspam').click(function() {
				$('#frmMsg').attr('action', '/Mailbox/unspam').submit();
			});

			if ($("#dialog").length > 0) {
				$("#dialog").dialog({
					autoOpen: false,
					modal: true,
					draggable: true,
					resizable: false,
					width: 350,
					buttons: {
						'OK': function() {
							$(this).dialog('close');
						}},
					close: function(event, ui) { self.location.reload(); }
				});
				$('#func-block a').click(function(){
					$.post('/Mailbox/do/block', { uid: $('#ui').val() },
						function(data) {
							if (data.bl > 0) {
								$("#dialog").dialog('open');
							}
						}, 'json');
					return false;
				});
			}

			break;

		case 'pg-3-8-4':
		/* Profile: guestbook */

			$('#btnPreview').click(function() {
				$(this).attr('disabled', 'disabled');
				$('#btnSubmit').attr('disabled', 'disabled');
				$('#frmGb').attr('action', '/Guestbook/preview').submit();
			})
			$('#btnSubmit').click(function() {
				$(this).attr('disabled', 'disabled');
				$('#btnPreview').attr('disabled', 'disabled');
				$('#frmGb').attr('action', '/Guestbook/post').submit();
			})
			break;

		case 'pg-3-10':
			/* Abuse form */

			$('#comment').change(function(){
				if (this.value.length > 10000) {
					alert('Ihre Eingabe wurde auf 10.000 Zeichen gek\u00fcrzt.');
					this.value = this.value.substring(0, 10000);
				}
			});
			if ($('#frmAbuse').length)
				$('#frmAbuse').get(0).reset();

			$('#btnSend').click(function() {
				this.disabled = true;


				// Clear previous form errors:
				$(this).parents('form:last').find('.inputset').removeClass('inputset-err');

				// Collect current form errors:
				formErrors = new Array();
				if (! ($('#inputset-abusereason input:radio:checked').val() > 0))
					formErrors.push(['abusereason']);
				if ($.trim($('#comment').val()).length == 0)
					formErrors.push(['comment']);

				// Pass the rest of the form processing to the server:
				$.post('/Legal/validateAbuseSubmit', {c: $('#captcha').val()}, function(data) {
					eval(data);
					if (formErrors.length == 0)
					{
						if (confirm('Sie sind im Begriff, das Mitglied mit dem Pseudonym\n\n' + $('#txtAbuserName').text() + '\n\nwegen missbräuchlicher Verwendung von Finya.de anzuzeigen.\nKlicken Sie OK, um fortzufahren.'))
							$('#frmAbuse').attr('action', '/Legal/abuse').submit();

						return;
					}
					// Active error messages for each field:
					$.each(formErrors, function() {
						$('#inputset-' + this).addClass('inputset-err');
					});
					// Jump to error:
					self.location = '#erranchor-' + formErrors[0];
					// Re-activate button
					$('#btnSend').get(0).disabled = false;
				});
				return false;
			});
			break;
	}
}

function _addThousandsSeparator(num) {
	_reverseString = function(str) {
		for (var newval = '', i = str.length-1; i>=0; i--) { newval += str.charAt(i); }
		return newval;
	}

	num = num.toString();
	if (num.length > 3) {
		return _reverseString(_reverseString(num).replace(/(\d{3})/g, '$1' + '.' ));
	} else {
		return num;
	}
}

/* gnc = get new captcha */
function gnc(wrapperId, ident) {
	$.post('/Index/getNewCaptcha', {i: ident, w: wrapperId}, handleAjaxRsp)
}

function _implementRefreshableSections()
{
	$('h2.refreshable a').click(function(){
		$(this).get(0).blur();
		h2 = $(this).parents('h2');

		h2.addClass('loading');

		// execute callback, if provided
		if (typeof $(this).data('callback') == 'function')
			$(this).data('callback').call(h2);

		return false;
	});
}


/* _implementNav() */
function _implementNav()
{
	activateMenuItem = function(id) {
		$('#nav-main>li').removeClass('item-active');
		$('#' + id).addClass('item-active');
	}

	$('#nav-main').data('active_item', $('#nav-main>li.item-active').attr('id'));

	$('#nav-main>li')
		.hover(
			/* mouse over */
			function() {
				if (! $('#nav-main').data('clicked')) {
					clearTimeout(tnav2);
					tnav = setTimeout("activateMenuItem('" + this.id + "')", 300);
				}
			},
			/* mouse out */
			function() {
				if (! $('#nav-main').data('clicked')) {
					clearTimeout(tnav);
					tnav2 = setTimeout("activateMenuItem('" + $('#nav-main').data('active_item') + "')", 400);
				}
			}
		)
		.click(
			function(){
				clearTimeout(tnav);
				clearTimeout(tnav2);
				$('#nav-main').data('clicked', true);
			});

	/* implement active chats menu hover for old IE */
	if (isOldIE) {
		$('li#mc-chat').hover(
			function() { $(this).addClass('hover'); },
			function() { $(this).removeClass('hover'); }
		);
	}
}

function _implementProfileSubnav() {
	// setTimeout('updateListVisits()', 200);

	$('#pnav-more')
		.hover(
			function(){
				if (isOldIE) { $(this).addClass('hover'); }
				$('#pnav-more').addClass('hover');
			},
			function(){
				if (isOldIE) { $(this).removeClass('hover'); }
				$('#pnav-more').removeClass('hover');
			});

	$('#lnk-block').click(
		function() {
			if (u.bl == 0) {
				msg = "NUTZER SPERREN\n\nSie beachsichtigen, diesen Nutzer zu Ihrer Sperrliste hinzuzuf\u00fcgen, sodass kein Kontakt mehr zwischen Ihnen m\u00f6glich ist.\n\nKlicken Sie auf 'OK', um diesen Vorgang zu best\u00e4tigen.";
			} else if (u.bl == 1) {
				msg = "SPERRUNG AUFHEBEN\n\nSie beachsichtigen, die Sperrung zu diesem Nutzer aufzuheben, sodass dieser wieder Kontakt mit Ihnen aufnehmen kann.\n\nKlicken Sie auf 'OK', um diesen Vorgang zu best\u00e4tigen.";
			}

			return (msg && confirm(msg));
		}
	);
}

function toggleListOnline()
{
	Finya.Settings.listOnline.expansion = Finya.Settings.listOnline.nextExpansion;
	updateListOnline();
}

function toggleListVisits()
{
	Finya.Settings.listVisitors.expansion = Finya.Settings.listVisitors.nextExpansion;
	updateListVisits();
}

function updateListOnline()
{
	if ($('#list-online').length > 0)
	{
		lo = Finya.Settings.listOnline;
		$('#list-online').addClass('content-loading');
		$('#listonline-content').load('/MyFinya/updateListOnline', {g: lo.gender, v: lo.viewtype, x: lo.expansion});
	}
}

function updateListVisits()
{
	if ($('#list-visitors').length > 0)
	{
		lv = Finya.Settings.listVisitors;
		$('#list-visitors').addClass('content-loading');
		$('#listvisits-content').load('/MyFinya/updateListVisits', {m: lv.mode, g: lv.gender, v: lv.viewtype, x: lv.expansion});
	}
}

function updateMsgCenter()
{
	if ($('#mc-wrapper').length > 0)
		$('#mc-wrapper').load('/MyFinya/refreshMsgCenter', {nc: Math.round(Math.random() * 1000000000)});
}

function initListVisits(m, g, v, x, xf)
{
	if (o = Finya.Settings.listVisitors)
	{
		o.mode 			= m;
		o.gender 		= g;
		o.viewtype 		= v;
		o.expansion 	= x;
		o.nextExpansion = xf;
	}
}

function initListOnline(g, v, x, xf)
{
	if (o = Finya.Settings.listOnline)
	{
		o.gender 		= g;
		o.viewtype 		= v;
		o.expansion 	= x;
		o.nextExpansion = xf;
	}
}

function _initSidebar()
{
	if ($('#list-visitors').length > 0)
	{
		Finya.Settings.listVisitors =
		{
			mode: 			null,
			gender: 		null,
			viewtype:	 	null,
			expansion: 		null,
			nextExpansion: 	null
		}
	}

	if ($('#list-online').length > 0)
	{
		Finya.Settings.listOnline =
		{
			gender: 	null,
			viewtype: 	null
		}
	}
}

function help(a) {
	window.open(a.href, 'finya_help_window', '');
	return false;
}

function reloadLocationList(context, country, zip, presel_cityid, doAfterCompletion) {
	if (presel_cityid == undefined)
		presel_cityid = '';

	window._onAfterLocationChange = doAfterCompletion;

	$.post('/Index/getLocation', {ct: context, c: country, z: zip, ci: presel_cityid, r: Math.round(Math.random() * 10000000)}, handleAjaxRsp)
}

// centering elements in the viewport
(function($){
  $.fn.center = function(options) {
    var pos = {
      sTop : function() {
        return window.pageYOffset || document.documentElement && document.documentElement.scrollTop ||	document.body.scrollTop;
      },
	  sLeft : function() {
        return window.pageXOffset || document.documentElement && document.documentElement.scrollLeft ||	document.body.scrollLeft;
      },
      wHeight : function() {
        return window.innerHeight || document.documentElement && document.documentElement.clientHeight || document.body.clientHeight;
      },
      wWidth : function() {
        return window.innerWidth || document.documentElement && document.documentElement.clientWidth || document.body.clientWidth;
      }
    };
    return this.each(function(index) {
      if (index == 0) {
        var $this = $(this);
        var elHeight = $this.height();
		var elWidth = $this.width();
		var elTop = pos.sTop() + (pos.wHeight() / 2) - (elHeight / 2);
		var elLeft = pos.sLeft() - 230 + (pos.wWidth() / 2) - (elWidth / 2);  // -230! zum Zentrieren im Content
        $this.css({ position: 'absolute', marginTop: '0', top: elTop, marginLeft: '0', left: elLeft });
      }
    });
  };

})(jQuery);

function zoomInBox(boxId) {
	$('#dialog-bg').height($('body').height()+30).show();
	$(boxId).center().css('z-index', '101').fadeIn();
	$(window).scroll(function() {
	      $(boxId).center();
	});
	$(window).resize(function() {
	      $(boxId).center();
	});
}

function zoomOutBox(boxId) {
	$(boxId).fadeOut(function(){
		$(boxId).css('z-index', '-1');
	});
	$('#dialog-bg').hide();
	$(window).unbind('scroll').unbind('resize');
}

function initZoomBox(boxId, zoomInElemId, zoomOutElemId) {
	$('body').append('<div id="dialog-bg"></div>');
	$(boxId).appendTo('body');
	$(zoomInElemId).click(function() {
		zoomInBox(boxId);
		return false;
	});
	$(zoomOutElemId).click(function(){ zoomOutBox(boxId); });
}

function ivwTrack(PI_Name)
{
	var newSrc = "http://finya.ivwbox.de/cgi-bin/ivw/CP/" + PI_Name + ";?r=" + escape(document.referrer) + "&d=" +(Math.random()*100000);
	$('img#ivwPixel').attr('src', newSrc);
}


/** Helpers **********************/

function handleAjaxRsp(response)
{
	eval(response);
}