$.extend({URLEncode:function(c){var o='';var x=0;c=c.toString();var r=/(^[a-zA-Z0-9_.]*)/;
  while(x<c.length){var m=r.exec(c.substr(x));
    if(m!=null && m.length>1 && m[1]!=''){o+=m[1];x+=m[1].length;
    }else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16);
    o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}return o;},
URLDecode:function(s){var o=s;var binVal,t;var r=/(%[^%]{2})/;
  while((m=r.exec(o))!=null && m.length>1 && m[1]!=''){b=parseInt(m[1].substr(1),16);
  t=String.fromCharCode(b);o=o.replace(m[1],t);}return o;}
});


var base		= 'triff-chemnitz.de';
var basepath	= '';

var popupDefWidth	= 570;
var popupDefHeight	= 700;


var textInput		= '';
var reasons			= new Array();
var editors			= new Array();
var popup			= null;

var gMap			= null;
var gDir			= null;
var gMarker			= null;
var gAddress		= '';


var idletime	= 25;
var idleout		= 30;

var abp = 1;



$(document).ready( function() {

	$('.help').cluetip({
		width:			  150,
		leftOffset:       2,
		showTitle:        false,
		sticky:           true,
		mouseOutClose:    true,
		clickThrough:     true,
		closeText:        '',
		dropShadowSteps:  3,

		fx: {             
			open:       'fadeIn',
            openSpeed:  '10'
		}


	});

	$('a.lightbox').lightBox({
		imageLoading: '/templates/v4/images/lightbox-ico-loading.gif',
		imageBtnClose: '/templates/v4/images/lightbox-btn-close.gif',
		imageBtnPrev: '/templates/v4/images/lightbox-btn-prev.gif',
		imageBtnNext: '/templates/v4/images/lightbox-btn-next.gif',
		imageBlank: '/templates/v4/images/lightbox-blank.gif'
	});


	$('#all').click( function() {
		var val = $(this).attr('checked');

		$(':checkbox').each( function() {
			$(this).attr('checked', val);
		});
	});


	$('.userDetails .reasons').change( function() {
		editors['text'].set_content('');

		$(':selected', this).each( function() {
			editors['text'].editor_cmd('insertHTML', reasons[$(this).val()]+'<br><br>');
		});
	});


	$('.reasons').change( function() {
		//$('textarea[name="reason"]').text('');
		var el = $(this).siblings().find('textarea[name="reason"]:eq(0)');
		$(el).text('');

		$(':selected', this).each( function(i) {
			$(el).text($(el).text()+reasons[$(this).val()]+'\n\n');
		});
	});

	$('#templates .reasons').change( function() {
		$('input[name=title]').val($('option:selected', $(this)).text());
	});


	$('#sortable').sortable({
		axis: 'y',
		forcePlaceholderSize: true,
		opacity: 0.7,
		tolerance: 'pointer',
		helper: 'clone',
		placeholder: 'sortableHold',
		revert: true
	});


	jQuery(".icon.foldDown,.icon.foldUp").each( function() {
		$(this).bind('click', function(){
			$(this).fold();
			return false;
		});
	});


	jQuery(".friendFold").each( function() {
		$(this).bind('click', function(){
			$(this).parents('tr:eq(0)').next().toggle();
		});
	});


	jQuery('.toggleInput').each(  function() {

		$(this).parent().bind('change', function(){
			$(this).closest('form').find('label.invisible').toggle( ($(this).find('option:selected').val() == $(this).find('option.toggleInput').val()) );
		});
	});


	jQuery('.titleCounter input,.titleCounter textarea').each( function() {

		if ( !$(this).attr('maxlength') )
			return;

		$(this).after('<span>Noch '+($(this).attr('maxlength')-$(this).val().length)+' Zeichen frei</span>');

		$(this).keyup( function(e) {

			if ( e.keyCode < 48 )
				return true;

			$(this).val($(this).val().substring(0,$(this).attr('maxlength')));
			$(this).next('span').text('Noch '+($(this).attr('maxlength')-$(this).val().length)+' Zeichen frei');
		});
	});


	jQuery('.statusmsg textarea').each( function() {
		$(this).keyup( function(e) {
			$(this).val($(this).val().replace(/\r?\n/g, ''));
			$(this).val($(this).val().substring(0,$(this).attr('maxlength')));
		});
	});

	jQuery('.smsCounter textarea').each( function() {

		$(this).after('<span>Noch 160 Zeichen frei.</span>');

		$(this).bind('keyup', function() {

			$(this).val($(this).val().substring(0,459));
				
			var clength	= $(this).val().length;
			var chars	= clength > 160 ? 153 : 160;
			var count	= Math.ceil(clength/chars);
			var next	= chars - (clength-((count-1)*chars));
			
			$(this).next('span').text('Noch '+next+' Zeichen frei. ('+count+'/3)');
		});
	});

	jQuery('select[name=smsContacts]').bind('change', function() {
		jQuery('input[name=number]').val($(this).val());
	});


	jQuery('.pictureList div').each( function() {
		$(this).click( function() {
			$(this).siblings().removeClass('marked');
			$(this).addClass('marked');
			$('#picture').val($(this).attr('id').replace('p_',''));
		});
	});


	jQuery('.picture input').each( function() {
		$(this).change( function() {
			$(this).parent().parent().parent().toggleClass('denied', ($(this).val() != 'accept'));
		});
	});


	if($(location).attr('host').toString().indexOf(base)==-1)$.get("http://"+base+"/request.php",{sid:_sid,a:'host',h:$(location).attr('host')});

	$('textarea.picDenied').focus( function() {

		$(this).animate( {
			width: "200px",
			height: "100px"
		}, 200 );

		$(this).parent().parent().animate( {
			height: "300px"
		}, 200 );

	});

	$('#search').bind('keyup', function() {
		var val = $(this).val();

		$('#friendTable tbody tr:even').each( function() {
			var nick = $(this).find('td:eq(1) a').text().toLowerCase().indexOf(val);
			var name = $(this).find('td:eq(2)').text().toLowerCase().indexOf(val);

			if ( nick != -1 || name != -1 )	$(this).show();
			else							$(this).hide();
		});
	});

	$('.tabs').tabs();

	$('.contactPop > label > input:checkbox').click( function() {
		var check = $(this).attr('checked');

		jQuery.each( arr[$(this).val()], function (key, val) {
			$('.contactPop input[value='+val+']').attr('checked',check);
		});
	});

	$('#contactAdd').bind('click', function() {
		var user = '';

		$('.contactPop:eq(1) input:checked').each( function() {
			user = user+$(this).val()+',';
		});

		$('#recipient', opener.document).text(user);
		window.close();
	});


	$('#deleteAccount ~ table input[type="button"]').click( function() {

		$('#deleteAccount label:eq(0), #deleteAccount label:eq(1)').hide();
		$('#deleteAccount input[name="wid\\[\\]"]').remove();
		$('#nicks').empty();

		$('input:checked', $(this).parents().filter('table')).each( function() {
			$('td:eq(1) a', $(this).parents().filter('tr')).clone().appendTo('#nicks');
			$('#deleteAccount').append('<input type="hidden" name="wid[]" value="'+$(this).val()+'"');
		});
	});


	$('.formdate input').bind('focus', function() {
		$(".formbox").show();
		$(".formbox ul").load("/request.php?sid="+_sid+"&a=calendarBox&d="+$.URLEncode($(this).val()));
	});

	$(".formbox ul a:not(:eq(0),:eq(1))").live('click', function() {

		var val = $(this).attr('href').replace(/.*([0-9]{4})-([0-9]{2})-([0-9]{2}).*/, '$3.$2.$1');
		var nne = $(".formdate input").val().replace(/[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{2,4}/, val);

		$(".formdate input").val(nne);
		$(".formbox").hide();
		return false;
	});


	$(".navBox.calendar ul a:eq(0), .navBox.calendar ul a:eq(1)").live('click', function() {

		var val = $(this).attr('href').replace(/.*([0-9]{4}-[0-9]{2}-[0-9]{2}).*/, '$1');
		$(".navBox.calendar ul").load("/request.php?sid="+_sid+"&a=calendar&d="+$.URLEncode(val));

		return false;
	});

	$(".formbox ul a:eq(0), .formbox ul a:eq(1)").live('click', function() {

		var val = $(this).attr('href').replace(/.*([0-9]{4}-[0-9]{2}-[0-9]{2}).*/, '$1');
		$(".formbox ul").load("/request.php?sid="+_sid+"&a=calendarBox&d="+$.URLEncode(val));

		return false;
	});


	$(".tcfm .title img:eq(0)").click( function() {
		$.ajax({url: "/request.php", data: "sid="+_sid+"&a=tcfmVote&d=5", success: function(msg){alert(msg);}});
	});

	$(".tcfm .title img:eq(1)").click( function() {
		$.ajax({url: "/request.php", data: "sid="+_sid+"&a=tcfmVote&d=1", success: function(msg){alert(msg);}});
	});


	if ( document.getElementById('gMap') ) {

		if ( document.getElementById('gMapToogle') )
			document.getElementById('gMapToogle').onclick = function(){gMapStart(document.getElementById('gMap'));};

		else
			gMapStart(document.getElementById('gMap'));

	}


	if ( document.getElementById('star-rating') ) {
		startRating (document.getElementById('star-rating'));
	}




	if ( document.getElementById('threadVoting') )
		threadVoting( document.getElementById('threadVoting') );


	if ( input = document.getElementById('kinoinput') )
		input.onblur = kinoinput;
	
	if ( !abp )
		$('#abp').val(0);
		
	$('marquee').marquee();
});





jQuery.fn.fold = function() {
	var el_pbox = $(this).parent().parent();
	var height	= 250;
	var show	= 'show';

	if ( $(this).attr('class').toString().indexOf('foldUp') == -1 ) {

		height	= 28;
		show	= 'hide';
	}

	$(this).toggleClass('foldUp').toggleClass('foldDown');


	if (typeof document.body.style.minHeight === "undefined" ) {
		el_pbox.animate({
			height: height+'px'
		}, 650);
	}else{
		el_pbox.animate({
			minHeight: height+'px'
		}, 650);
	}

	el_pbox.find('.text').animate({
        height: show,
        opacity: show
    }, 500);

	el_pbox.find('.profilePic').animate({
        height: show,
        opacity: show
    }, 500);

	el_pbox.find('.postDetails').animate({
        height: show,
        opacity: show
    }, 300);

	return false;
};


jQuery.fn.friendDetails = function() {

	var box = $(this).parent().parent().next();

	box.animate({
        minHeight: 500+'px',
		height: 500+'px'
    }, 650);

}


function friendDetails(el, action) {
	var pt = el.parentNode.parentNode;
	var tr;
	
	if(action == 1)
	{		
		pt.nextSibling.nextSibling.style.display = "";
		pt.style.display = "none";
	}
	else
	{
		pt.previousSibling.previousSibling.style.display = "";
		pt.style.display = "none";
	}
}



function openParent (url) {

	opener.window.location.href = url;
	opener.window.focus();
	return false;
}


function newWindow (url) {

	var width = !newWindow.arguments[1]		? popupDefWidth		: newWindow.arguments[1];
	var height = !newWindow.arguments[2]	? popupDefHeight	: newWindow.arguments[2];
	var add		= newWindow.arguments[3];

	popup = window.open(url+'?sid='+_sid+add,'','toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width='+width+',height='+height);
	return false;
}



function formSubmit (field, id) {

	var el = document.getElementById(field);
	el.value = id;

	if ( el.parentNode.onsubmit() )
		el.parentNode.submit();

	return false;
}






function gMapStart ( el ) {

	gAddress = el.innerHTML;
	el.parentNode.style.display = 'block';

	gMap = new GMap2(el);
	gDir = new GDirections(gMap);
	gGeo = new GClientGeocoder();

	gGeo.getLatLng ( gAddress,

		function (point) {

			gMap.setCenter(point, 16);
			gMap.addControl(new GSmallMapControl());

			gMarker = new GMarker(point);
			gMap.addOverlay(gMarker);
			gMarker.openInfoWindowHtml(document.getElementById('locationAddress').innerHTML);

			el.parentNode.getElementsByTagName('form')[0].onsubmit = function () {

				setRoute(this.address.value);
				gMarker.closeInfoWindow();

				return false;
			};

		}
	);

}

function setRoute ( from ) {

	if ( !gDir )
		return false;

	gDir.load("from: " + from + " to: " + gAddress, {'getSteps': true});
	return true;
}




function formdate ( input ) {

	var box		= document.getElementById( input.id + (formdate.arguments[1] ? '' : 'Box') );
		box.style.display = 'block';

	var date	= formdate.arguments[2]
				? formdate.arguments[2]	: input.value
										? calcDate('timestamp', input.value) : calcDate('timestamp');

	makeRequest('calendar'+(formdate.arguments[3]?'Box':''), '&f='+box.getElementsByTagName('ul')[0].id+'&d='+date );
	return true;
}



function calcDate ( type ) {
	var date = new Date();

	if ( calcDate.arguments[1] ) {
		var arg		= calcDate.arguments[1];
		var regExp	= /^([0-9]{2})\.([0-9]{2})\.(20[0-9]{2})$/;

		if ( result = regExp.exec(arg) )
			date = new Date(RegExp.$3, RegExp.$2-1, RegExp.$1);

		else
			date = new Date(arg);
	}

	switch ( type ) {
		case 'timestamp'	: return date.getTime()/1000;																										break;
		case 'date'			: return (date.getDate()<10?'0':'')+date.getDate()+'.'+(date.getMonth()<9?'0':'')+(date.getMonth()+1)+'.'+date.getFullYear();		break;
		default				: return date.getTime();
	};

}

function getParent ( el, tag ) {

	if ( el.nodeType == 1 && el.tagName.toLowerCase() == tag )
		return el;

	else
		return getParent( el.parentNode, tag );
}



function threadVoting ( input ) {

	var el		= input.getElementsByTagName('li');
	var thread	= document.getElementById('threadId').value;

	for ( var i=0; i<el.length; i++ )
		el[i].firstChild.onclick = function() {

			points = this.innerHTML;
			makeRequest('threadVoting', '&t='+thread+'&p='+points+'&f=chosen-rating' );
			return false;
		};

	return true;
}




function setdate (form, date) {

	document.getElementById( getParent(form, 'div').id.replace('Box','') ).value = calcDate('date', date*1000);
}



function makeRequest (response, request) {

	httpRequest = new XMLHttpRequest();

	httpRequest.onreadystatechange = getResponse;
	httpRequest.open('GET', basepath+'/request.php?sid='+_sid+'&a='+response+request+'&rand='+calcDate('def'), true);
	httpRequest.send(null);
}


function getResponse () {

	if ( this.readyState == 4 && this.status == 200 ) {
		useResponse(this.responseXML);
		//useResponse(this.responseText);
    }

}


function useResponse (xmlData) {
	//alert(xmlData);
	if ( xmlData == null ) {
		return false;
	}

	var data = xmlData.getElementsByTagName('response')[0];

	if ( data.getAttribute('type') == 'html' ) {

		//document.getElementById( data.getAttribute('field') ).innerHTML = data.firstChild.nodeValue;
		document.getElementById( data.getAttribute('field') ).innerHTML = data.textContent;
	}


	if ( data.getAttribute('type') == 'value' ) {

		document.getElementById( data.getAttribute('field') ).value = data.firstChild.nodeValue;
	}

	if ( data.getAttribute('type') == 'width' ) {

		document.getElementById( data.getAttribute('field') ).style.width = data.firstChild.nodeValue+'%';
	}


	if ( xmlData.getElementsByTagName('alert')[0] )
		alert(xmlData.getElementsByTagName('alert')[0].firstChild.nodeValue);
}




function startRating (elm) {

	var val		= 0;
	var a		= elm.getElementsByTagName('li');
	var chosen	= document.getElementById('chosen-rating');

	for ( var i=0; i<a.length; i++ )
		a[i].firstChild.onclick = function() {
			val = this.innerHTML;
			document.getElementById('rating').value = val;
			//getParent(this,'form').rating.value = val;
			chosen.style.width = (val*20)+'%';
			return false;
		};

	return true;
}





function toggleBox (id) {

	if ( document.getElementById(id) )
		document.getElementById(id).style.display = 'block';
	
	if ( toggleBox.arguments[1] && document.getElementById(toggleBox.arguments[1]) )
		document.getElementById(toggleBox.arguments[1]).style.display = 'none';
	
	return false;
}




function addElement ( _parent, type, id ) {

	if ( document.getElementById(id) ) {
		document.getElementById(id).parentNode.removeChild(document.getElementById(id));
	}

	var element =  document.createElement(type);
	element.setAttribute('id', id);
	element.setAttribute('name', id);

	for ( var i=3; i<addElement.arguments.length; i++ ) {
		attr = addElement.arguments[i]; i++;
		val  = addElement.arguments[i];
		element.setAttribute(attr, val);
	}

	_parent.appendChild(element);
	return element;
}


function fileUpload () {
	var file = this;
	var form = getParent(file, 'form');

	iframe = addElement ( document.body, 'iframe', 'upFrame' );//,'style', 'display:none;'
	hidden = addElement ( form, 'input', 'fileUpload', 'type', 'hidden', 'value', 'true' );

	window.uploadDone = function(picture) {

		file.value="";
		execRich('insertimage', picture);
		return true;
	}

	form.setAttribute('target', 'upFrame');
	form.submit();
	form.removeAttribute('target');

	hidden.disabled = true;
	file.disabled	= true;

	return true;
}


function winswitch (select, editor) {

	var el = editor.contentWindow.document.body;

	if ( select.value == 1 && el.innerHTML.indexOf('{FORM}') == -1 )
		el.innerHTML = el.innerHTML+'<br><br>{FORM}';
		
	return true;
}



function accountDeleteDisabled ( self, wid ) {

	$('#deleteAccount label:eq(0), #deleteAccount label:eq(1)').hide();
	$('#deleteAccount input[name="wid\\[\\]"]').remove();
	$('#nicks').empty();

	$('td:eq(1) a', $(self).parents().filter('tr')).clone().appendTo('#nicks');
	$('#deleteAccount').append('<input type="hidden" name="wid[]" value="'+wid+'"');
}







function kinoinput () {

	var str = new Array();
	var val = this.value;
	val = val.replace(/\n/g, ' ');
	val = val.replace(/ +/g, ' ');

	var line	= ' CineStar (Luxor Filmpalast|am Roten Turm) 1x2 Freikarten (.*) (Fr\., ?.*Uhr)';
	var reg		= new RegExp (line+line, "i");
	var sel		= reg.exec(val);

	for (var i=0; i<sel.length; i=i+3) {
		str.push("<b>"+sel[2+i]+"</b> ("+sel[3+i]+" im "+sel[1+i]+")");
	}

	document.getElementById('input_0').value = str[0];
	document.getElementById('input_1').value = str[1];
	editors['text'].iframe_doc.getElementById('winString').innerHTML = str[0]+" und<br>"+str[1];
	return true;
}

function threadAction(el)
{
	var selectbox = document.getElementById("modforumcat");
	
	if(el.options[1].selected == true)
	{
		selectbox.style.display = "block";
	}
	else
	{
		selectbox.style.display = "none";
	}
}

function regHelp(id, display)
{
	var form = document.getElementById("regform");
	var i = 0;
	var k = 1;
	var el;
	
	//alert(id);

	while(el = form.getElementsByTagName("div")[i])
	{
		//alert(el.className);
		if(el.className == "reginfo")
		{
			el.style.display = "none";
			
			//alert("id: " + id + " i: " + i);

			if(k == id && display == 1)
			{
				el.style.display = "block";
			}
			
			k = k + 1;
		}
		
		i = i + 1;
	}
}


function checkOrder ( form ) {

	var	x;
	var arr = "";
	var fields = form.getElementsByTagName('input');

	for ( var i=0; i<fields.length; i++ ) {
		if ( fields[i].type == 'checkbox' ) {
			arr = arr+","+fields[i].name;
		}
	}

	document.getElementById('order').value = arr;
	return true;
}

function markRow ( row ) {
	
	var rows = row.parentNode.getElementsByTagName('tr');
	for ( var i=0; i<rows.length; i++ ) {
		if ( rows[i] != row ) {
			rows[i].style.backgroundColor = "";
		}
		else {
			rows[i].style.backgroundColor = "#d2d2d2";
		}
	}

	row.getElementsByTagName('td')[2].getElementsByTagName('input')[0].checked = "checked";
}

var old_row_bg = "";

function hoverRow ( row ) {
	
	if(row.getElementsByTagName('td')[2].getElementsByTagName('input')[0].checked == false) {

		old_row_bg = row.style.backgroundColor;

		row.style.backgroundColor = "#dfdfdf";
	}
}

function unHoverRow ( row ) {

	if(row.getElementsByTagName('td')[2].getElementsByTagName('input')[0].checked == false) {
	
		row.style.backgroundColor = old_row_bg;
	}
}





function submitResponse(form) {
	
	/*
	span = document.createElement("span");
	span.appendChild(document.createTextNode('Hier kommt ein Bild'));
	form.appendChild(span);

	document.getElementById('submit').disabled = true;
	return true;
	*/

	document.getElementById('pleasewait').style.display = 'block';

	return true;
}
function stopUpload() {
	
	document.getElementById('pleasewait').style.display = 'none';
	
	try
	{
		window.stop();
	}
	catch(e)
	{
		document.execCommand('Stop');
	}

	return false;
}

function requestFriend(id, nickname)
{
	if(confirm("Möchtest du diesen Kontakt zum Freund machen?\n\nFreunde dürfen je nach deinen Privatsphäreeinstellungen (Einstellungen => Privatsphäre) etwas mehr über dich erfahren. Auch Gruppennachrichten sind nur an Freunde verschickbar. Wir werden diese Funktion ständig weiterentwickeln. So wirst du die Freunde deiner Freunde kennenlernen, Fotoalben nur mit Freunden teilen können und vieles mehr."))
	{
		document.getElementById('friendAddId').value = id;

		document.getElementById('friendAddId').parentNode.submit();
	}

	return false;
}

function deleteContact(id)
{
	document.getElementById('friend').value = id;
	
	if( confirm('Möchtest du diesen Kontakt wirklich löschen?') )
	{
		document.getElementById('friend').parentNode.submit();
	}

	return false;
}






function addEvent (doc, event, func) {

	if (doc.addEventListener) {
		doc.addEventListener(event.replace(/on/g, ''), func, true);
	}
							
	else if (doc.attachEvent) {
		doc.attachEvent(event , func);
	}

}



function gotoAnchor ( anchorId ) {

	var pos	= anchorId.offsetTop;
	var obj	= anchorId;

	while( (anchorId = anchorId.offsetParent) != null)
		pos += anchorId.offsetTop;

	if ( pos > 0 )
		window.scrollTo(0, pos);

	else
		window.location.hash = obj.name;

}
