(function($) { 
	$.fn.extend({
		replaceAll: function(searchString, replaceString) {
		var o = $(this);
		return o.text().split(searchString).join(replaceString);
		}
	}); 

	$.fn.focusNextInputField = function(filter) {
	    return this.each(function() {
	        var fields = $(this).parents('form:eq(0),body').find('button,input' + filter + ',textarea,select');
	        var index = fields.index( this );
	        if ( index > -1 && ( index + 1 ) < fields.length ) {
	            fields.eq( index + 1 ).focus();
	        }
	        return false;
	    });
	};

})(jQuery);  

$(document).ready(function()
{
	$('body').supersleight();
	if(jQuery().tabs)
	{
		$('#event_function_menu').tabs();
		$('#calendar_view').tabs();
	}
//	$('#event_function_weiterleiten_email').hide();
	$('#toggle_email_form').click(function(){
		$('#event_function_weiterleiten_email').toggle();
		return false;
	});
	$('#auth_login').focus();
	$('input.was').toggleValue('Was?');
	$('input.wo').toggleValue('Wo?');
	$('#mypopula_events_editor_invite_email').toggleValue('E-Mail Adresse');
	$('input.was').attr('value', '');
	$('#was').focus();
	
	var dt = new Date();
	var currentdate = dt.getFullYear() + '-' + (dt.getMonth() + 2) +'-' + dt.getDate();
	var LOCALE_GERMAN = {
			days: ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag', 'Sonntag'],
			daysShort: ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'],
			daysMin: ['S', 'M', 'D', 'M', 'D', 'F', 'S', 'S'],
			months: ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'],
			monthsShort: ['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'],
			weekMin: 'wk'
		}; 
	
	if(jQuery().DatePicker)
	{
		$('#multiple_datepicker').DatePicker({
			flat: true,
			current: currentdate,
			date: '',
			calendars: 3,
			mode: 'multiple',
			starts: 1,
			locale: LOCALE_GERMAN,
			onChange: function(dates) {
				$('#datetime_previewlist_content div').remove();
				$.each(dates, function(i, item) {
					if (item != 'NaN-NaN-NaN') {
						add_datetime_to_previewlist(item,
							$('#start_time_hour').val(),
							$('#start_time_minute').val(),
							$('#end_time_hour').val(),
							$('#end_time_minute').val(),
							false,
							true
						);
					}
				});
			}
		});
	}
	$('#location_name').autocomplete(
		BASE_PATH+'suggestlocation',
		{
			dataType: 'json',
			selectFirst: false,
			matchContains: true,
			cacheLength: 0,
			delay: 100,
			onselect: 'refreshLocation',
			statusbar: '<div class="ac_statusbar"><a href="#" class="ac_newloc">Neue Location anlegen</a> | <a href="#" class="ac_hide">Abbrechen</a></div>'
		}
	);

	if(jQuery().fcbkcomplete)
	{
		$('#keywords').fcbkcomplete({
			json_url: BASE_PATH+'suggesttag',
			json_url_tag: 'part',
			complete_text: 'Bitte auswählen',
			cache: false,
	        filter_case: false,
	        filter_hide: false,
	        filter_selected: true,
	        seperatorKeys: [188],
			newel: true,
	        onselect : 'checkkeywordscheckbox',
	        onremove : 'checkkeywordscheckbox'
		});
		
		checkkeywordscheckbox = function () {
			$('#form_edit_event input.value_checkbox[name=checkbox_keywords]').attr('checked', 'checked');
		}
		
		$('#artists').fcbkcomplete({
			json_url: BASE_PATH+'suggestinvolved',
			json_url_tag: 'part',
			complete_text: 'Bitte auswählen',
			cache: false,
	        filter_case: false,
	        filter_hide: false,
	        filter_selected: true,
	        seperatorKeys: [188],
	        newel: true,
	        onselect : 'checkartitstcheckbox',
	        onremove : 'checkartitstcheckbox'
		});
		
		checkartitstcheckbox = function () {
			$('#form_edit_event input.value_checkbox[name=checkbox_artists]').attr('checked', 'checked');
		}
	}
	$('input#wo').autocomplete(
			BASE_PATH + 'suggestcity',
			{
				dataType: 'json',
				matchContains: true,
				cacheLength: 0,
				width: 177,
				delay: 100,
				scroll: false,
				mustMatch: true,
				onselect: ''
			}
		);
	
	$('input.wo').autocomplete(
			BASE_PATH + 'suggestcity',
			{
				dataType: 'json',
				matchContains: true,
				cacheLength: 0,
				width: 177,
				delay: 100,
				scroll: false,
				mustMatch: true,
				onselect: ''
			}
		);
	
	var cityid; 
	
	$('input#stadtstart').autocomplete(
			BASE_PATH + 'suggestcity',
			{
				dataType: 'json',
				matchContains: true,
				cacheLength: 0,
				width: 177,
				delay: 100,
				scroll: false,
				mustMatch: true,
				onselect: ''				
			}
		).result(function(event, data, formatted) 
				{
					cityid = formatted;	
					$.getJSON(BASE_PATH + "suggesturlcity", { id: cityid}, function(json){
							document.stadtanzeigen.action = json.url; 
					    });     
				});	 
	
	
	
	
	$('input.stadtstart').autocomplete(
			BASE_PATH + 'suggestcity',
			{
				dataType: 'json',
				matchContains: true,
				cacheLength: 0,
				width: 177,
				delay: 100,
				scroll: false,
				mustMatch: true,
				onselect: ''
			}
		);

	checkartitstcheckbox = function () {
		$('#form_edit_event input.value_checkbox[name=checkbox_artists]').attr('checked', 'checked');
	}

	$('#calendar_view_extended .date_option_m').hide();
	$('#calendar_view_extended .date_option_w').hide();
	$('#calendar_view_extended .date_option_t').show();
	$('#date_every_type').change(function(){
		var selected = $(this).val();
		if (selected == 'Täglich'){
			$('#calendar_view_extended .date_option_m').hide();
			$('#calendar_view_extended .date_option_w').hide();
			$('#calendar_view_extended .date_option_t').show();
		}
		else if (selected == 'Wöchentlich'){
			$('#calendar_view_extended .date_option_m').hide();
			$('#calendar_view_extended .date_option_w').show();
			$('#calendar_view_extended .date_option_t').hide();
		}
		else if (selected == 'Monatlich'){
			$('#calendar_view_extended .date_option_m').show();
			$('#calendar_view_extended .date_option_w').hide();
			$('#calendar_view_extended .date_option_t').hide();
		}
		else{
			$('#date_option_m').hide();
			$('#date_option_w').hide();
			$('#date_option_t').hide();
		}
		
	});
	var currentdateGerman = (dt.getDate() < 10 ? '0':'') + dt.getDate() + '.' + ((dt.getMonth() + 1) < 10 ? '0':'') +(dt.getMonth() + 1) + '.' + dt.getFullYear() ;
	if ($('#start_date').val() == ''){
		$('#start_date').val(currentdateGerman, true );
	}
	
	if(jQuery().DatePicker)
	{
		$('#start_date').DatePicker({
			format: 'd.m.Y',
			date: currentdateGerman,
			starts: 1,
			position: 'l',
			locale: LOCALE_GERMAN,
			onChange: function(formated){
				$('#start_date').val(formated);
				$('#start_date').DatePickerHide();
			}
		});
		$('#end_date').DatePicker({
			format: 'd.m.Y',
			date: currentdateGerman,
			starts: 1,
			position: 'r',
			locale: LOCALE_GERMAN,
			onChange: function(formated){
				$('#end_date').val(formated);
				$('#end_date').DatePickerHide();
			}
		});
		$('#edit_event_date').DatePicker({
			format: 'd.m.Y',
			date: $('#edit_event_date').val(),
			starts: 1,
			position: 'r',
			locale: LOCALE_GERMAN,
			onChange: function(formated){
				$('#edit_event_date').val(formated);
				$('input[name=checkbox_date]').attr('checked', 'checked');
				$('#edit_event_date').DatePickerHide();
			}
		});
	}
	$('#add_event_datetime').click(function(){
		var start_date = $('#start_date').val();
		var end_date = $('#end_date').val();
		var date_every_type = $('#date_every_type').val();
		var date_every = $('#date_every').val();
		var date_every_weekday = $('#date_every_weekday').val();
		
		var cbxDays = [];
		$('.date_option_w .checkbox').each(function(){
			cbxDays.push($(this).is(":checked"));
		})
		showWaitingDialog('Lade...');
		$.post(BASE_PATH + 'ajaxdate',
				{
					begin: start_date,
					end: end_date,
					repeats: date_every_type,
					mo: cbxDays[0],
					di: cbxDays[1],
					mi: cbxDays[2],
					'do': cbxDays[3],
					fr: cbxDays[4],
					sa: cbxDays[5],
					so: cbxDays[6],
					everymonth: date_every,
					dayofmonth: date_every_weekday
					
				},
				function(data){
					$.each(data, function(i,item){
						if (i != 'MESSAGE'){
							add_datetime_to_previewlist(item,
									$('#start_time_hour').val(),
									$('#start_time_minute').val(),
									$('#end_time_hour').val(),
									$('#end_time_minute').val()
									);
						}
						else{
							showMessageDialog (item);
						}
								
							});
//					add_datetime_to_previewlist(aDate);
				},
				"json"
				);
		hideWaitingDialog(300);
		return false;
	});
	
	$('#datetime_previewlist_delete_all_events').click(function() {
		$('#datetime_previewlist_content div').remove();
		refresh_multiple_datepicker('multiple_datepicker');
		return false;
	});
	
	
	function add_datetime_to_previewlist(startdate, starttime_h, starttime_m, endtime_h, endtime_m, without_sort, dont_refresh) {
		if (!startdate.match(/\d{4}-\d{2}-\d{2}/)){
			return
		}
		var id = startdate.replace(/-/g, '_');
		var aTemp = startdate.split('-');
		var DateGermanFormat = aTemp[2] + '. ' + LOCALE_GERMAN.monthsShort[aTemp[1] - 1] + '. ' + aTemp[0];
		if ($('#id_' + id).length > 0) {
			return;
		}
		var newId = 'id_' + id;
		var newRow=('<div id="id_' + id + '" class="row">'
				+ '<input name="startdate[]" type="hidden" value="' + startdate + '" class="event_data"/>'
				+ '<div class="col1">' + DateGermanFormat + '</div>'
				+ '<div class="col2 start_time"><input name="starttime_hour[]" type="text" value="' + starttime_h + '" class="event_data timeinput"/> : <input name="starttime_minute[]" type="text" value="' + starttime_m + '" class="event_data timeinput" /></div>'
				+ '<div class="col3 end_time"><input name="endtime_hour[]" type="text" value="' + endtime_h + '" class="event_data timeinput" /> : <input name="endtime_minute[]" type="text" value="' + endtime_m + '" class="event_data timeinput" /></div>'
				+ '<div class="col4"><a id="delete_' + id + '"  href="#"><span class="image_close_button_big">X</span></a></div>'
				+ '</div>');
		var lastId = newId;
		var currentId = '';
		if (!without_sort){
			$('#datetime_previewlist_content .row').each(
					function(){
						currentId = $(this).attr("id");
						if ((newId >= lastId && newId < currentId) || (newId < currentId)){
							
							return false;
						}
						lastId = currentId;
					});
		}
		if (newId < currentId){
			$(newRow).insertBefore($('#'+currentId));
		}
		else if (lastId == newId){
			$('#datetime_previewlist_content').append(newRow);
			
		}
		else{
			$(newRow).insertAfter($('#'+lastId));
		}
		$('#'+newId).hide();
		$('#'+newId).show();

		$('#delete_' + id).click(function (){
			$('#' + newId).hide(200, function(){
				$('#' + newId).remove();
				refresh_multiple_datepicker('multiple_datepicker');
			});
			return false;
			});
		if (!dont_refresh){
			refresh_multiple_datepicker('multiple_datepicker');
		}
		$('#datetime_previewlist_counter span').html($('#datetime_previewlist_content div.row').length);
	}
	// refresh multiple_datepicker from datetime previewlist
	
	function refresh_multiple_datepicker(id) {
		var aDates = [];
		$('#datetime_previewlist_content .row').each( function(){
			var id = $(this).attr("id");
			var aIdPart = id.split('_');
			var date = aIdPart[1] + '-'  + aIdPart[2] + '-' + aIdPart[3];
			aDates.push(date);
		});
		
		$('#' + id).DatePickerClear();
		$('#' + id).DatePickerSetDate(aDates);
		
		$('#datetime_previewlist_counter span').html($('#datetime_previewlist_content div.row').length);
	}

	/* change main category */
	$('#category1').change(function(object) {
		$('#category_div span.image_close_button_big, dl.category_attributes').hide();
		$('select.pseudocat').hide();
		$('select.subcategory').hide();
		$('select.subcategory option').removeAttr('selected');
		subcat = $('select#ID_' + $(this).val());
		$('#category_div span.addnewcat').css({ display: ($(this).val() == 'none' ? 'none' : 'block') });
		if (!subcat.find('option').length) {
			$('#category_div span.addnewcat').css({ display: 'none' });
		} else {
			subcat.show();
		}
		$('.ID_A_' + $(this).val()).show();
	});

	/* change sub category */
	$('select.subcategory').change(function() {
		update_category_attributes();
	});

	/* add sub category */
	$('#category_div span.addnewcat a').click(function() {
		cat = $('#category1').val();
		newcat = $('#category1').clone().removeAttr('id').attr('disabled', 'disabled').addClass('pseudocat').insertBefore($(this).parent());
		newcat.find('option[value='+cat+']').attr('selected', 'selected');
		newsubcat = $('select#ID_'+cat).clone().removeAttr('id').insertBefore($(this).parent()).css('margin-top', '.5em');
		newsubcat.change(function() {
			update_category_attributes();
		});
		$('select.subcategory:visible:last').each(function() {
			$('<span class="image_close_button_big">&nbsp;&nbsp;&nbsp;&nbsp;</span>').insertAfter($(this));
		});
		return false;
	});

	/* remove sub category */
	$('#category_div span.image_close_button_big').live('click', function() {
		$(this).prev('select').remove();
		$(this).prev('select').remove();
		$(this).remove();
		update_category_attributes();
	});

	/* update visibility of category attributes */
	function update_category_attributes() {
		$('dl.category_attributes').hide();
		$('.ID_A_' + $('select#category1 option:selected').attr('value')).show();
		$('#category_div select.subcategory:visible').each(function() {
			$('.ID_'+$(this).find('option:selected').val()).show();
		});
	}
	
    var options = { 
        target:        '#output1',   // target element(s) to be updated with server response 
 
        // other available options: 
        //url:       url         // override for form's 'action' attribute 
        type:      'post',        // 'get' or 'post', override for form's 'method' attribute 
        dataType:  'json',        // 'xml', 'script', or 'json' (expected server response type) 
        clearForm: true       // clear all form fields after successful submit 
        //resetForm: true        // reset the form after successful submit 
 
        // $.ajax options can be used here too, for example: 
        //timeout:   3000 
    }; 
//    $('#form_insert_event').ajaxForm(options); 


    $('.ac_hide').live('click', function(event) {
    	event.stopPropagation();
    	$('div.ac_results').hide();
    	return false;
    });
    
    $('.ac_newloc').live('click', function(event) {
    	event.stopPropagation();
    	$('div.ac_results').hide();
    	$('.location_selected_block').hide();
		$('#location_selected').html('');
		$('#insert_location_name').attr('value', $('#location_name').attr('value'));
		$('#insert_location_box').show();
		return false;
    });

    refreshLocation = function (id) {
    	if (id && id != 1337666)
    	{
			$('#insert_location_box').hide();
    		$('.location_selected_block').show();
    		$('#location_id').attr('value', id);
    		showWaitingDialog('Lade...');
    		$.get(BASE_PATH+'ajaxlocation', { location_id: id }, function(jsondata) {
        		hideWaitingDialog(300);
    			var data = eval('('+ jsondata + ')');
    			var output = data.name
    						+ '<br/>' + data.street
    						+ '<br/>' + data.postcode + ' ' + data.city;
    			$('#location_selected').html(output);
    		});
    		$('#form_edit_event input.value_checkbox[name=checkbox_location]').attr('checked', 'checked');
    	}
    	else
    	{
    		if (jQuery.trim($('input#location_name').val()) != '' && $('#location_id').attr('value') == '')
    		{
    			if (id && id == 1337666) {
    				$('#location_name').val('');
    			}
    			$('div.ac_results').hide();
    			$('.location_selected_block').hide();
    			$('#location_selected').html('');
    			$('#insert_location_name').attr('value', $('#location_name').attr('value'));
    			$('#insert_location_box').show();
    		}
    	}
    	$('#category1').focus();
    }

    $('input#location_name').keyup(function(event) {
    	if (event.keyCode == 13 && $('#location_id').attr('value') == '') {
    		$('div.ac_results').hide();
			$('.location_selected_block').hide();
			$('#location_selected').html('');
			$('#insert_location_name').attr('value', $('#location_name').attr('value'));
			$('#insert_location_box').show();
        }
    });

    // insert location 
    $('#submit_location_data').click(function() {
    	var queryString = $('.location_data').fieldSerialize();
		//showWaitingDialog('Sende...');
		$.post( BASE_PATH +  'locationeintrag.html',
				queryString,
				function(data){
					//hideWaitingDialog(300);
					var message = '';
					var errors = {};
					$.each(data, function(i,item){
						if (i == 'id' && item != '')
						{
							refreshLocation(item);
						}
						else if (i == 'errors')
						{
							for (var j in item)
							{
								errors[j] = item[j];
								message += item[j] + '\n';
							}
							$('p.formerror').remove();
							var first = true;
							$.each(errors, function(errorName, errorString) {
								var element = $('#' + errorName);
								element.after('<p class="formerror">'+errorString+'</p>');
																
								if(first)
								{
									$('html,body').animate({scrollTop: element.offset().top-30},500);
									element.focus();
									first = false;
								}
							});
						}	
						
					});
				},
				"json"
				);
		return false;
    }); 
    
    // insert event
    $('#submit_event_data').click(function() {
    	var queryString = $('#form_insert_event .event_data').fieldSerialize();
		$.post('veranstaltungseintrag.html',
				queryString,
				function(data){
					var eventid = null;
					var message = '';
					var errors = {};
					$.each(data, function(i,item){
						//numeric value => event id => success
						if((item - 0) == item)
						{
							eventid = item;
						}
						else
						{
							errors[i] = item;
							message += item + '\n';
						}
					});
					if (message != ''){
						if(eventid)
						{
							showWaitingDialog('Veranstaltung eingetragen');
							//alert(window.location.protocol + '//' + window.location.host + BASE_PATH + 'meinpopula/veranstaltungen/' + eventid + '/detail/');
							window.location.href = window.location.protocol + '//' + window.location.host + BASE_PATH + 'meinpopula/veranstaltungen/' + eventid + '/detail/';
						}
						else
						{
							$('p.formerror').remove();
							$.each(errors, function(errorName, errorString) {
								var element = $('#' + errorName);
								element.after('<p class="formerror">'+errorString+'</p>');
																
								$('html,body').animate({scrollTop: element.offset().top-30},500);
								element.focus();
							});
							//showMessageDialog(message);
						}
					}
				},
				"json"
				);
		return false;
    }); 

    // edit event
    $('#submit_event_data_edit_top, #submit_event_data_edit_bottom').click(function() {
    	var queryString = $('#form_edit_event .event_data').fieldSerialize();
    	var url = BASE_PATH + 'meinpopula/veranstaltungen/' + $('#form_edit_event #event_id').val() + '/bearbeiten/'
    	showWaitingDialog('Sende Daten...');
		$.post(url,
				queryString,
				function(data){
					var message = '';
					var success = false;
					var errors = {};
					$.each(data, function(i,item){
						if(i == 'OK')
						{
							success = true;
						}
						errors[i] = item;
						message += item + '\n';
					});
					if(success)
					{
						showWaitingDialog('Veranstaltung(en) gespeichert...');
						if(data['link'])
						{
							window.location.href = data['link'];
						}
						else
						{
							window.history.back();
						}
					}
					else
					{
						/*
						if (message != ''){
							showMessageDialog(message);
						}*/
						$('p.formerror').remove();
						$.each(errors, function(errorName, errorString) {
							var element = $('#' + errorName);
							element.after('<p class="formerror">'+errorString+'</p>');
															
							$('html,body').animate({scrollTop: element.offset().top-30},500);
							element.focus();
						});
						hideWaitingDialog(300);
					}
				},
				"json"
				);
		return false;
    });
    $('.cancel_button').bind('click', function(){
    	history.go(-1);
    });
    
    // edit location
    $('#submit_location_data_edit_top, #submit_location_data_edit_bottom').click(function() {
    	var queryString = $('#form_edit_location .location_data').fieldSerialize();
    	var url = BASE_PATH + 'meinpopula/locations/' + $('#form_edit_location #location_id').val() + '/bearbeiten/';
    	showWaitingDialog('Sende Daten...');
		$.post(url,
				queryString,
				function(data){
					var message = '';
					var link = null;
					var errors = {};
					$.each(data, function(i,item){
						if(i == 'link')
						{
							link = item;
						}
						else
						{
							errors[i] = item;
							message += item + '\n';
						}
					});
					if (message != ''){
						$('p.formerror').remove();
						$.each(errors, function(errorName, errorString) {
							var element = $('#' + errorName);
							element.after('<p class="formerror">'+errorString+'</p>');
															
							$('html,body').animate({scrollTop: element.offset().top-30},500);
							element.focus();
						});
					}
					else if(link)
					{
						window.location.href = link;
					}
					hideWaitingDialog(300);
				},
				"json"
				);
		return false;
    }); 

    // edit user passwort
    
    $('#submit_usersettings_passwort').click(function() {
    	var queryString = $('#form_edit_usersettings .data').fieldSerialize();
    	var url = BASE_PATH + 'meinpopula/einstellungen/passwort/';
    	showWaitingDialog('Sende Daten...');
		$.post(url,
				queryString,
				function(data){
					var message = '';
					$.each(data, function(i,item){
						message += item + '\n';
					});
					if (message != ''){
						showMessageDialog(message);
					}
					hideWaitingDialog(300);
				},
				"json"
				);
		return false;
    });
    
    
    $('#submit_facebook_connect').click(function() {
    	var queryString = $('#form_edit_usersettings .data').fieldSerialize();
    	var url = BASE_PATH + 'meinpopula/einstellungen/freigabe/';
    	showWaitingDialog('Sende Daten...');
		$.post(url,
				queryString,
				function(data){
					var message = '';
					$.each(data, function(i,item){
						message += item + '\n';
					});
					if (message != ''){
						showMessageDialog(message);
					}
					hideWaitingDialog(300);
				},
				"json"
				);
		return false;
    });
    
    $('#overlay_submit_usersettings').click(function() {
    	var queryString = $('#form_edit_usersettings .data').fieldSerialize();
    	var url = BASE_PATH + 'meinpopula/einstellungen/';
    	showWaitingDialog('Sende Daten...');
		$.post(url,
				queryString,
				function(data){
					var message = '';
					$.each(data, function(i,item){
						message += item + '\n';
					});
					if (message != ''){
						showMessageDialog(message);
					}
					else
					{
						document.location.reload();
						
					}
				},
				"json"
				);
		return false;
    }); 
    
    /*
    // edit user settings
    $('#submit_usersettings').click(function() {
    	var queryString = $('#form_edit_usersettings .data').fieldSerialize();
    	var url = BASE_PATH + 'meinpopula/einstellungen/';
    	showWaitingDialog('Sende Daten...');
		$.post(url,
				queryString,
				function(data){
					var message = '';
					$.each(data, function(i,item){
						message += item + '\n';
					});
					if (message != ''){
						showMessageDialog(message);
					}
					hideWaitingDialog(300);
				},
				"json"
				);
		return false;
    }); 
    */
	$('#form_insert_event input').keypress(function (e) {  
		if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
			$('button[type=submit] .default').click();  
			return false;  
		}
		else {  
			return true;  
		}  
	});

	$('#insert_location_box').hide();

	/* simulare link click on input (search results) */
	$srchkboxz = $('#search_result_content_left .box_filter input:checkbox, #searchresult_attributes input');
	$srchkboxz.live('click', function() {
		$srchkboxz.attr('disabled', 'disabled');
		window.location = $(this).next('a').attr('href');
	});

	/* display toogle of empty categories */
	$('#search_result_content_left .box_filter a.showallcats').click(function() {
		if ($(this).hasClass('shown')) {
			$(this).removeClass('shown');
			$(this).html('alle anzeigen');
			$(this).prevAll('span.emptysubcat').hide();
		} else {
			$(this).addClass('shown');
			$(this).html('leere verstecken');
			$(this).prevAll('span.emptysubcat').css('display', 'block');
		}
	});

	if(jQuery().DatePicker)
	{
		$('#search_result_content_left #searchfilterfrom').DatePicker({
			format: 'Y-m-d',
			date: $('#searchfilterfrom').attr('title'),
			locale: LOCALE_GERMAN,
			onChange: function(formated) {
				var $todate = $('input#searchfilterto');
				var todate = $todate.attr('title').split('-').join('');
				var fromdate = formated.split('-').join('');
				if ($todate.val() != '' && fromdate > todate) {
					showMessageDialog('Das Startdatum kann nicht nach dem Enddatum liegen.');
				} else {
					$('div.datepicker').hide();
					var newurl = SEARCH_URL.replace(/(\?|&)df=([^Z]+)Z/g, '');
					newurl += (newurl.indexOf('?') != -1) ?  '&' : '?';
					window.location = newurl + 'df=' + formated + 'T00:00:00Z';
				}
			}
		});
	
		$('#search_result_content_left #searchfilterto').DatePicker({
			format: 'Y-m-d',
			date: $('#searchfilterto').attr('title'),
			locale: LOCALE_GERMAN,
			onChange: function(formated) {
				var $fromdate = $('input#searchfilterfrom');
				var fromdate = $fromdate.attr('title').split('-').join('');
				var todate = formated.split('-').join('');
				if ($fromdate.val() != '' && todate < fromdate) {
					showMessageDialog('Das Enddatum kann nicht vor dem Startdatum liegen.');
				} else {
					$('div.datepicker').hide();
					var newurl = SEARCH_URL.replace(/(\?|&)du=([^Z]+)Z/g, '');
					newurl += (newurl.indexOf('?') != -1) ?  '&' : '?';
					window.location = newurl + 'du=' + formated + 'T23:59:59Z';
				}
			}
		});
	}
	$('#searchresult_list select[name=sort]').change(function() {
		if($(this).val() == 'none') {
			return false;
		}
		url = window.location.href.replace(/(\?|&)sort=[a-z_]+/i, '');
		window.location = url + (url.indexOf('?') == '-1' ? '?' : '&') + 'sort=' + $(this).val();
	});
	
	$('#distancebox select').change(function() {
		if (window.location.href.indexOf('distance=') == '-1') {
			window.location = (window.location.href.indexOf('?') == '-1') ? window.location.href + '?distance=' + $(this).val() : window.location = window.location.href + '&distance=' + $(this).val();
		} else {
			url = window.location.href.replace(/(\?|&)distance=([0-9]+)/i, '');
			window.location = (url.indexOf('?') == '-1') ? url + '?distance=' + $(this).val() : url + '&distance=' + $(this).val();
		}
	});

	$('textarea#brief_description').keypress(function(event) { updateTextaraLimit($(this)); }).keydown(function(event) { updateTextaraLimit($(this)); }).keyup(function(event) { updateTextaraLimit($(this)); });
	function updateTextaraLimit(jObject) {
		var maxLength = 100; 
		var length = jObject.val().length;
		var infoSpan = $('#'+jObject.attr('id')+'_info span');
		if (length >= maxLength) {
			jObject.val(jObject.val().substring(0, maxLength));
		}
		if (length <= maxLength) {
			infoSpan.html(maxLength - length);
		}
		if (length > (maxLength * 0.8)) {
			infoSpan.css({ color : '#5C0002' });
		}
		if (length > (maxLength * 0.9)) {
			infoSpan.css({ color : '#D40D12' });
		}
	}

	$('.timeinput').keyup(function(event) {
		if ($(this).val().length >= 2){
			$(this).focusNextInputField('.timeinput');
		}
	});
	
	
    $('#event_img_upload_button').click(function() {
		showWaitingDialog('Sende Bild...');
    	$.ajaxFileUpload({
			url: BASE_PATH + 'ajaximageupload',
			secureuri:false,
			fileElementId:'event_img_upload',
			dataType: 'json',
			success: function (data, status)
			{
				hideWaitingDialog(300);
                if(typeof(data.error) != 'undefined')
                {
                    if(data.error != '')
                    {
                        showMessageDialog(data.error);
                    }
                }
                if(typeof(data.filepath) != 'undefined')
                {
                	$('#event_img').attr('value', data.filepath);
                	$('#event_image_preview').attr('src', data.image_url);
                	$('#delete_event_image_preview').show();
                	$('#event_img_upload_label').text('Das Bild wurde erfolgreich hochgeladen!').fadeIn(500, function(){
                		setTimeout("$('#event_img_upload_label').fadeOut(3000);", 2000);
	                	});
	                
                }
                $('#form_edit_event input[name=checkbox_event_img_upload_button]').attr('checked', true);

            },
            error: function (data, status, e)
            {
        		hideWaitingDialog(300);
                showMessageDialog(e);
            }
        });
    });

    $('#location_img_upload_button').click(function() {
		showWaitingDialog('Sende Bild...');
		$.ajaxFileUpload(
    			{
        			url: BASE_PATH + 'ajaximageupload',
        			secureuri:false,
        			fileElementId:'location_img_upload',
        			dataType: 'json',
        			success: function (data, status)
        			{
    				hideWaitingDialog(300);
	                if(typeof(data.error) != 'undefined')
	                {
	                    if(data.error != '')
	                    {
	                        showMessageDialog(data.error);
	                    }
	                }
	                if(typeof(data.filepath) != 'undefined')
	                {
	                	$('#location_img').attr('value', data.filepath);
	                	$('#location_image_preview').attr('src', data.image_url);
	                	$('#delete_location_image_preview').show();
	                	$('#location_img_upload_label').text('Das Bild wurde erfolgreich hochgeladen!').fadeIn(500, function(){
	                		setTimeout("$('#location_img_upload_label').fadeOut(3000);", 2000);
	                		});
	                	}
	                },
	                error: function (data, status, e)
	                {
	                	hideWaitingDialog(300);
	                	showMessageDialog(e);
	                	}
	                });
		});

    $('#delete_event_image_preview').hide();
    $('#delete_event_image_preview').click(function(){
    	$('#event_image_preview').attr('src', standardImageUrl);
    	$('#event_img_upload').attr('value', '');
    	$('#event_img').attr('value', '');
    	$('#delete_event_image_preview').hide();
    	
    	return false;
    });
    
    $('#delete_location_image_preview').hide();
    $('#delete_location_image_preview').click(function(){
    	$('#location_image_preview').attr('src', standardImageUrl);
    	$('#location_img_upload').attr('value', '');
    	$('#location_img').attr('value', '');
    	$('#delete_location_image_preview').hide();
    	return false;
    });


    var standardImageUrl = $('#starndard_image_path').attr('value');

    $('input[type=text], textarea, select').focus(function() {
    	$('div.ttitem').hide();
    });
    
    /* custom tooltips (keywords, artists) */
    $('#fcbk_keywords').focus(function() {
    	$('div#tt_keywords').css({top : $(this).offset().top - 34, left : $('#main').offset().left + 650}).show();
    });
    $('#fcbk_artists').focus(function() {
    	$('div#tt_artists').css({top : $(this).offset().top - 34, left : $('#main').offset().left + 650}).show();
    });

	initTooltipPosition = function(){
		$('.tooltip').each(function() {
			// erst nach dem hide() methode auf alle Elemente verwenden, sonst wird die Hoehe 
			// falsch berechnet
			var divTooltip = '#tt_' + this.id;
			$(divTooltip).hide();
			$(divTooltip).css('position', 'absolute');
//			$(divTooltip).css('top', $(this).offset().top - 34);
//			$(divTooltip).css('left', $('#main').offset().left  + 650);
			$(divTooltip).css('width', 263);
			$(divTooltip).css('border', '#339900 1px solid');
			$(divTooltip).css('background-color', '#e2ffe4');
			$(divTooltip).css('padding', '14px 25px 14px 20px');
			$(this).bind(
					'focus',
					function() {
						divTooltip = '#tt_' + this.id;
						$(divTooltip).css('top', $(this).offset().top - 34);
						$(divTooltip).css('left', $('#main').offset().left  + 650);
						$(divTooltip).show();
					}
			);
		});
	}
	initTooltipPosition();
	
	refreshTooltipPosition = function(){
		$('.tooltip').each(function(){
			// erst nach dem hide() methode auf alle Elemente verwenden, sonst wird die Hoehe 
			// falsch berechnet
			var divTooltip = '#tt_' + this.id;
			$(divTooltip).css('top', $(this).offset().top - 34);
			$(divTooltip).css('left', $('#main').offset().left  + 650);
		});
	}
	
	$(window).resize(function(){
		refreshTooltipPosition();
	});	

	
	
	$('#page_1').show();
	
	
	
	$('.pagelink_div a').click(function(){
		var id = $(this).attr('class');
		if (!id){
			return true;
		}
		$('.pagelink_div div.page').each(function(){
			$(this).hide();
		});
		$('#' + id).show();
		return false;
	});
	
	$('.pagelink_div1').css('background', 'none');
		
	$('.topicbox #page_10').show();
	$('#topic .picborder img').show();
	
	
	$('.pagelink_div1 a').click(function(){
		var id = $(this).attr('class');
		if (!id){
			return true;
		}
		$('.topicbox div.page').each(function(){
			$(this).hide();
		});
		$('.topicbox #' + id).show();
		$('.topicbox #' + id +' img').show();
		return false;
	});
	
	$('#mainpage_top_left_current div.box_content').css('background', 'none');
	$('.pagelink #page_1').show();
	
	$('.pagelink_div a').click(function(){
		var id = $(this).attr('class');
		if (!id){
			return true;
		}
		$('.pagelink div.page').each(function(){
			$(this).hide();
		});
		$('#' + id).show();
		return false;
	});
	
	$('.pagelink_div2').css('background', 'none');
	$('.cols #page_1').show();
	
	$('.pagelink_div2 a').click(function(){
		var id = $(this).attr('class');
		if (!id){
			return true;
		}
		$('.cols div.page').each(function(){
			$(this).hide();
		});
		$('.cols #' + id).show();
		return false;
	});
	
	


//	// gmap is loaded?
	/*if (typeof GMap2 != 'undefined'){
		var jMapIcon = new Mapifies.createIcon({
			'iconImage': BASE_PATH + 'media/image/frontend/gmaps_icon_20_34.png'
		});
	}
	$('#gmapsuche').jmap('init', {
		mapCenter: [$('#gmap_lat').text(), $('#gmap_lon').text()]
	});
	//$('#gmapsuche').jmap('AddMarker', {
		pointLatLng: [$('#gmap_lat').text(), $('#gmap_lon').text()],
		pointHTML: $('#gmap_address').html()
	});
	*/
    /*
    
    
    $('#myevents_form li.col2 a.cond2').each(function(i, item){
    	var newValue = $(this).replaceAll(' ', '_');
    	if ($('#my_popula_content_right #myevents #myevents_filter #title [value=' +   newValue   + ']').text() == ''){
    		var current = $('#my_popula_content_right #myevents #myevents_filter #title').html();
    		$('#my_popula_content_right #myevents #myevents_filter #title').html(current + '<option value="' + newValue + '">' + $(this).text() + '</option>');
    	}
    	
    });
    $('#myevents_form li.col2 span').each(function(i, item){
    	var newValue = $(this).replaceAll(' ', '_');
    	if ($('#my_popula_content_right #myevents #myevents_filter #subtitle [value=' +   newValue   + ']').text() == ''){
    		var current = $('#my_popula_content_right #myevents #myevents_filter #subtitle').html();
    		$('#my_popula_content_right #myevents #myevents_filter #subtitle').html(current + '<option value="' + newValue + '">' + $(this).text() + '</option>');
    	}
    	
    });
    $('#myevents_form li.col3 span').each(function(i, item){
    	var newValue = $(this).replaceAll(' ', '_');
    	if ($('#my_popula_content_right #myevents #myevents_filter #location [value=' +   newValue   + ']').text() == ''){
    		var current = $('#my_popula_content_right #myevents #myevents_filter #location').html();
    		$('#my_popula_content_right #myevents #myevents_filter #location').html(current + '<option value="' + newValue + '">' + $(this).text() + '</option>');
    	}
    	
    });
    
    $('#my_popula_content_right #myevents #myevents_filter select[name=condition2]').hide();
    $('#my_popula_content_right #myevents #myevents_filter select[id=title]').show();
    */
    $('#my_popula_content_right #myevents #myevents_filter #condition1').change(function(){
    	$('#my_popula_content_right #myevents #myevents_filter select[name=condition2]').hide();
    	if ($(this).attr('value') !='none'){
    		$('#' + $(this).attr('value')).show();
    	}
    	else {
    		$('#title').show();
    	}
    });
    
    $('#my_popula_content_right #myevents #myevents_filter select[name=condition2]').change(function(i){
    	var id = $(this).attr('id');
    	var value = $('#my_popula_content_right #myevents #myevents_filter select[id=' + id + '] option:selected').val();
    	var filtertype = $('#my_popula_content_right #myevents #myevents_filter select[id=condition1] option:selected').val();
    	window.location.href = window.location.protocol + '//' + window.location.host + BASE_PATH + 'meinpopula/veranstaltungen/?type='+filtertype + '&filter=' + value;
    	/*
    	$('#mypopula_events_select_all').attr('checked', false);
    	$('#myevents_form ul li.col1 input[type=checkbox]').attr('checked', false);
    	if (text == ''){
    		$('#myevents_form ul').show();
    	}
    	else if(id == 'title'){
    		$('#myevents_form li.col2 a.cond2').each(function(){
				$(this).parent().parent().hide();
    			if ($(this).text() == text){
    				$(this).parent().parent().show();
    			}
    		});
    	}
    	else if(id == 'location'){
    		$('#myevents_form li.col3 span').each(function(){
				$(this).parent().parent().hide();
    			if ($(this).text() == text){
    				$(this).parent().parent().show();
    			}
    		});
    	}
    	*/
    });
    
    
    $('#myevents_form li.col1 input[type=checkbox]').click(function(){
    	if (!$(this).attr('checked')){
    		$('#mypopula_events_select_all').attr('checked', false);
    	}    	
    });
    
    $('#mypopula_events_select_all').click(function(){
    	if ($(this).attr('checked')){
        	$('#myevents_form ul li.col1 input[type=checkbox]:visible').each(function(){
        		$(this).attr('checked', true);
        	})
    	}
    	else{
        	$('#myevents_form ul li.col1 input[type=checkbox]:visible').each(function(){
        		$(this).attr('checked', false);
        	})
    	}
    });
    
    $('#mypopula_events_edit_selected').click(function(){
    	var ids = '';
    	$('#myevents_form ul li.col1 input[type=checkbox]:visible').each(function(){
    		if ($(this).attr('checked')){
    			ids += $(this).parent().parent().attr('id') + '_';
    		}
    	});
    	if (ids.length > 0){
    		ids = ids.substring(0, ids.length -1);
    	}
    	window.location = window.location.protocol + '//' + window.location.host + BASE_PATH + 'meinpopula/veranstaltungen/' + ids + '/bearbeiten/';
    	return false;
    });
    
    $('#mypopula_events_delete_selected').click(function(){
    	if(confirm('Sollen diese Veranstaltungen wirklich gelöscht werden?'))
    	{
	    	var ids = '';
	    	$('#myevents_form ul li.col1 input[type=checkbox]:visible').each(function(){
	    		if ($(this).attr('checked')){
	    			ids += $(this).parent().parent().attr('id') + '_';
	    		}
	    	});
	    	if (ids.length > 0){
	    		ids = ids.substring(0, ids.length -1);
	    	}
	    	window.location = window.location.protocol + '//' + window.location.host + BASE_PATH + 'meinpopula/veranstaltungen/' + ids + '/loeschen/';
    	}
    	
    	return false;
    });

    $('.myevents_delete_event').click(function(){
    	if(confirm('Die Veranstaltungsdaten werden unwiderruflich entfernt.\n\nSoll diese Veranstaltung wirklich gelöscht werden?'))
    	{
    		return true;
    	}
    	return false;
    });

	$('#reload_musicevents').click(function(){
		showWaitingDialog('Lade...');
		$.post(
				BASE_PATH + "ajaxeventsmusic",
				{},
				function(data){
					$('#musicevents').html(data);
				}
				);
		hideWaitingDialog(300);
		return false;
	});

	$('#reload_sportevents').click(function(){
		showWaitingDialog('Lade...');
		$.post(
				BASE_PATH + "ajaxeventssports",
				{},
				function(data){
					$('#sportevents').html(data);
				}
				);
		hideWaitingDialog(300);
		return false;
	});
	$('#reload_artevents').click(function(){
		showWaitingDialog('Lade...');
		$.post(
				BASE_PATH + "ajaxeventsart",
				{},
				function(data){
					$('#artevents').html(data);
				}
				);
		hideWaitingDialog(300);
		return false;
	});
	$('#reload_societyevents').click(function(){
		showWaitingDialog('Lade...');
		$.post(
				BASE_PATH + "ajaxeventssociety",
				{},
				function(data){
					$('#societyevents').html(data);
				}
				);
		hideWaitingDialog(300);
		return false;
	});
	$('#reload_webtechevents').click(function(){
		showWaitingDialog('Lade...');
		$.post(
				BASE_PATH + "ajaxeventswebtech",
				{},
				function(data){
					$('#webtechevents').html(data);
				}
				);
		hideWaitingDialog(300);
		return false;
	});

	$('#reload_eventsofdistance').click(function(){
		showWaitingDialog('Lade...');
		$.post(
				BASE_PATH + "ajaxeventsofdistance",
				{
					lat: $('#gmap_lat').text(),
					lon: $('#gmap_lon').text()
				},
				function(data){
					$('#eventsofdistance').html(data);
				}
				);
		hideWaitingDialog(300);
		return false;
	});
	
    
    $("#waiting").center({vertical: false, centerTo: 'main', zIndex: 9999});
    var disabledInputs = new Array();
    showWaitingDialog = function(message){
        $('#waiting_div').text(message);
        $('#waiting').hide();
        $("#waiting").center({vertical: false, centerTo: 'main', zIndex: 9999});
        $('input[type=button], input[type=text]').each(function(){
        	if (!$(this).attr('disabled'))
        	{
        		$(this).attr('disabled', true);
        		disabledInputs.push($(this));
        	}
        	
        });
        $('#waiting').show();
    }
    hideWaitingDialog = function(delay){
    	for (i= 0; i < disabledInputs.length; i++)
    	{
    		disabledInputs[i].attr('disabled', false);
    	}
    	setInterval("closeWaitingDialog();", delay);
    }
    closeWaitingDialog = function(){
    	$('#waiting').fadeOut(1000);
    }

    $('#msgdialog').hide();
    
    showMessageDialog = function(message, titletext){
    	alert(message); return;
    	
    	if (! titletext){
    		titletext = 'Meldung';
    	}
    	$('#msgdialog').text(message);
    	$('#msgdialog').dialog({
    		title: titletext,
    		bgiframe: false,
    		resizable: false,
			width: 400,
			minHeight: 150,
			modal: false,
			close: function(event, ui) { 
				$(this).dialog('destroy');
			},
			overlay: {
				backgroundColor: '#ff0000',
				opacity: 0.8
			},
			buttons: {
				'Ok': function(){
					$(this).dialog('close');
				}
			}
    	});
    }

    $('#form_edit_event').find('input[name=title], input[name=subtitle], textarea[name=description], textarea[name=brief_description], textarea[name=video_url]').keypress(function() {
    	$('#form_edit_event input.value_checkbox[name=checkbox_'+$(this).attr('name')+']').attr('checked', 'checked');
    });

    $('#form_edit_event').find('input[name=ticket], input[name=ticket_info]').keypress(function() {
    	$('#form_edit_event input.value_checkbox[name=checkbox_ticket]').attr('checked', 'checked');
    });
    $('#form_edit_event input[name*=_time_]').keypress(function() {
    	$('#form_edit_event input.value_checkbox[name=checkbox_time]').attr('checked', 'checked');
    });    
    $('#form_edit_event').find('select.category, span.addnewcat a').click(function() {
    	$('#form_edit_event input.value_checkbox[name=checkbox_category]').attr('checked', 'checked');
    });

    $('#mypopula_events_editors_delete').click(function(){
    	$('#delete_editors').click();
    	return false;
    });
    $('#mypopula_events_set_owner').click(function(){
    	$('#set_owner').click();
    	return false;
    });

    $('#mypopula_locations_editors_delete').click(function(){
    	$('#location_delete_editors').click();
    	return false;
    });
    $('#mypopula_locations_set_owner').click(function(){
    	$('#location_set_owner').click();
    	return false;
    });

    if (!$('body#searchresults').length && !$('body#editevent').length) {
    	$('.datepickerGoPrev').slice(1,3).text('');
    	$('.datepickerGoNext').slice(0,2).text('');
    }
    
    $('ul.rating li a').click(function() {
    	var voteUrl = $(this).attr('href');	
    	$(this).parent().parent().addClass('active');
    	var ratingElement = $(this).parent().parent();
		
    	if(voteUrl.length > 0) {
			$.ajax({
				url: voteUrl,
				type: 'POST',
				success: function(avgVote) {
					ratingElement.removeClass('halfstar');
					ratingElement.removeClass('onestar');
					ratingElement.removeClass('onehalfstar');
					ratingElement.removeClass('twostar');
					ratingElement.removeClass('twohalfstar');
					ratingElement.removeClass('threestar');
					ratingElement.removeClass('threehalfstar');
					ratingElement.removeClass('fourstar');
					ratingElement.removeClass('fourhalfstar');
					ratingElement.removeClass('fivestar');
					
					if( avgVote < 1) {
						ratingElement.addClass( 'halfstar' );
					} else if( avgVote < 1.5) {
						ratingElement.addClass( 'onestar' );
					} else if( avgVote < 2) {
						ratingElement.addClass( 'onehalfstar' );
					} else if( avgVote < 2.5) {
						ratingElement.addClass( 'twostar' );
					} else if( avgVote < 3) {
						ratingElement.addClass( 'twohalfstar' );
					} else if( avgVote < 3.5) {
						ratingElement.addClass( 'threestar' );
					} else if( avgVote < 4) {
						ratingElement.addClass( 'threehalfstar' );
					} else if( avgVote < 4.5) {
						ratingElement.addClass( 'fourstar' );
					} else if( avgVote >= 5) {
						ratingElement.addClass( 'fivestar' );
					} else {
						ratingElement.addClass( '' );
					}
					
					if (avgVote == 'toofast'){
						ratingElement.parent().find('.votesncomments').fadeOut(250, function() {
							$(this).html('Du hast bereits eine Bewertung abgegeben!');
							$(this).fadeIn(600);
						});
					}else{
						ratingElement.parent().find('.votesncomments').fadeOut(250, function() {
							$(this).html('Vielen Dank für deine Bewertung!');
							$(this).fadeIn(600);
						});
					}
					ratingElement.removeClass('active');
				},
				error : function(request, textStatus, errorThrown) {
					ratingElement.parent().find('.votesncomments').fadeOut(250, function() {
						$(this).html('Du hast bereits eine Bewertung abgegeben!');
						$(this).fadeIn(600);
					});
				}
			});
		}
		return false;
	});

	$('.showcommentform a').click(function() {
		$('.newcomment').show();
		$(this).fadeOut(400);
		return false;
	});

	$('.newcomment form input[name=title]').toggleValue('Titel');
	$('.newcomment form textarea').toggleValue('Kommentar ...');
	$("input[name=twitterpublic]").attr("disabled", true); 
	$("input[name=facebookpublic]").attr("disabled", true);

	$("#eventCommenttextarea").keydown(function() {
		if($("#eventCommenttextarea").val() != "Kommentar ...")
		{
			$("input[name=twitterpublic]").attr("disabled", false); 
			$("input[name=facebookpublic]").attr("disabled", false);
		}
	}); 

	$('.newcomment form input[type=submit]').click(function() {
		$form = $(this).parent('form');
		$postname = $form.find('#postby');
		$postmail = $form.find('#postmail');
		$posthomepage = $form.find('#posthomepage');
		$facebook = $form.find('#facebookname');
		$facebooklink = $facebook.find('a').attr('href');
		$facebookname = $facebook.find('a').html();

		$twitterpublicheck = $('.newcomment').find("input[name=twitterpublic]").is(':checked');
		$facebookpublicheck = $('.newcomment').find("input[name=facebookpublic]").is(':checked');
		if($twitterpublicheck){
			$url = $('input[name=widget_url]').val();
			$twitter = 'http://twitter.com/home?status=';
			$title = $('#event_detail h1:first-child').html();
			$text = 'meine Meinung zu '+$title+' auf ' +$url;
			window.open($twitter+$text,"Zweitfenster", "width=640,height=480,scrollbars=yes");
		
		}
		
		$("input[name=twitterpublic]").attr("disabled", "disabled"); 
		$("input[name=facebookpublic]").attr("disabled", "disabled");
		
		var $comment = $form.find('textarea');
		
		comment_url = $form.attr('action');
		$('#postmailerror').html('');
		$('#postbyerror').html('');
		
		if ($postname.val() == '') {
			$('#postbyerror').html('Bitte gib deinen Namen an!');
			return false;
		}
		if ($postmail.val() == '') {
			$('#postmailerror').html('Bitte gib deine Email-Adresse an!');
			return false;
		}
		if ($comment.val() == 'Kommentar ...') {
			alert('Bitte gib einen Kommentartext an!');
			return false;
		}
		
		
		function ifConnected()
	    {
			eventname = $("#eventName").val(); 
		    eventurl = $("#eventUrl").val();
		    eventimg = $("#eventImg").val();
		    eventdate = $("#eventDate").val();
		    eventaddr = $("#eventAddr").val(); 
		    eventcity = $("#eventCity").val();
		    eventpostcode = $("#eventPostcode").val();
		    eventlocation = $("#eventLocation").val();
			
		    if(eventname == "undefined") {eventname = ""}
		    if(eventurl == "undefined") {eventurl = ""}
		    if(eventimg == "undefined") {eventimg = ""}
		    if(eventdate == "undefined") {eventdate = ""}
		    if(eventaddr == "undefined") {eventaddr = ""}
		    if(eventcity == "undefined") {eventcity = ""}
		    if(eventpostcode == "undefined") {eventpostcode = ""}
		    if(eventlocation == "undefined") {eventlocation = ""}
		    
		    
		    var description = eventname + " " +eventlocation+ " " +eventaddr+ " " +eventpostcode+ " " +eventcity; 
		    
		    var action_link; 
		    
	    	var attachment = { 	'name': eventname, 
				'href': eventurl, 
				'description': description, 
				'media': [{ 'type': 'image', 'src': eventurl, 'href': eventurl}] }; 
	    	
	    	FB.Connect.streamPublish($comment.val(), attachment, action_link);
	    }

	    function notConnected()
	    {
	    	//  
	    }

	   
		$.ajax({
			url: comment_url,
			type: 'POST',
			data: ({ text : $comment.val(),postby: $postname.val(), postmail: $postmail.val(), postmail: $postmail.val(), posthomepage: $posthomepage.val(), facebookname: $facebookname,facebooklink: $facebooklink }),
			success: function(data) {
				if (data != 'error' && data != 'emailerror') {
					//$('div#comments div.newcomment').remove();
					$(data).insertBefore('div#comments div.newcomment');
					$comment.val('');
					$postname.val('');
					$postmail.val('');
					$posthomepage.val('');
					$('#postmailerror').html('');
					$('#postbyerror').html('');
				} else {
					if (data == 'emailerror')
					{
						$('#postmailerror').html('Email-Adresse wurde vom System nicht angenommen.');
						return false;
					}
					if (data == 'email')
					{
						alert('Email-Adresse wurde im System gefunden bitte melden Sie sich an.');
						return false;
					}
					alert('Ein unbekannter Fehler ist aufgetreten!');
				}
			},
			error : function(request, textStatus, errorThrown) {
				alert('Ein unbekannter Fehler ist aufgetreten!');
			}
		});
		
		if($facebookpublicheck)
		{
			FB.Connect.ifUserConnected(ifConnected, notConnected);
		}
		return false;
	});
	
	
    $('#event_functions').show();
   
    $('#event_function_favoritErinnerung #user_favorite').click(function(){
    	var userchecked = $('#event_function_favoritErinnerung #user_favorite').attr('checked');
    	var eventid = $('#event_function_favoritErinnerung #user_remind_eventid').val();
    	var userid = $('#event_function_favoritErinnerung #user_remind_userid').val();
    	showWaitingDialog('Lade...');
    	
		$.get(BASE_PATH + 'ajaxuserfavorite', {checked: userchecked, event_id: eventid, user_id: userid}, function(jsondata) {
			if (!userchecked){
				$('#event_function_favoritErinnerung #user_remind_time').val(0);
			}
			var data = eval('('+ jsondata + ')');
			if (data.message){
				showWaitingDialog(data.message);
				hideWaitingDialog(4000);
			}
		});
    });
    
    $('#event_function_favoritErinnerung #user_favorite_location').click(function(){
    	var userchecked = $('#event_function_favoritErinnerung #user_favorite_location').attr('checked');
    	var locationid = $('#event_function_favoritErinnerung #user_favorite_locationid').val();
    	var userid = $('#event_function_favoritErinnerung #user_favorite_userid').val();
    	showWaitingDialog('Lade...');
    	
		$.get(BASE_PATH + 'ajaxuserfavoritelocation', {checked: userchecked, location_id: locationid, user_id: userid}, function(jsondata) {
			var data = eval('('+ jsondata + ')');
			if (data.message){
				showWaitingDialog(data.message);
				hideWaitingDialog(4000);
			}
		});
    });

    $("#weitereThemenShow").click(function () { 
    	$("#weitereThemen").hide();
    	$("#weitereThemenAll").show();
      });

    $('#event_function_favoritErinnerung #user_remind_time').change(function(){
    	var remindtime = $('#event_function_favoritErinnerung #user_remind_time option:selected').val();
    	var eventid = $('#event_function_favoritErinnerung #user_remind_eventid').val();
    	var userid = $('#event_function_favoritErinnerung #user_remind_userid').val();
    	showWaitingDialog('Lade...');
    	
		$.get(BASE_PATH + 'ajaxuserremind', {remind: remindtime, event_id: eventid, user_id: userid}, function(jsondata) {
			if (remindtime != '0'){
				$('#event_function_favoritErinnerung #user_favorite').attr('checked', true);
			}
			var data = eval('('+ jsondata + ')');
			if (data.message){
				showWaitingDialog(data.message);
				hideWaitingDialog(4000);
			}
		});
    });


    $('#userfavorite_remind_overlay #user_remind_time').change(function(){
    	var remindtime = $('#userfavorite_remind_overlay #user_remind_time option:selected').val();
    	var eventid = $('#userfavorite_remind_overlay #user_remind_eventid').val();
    	var userid = $('#userfavorite_remind_overlay #user_remind_userid').val();
    	showWaitingDialog('Lade...');
    	
		$.get(BASE_PATH + 'ajaxuserremind', {remind: remindtime, event_id: eventid, user_id: userid}, function(jsondata) {
			window.location.reload();
		});
    });

    $('.userfavorite_remind_button').click(function(){
    	var userFavoriteIds = $(this).attr('href');
    	var ids = userFavoriteIds.split('_'); 
    	showUserfavoriteRemindDialog(ids[0], ids[1], ids[2], ids[3], ids[4]);
    	return false;
    });
//	$('<div id="userfavorite_remind_overlay"><div class="overlay"></div><div class="overlay_div"><div class="overlay_div_box_top">Erinnerungsfunktion</div><div class="overlay_div_box_top_close"><a href=""><div class="delete">x</div></a></div><div class="overlay_div_box_content"><p>Lass dich per E-Mail an "Veranstaltungsname" erinnern.</p></div></div></div>')
    
    showUserfavoriteRemindDialog = function(eventId, userId, selectedIndex, eventTitle, vvk){
    	$('#userfavorite_remind_overlay #user_remind_eventid').val(eventId);
    	$('#userfavorite_remind_overlay #user_remind_userid').val(userId);
    	$('#userfavorite_remind_overlay #user_remind_event_title').text(eventTitle);
    	var notadded = $('#userfavorite_remind_overlay #user_remind_time option:last').val() != '-1';
    	if(vvk == 1)
    	{
			if (notadded) {
	    		$('<option value="-1">zum Vorverkauf</option>').appendTo('#userfavorite_remind_overlay #user_remind_time');
			}
    	}
		else
		{
			if (!notadded) {
				$('#userfavorite_remind_overlay #user_remind_time option:last').remove();
			}
		}
    	$('#userfavorite_remind_overlay #user_remind_time').val(selectedIndex);
    	
    	
    	$('#userfavorite_remind_overlay').show();
//    	$('<div id="userfavorite_remind_overlay"><div class="overlay"></div><div class="overlay_div"><div class="overlay_div_box_top">Erinnerungsfunktion</div><div class="overlay_div_box_top_close"><a href=""><div class="delete">x</div></a></div><div class="overlay_div_box_content"><p>Lass dich per E-Mail an "Veranstaltungsname" erinnern.</p></div></div></div>')
//    	.appendTo('body').show();
    };
    
//    $('#userfavorite_remind_overlay .overlay_div_box_top_close').click(function(){
//    	$('#userfavorite_remind_overlay').css('display', 'none');
//    	return false;
//    });
    $('#searchresult_query_save, #searchresult_query_subscribe').click(function(){
    	$('#searchresult_subscribe_overlay').show();
    	return false;
    });

    $(document).keyup(function(event){
        if (event.keyCode == 27) {
            $('.overlay_div_box_top_close').parents('div:eq(1)').css('display', 'none');
        }
    });

    $('#div.overlay_div_box_top').focus(function(){alert($('#main').offset().top)});

//    $('.overlay_div').css('position', 'absolute');

    $('.overlay_div_box_top_close').click(function(){
    	$(this).parents('div:eq(1)').hide();
    	return false;
    });

    $('.usersearches_subscribe_button').click(function(){
    	var usersearchtitle = $(this).attr('title');
    	var usersearchdata = $(this).attr('href');
    	var data = usersearchdata.split('_'); 
    	showUsersearchesDialog(data[0], data[1], data[2], usersearchtitle);
    	return false;
    });
//	$('<div id="userfavorite_remind_overlay"><div class="overlay"></div><div class="overlay_div"><div class="overlay_div_box_top">Erinnerungsfunktion</div><div class="overlay_div_box_top_close"><a href=""><div class="delete">x</div></a></div><div class="overlay_div_box_content"><p>Lass dich per E-Mail an "Veranstaltungsname" erinnern.</p></div></div></div>')
    

    showUsersearchesDialog = function(Id, userId, selectedIndex, title){
    	$('#searchresult_subscribe_overlay #email_subscribe_id').val(Id);
    	$('#searchresult_subscribe_overlay #email_subscribe_userid').val(userId);
    	$('#searchresult_subscribe_overlay #email_subscribe_title').val(title);
    	$('#searchresult_subscribe_overlay #email_subscribe_interval').val(selectedIndex);
    	
    	$('#searchresult_subscribe_overlay').show();
    };
    $('#form_widget_counter dl dd input, #form_widget_counter dl dd select').change(function(){
    	refreshWidgetCounter();
    });
    var widget_width = ($('#widget_width').val() !="" ? $('#widget_width').val() : "355");    
    var widget_bgcolor1 = ($('#widget_bgcolor1').val() !="" ? $('#widget_bgcolor1').val() : "106699");
    var widget_bgcolor2 = ($('#widget_bgcolor2').val() !="" ? $('#widget_bgcolor2').val() : "104C72");
    var widget_color1 = ($('#widget_color1').val() !="" ? $('#widget_color1').val() : "FFFFFF");
    var widget_color2 = ($('#widget_color2').val() !="" ? $('#widget_color2').val() : "C1D2DA");
    var widget_font = $('#widget_font').val();
    var widget_arrow = ($('#widget_arrow').val() !="" ? $('#widget_arrow').val() : "top");
    refreshWidgetCounter = function(){
    	var code = '<object type="application/x-shockwave-flash" data="http://static.popula.de/widget/CountdownWidget.swf" '
    			+ 'width="' + $('#widget_width').val() // width
    			+ '" height="138" name="populaWidget"><param name="flashvars" value="'
    			+ '&name=' + $('#widget_event_title').val()
    			+ '&time=' + $('#widget_event_time').val()
    			+ '&loc=' + $('#widget_event_location_name').val()
    			+ '&city=' + $('#widget_event_city_name').val()
    			+ '&ints=85'
    			+ '&img=' + $('#widget_event_image_url').val()
    			+ '&url=' + $('#widget_url').val() // url //http%3A%2F%2Fpopu.la%2F0l0n
    			+ '&colbg1=' + $('#widget_bgcolor1').val() // bg1 //106699
    			+ '&colbg2=' + $('#widget_bgcolor2').val() // bg2 //104C72
    			+ '&coltext1=' + $('#widget_color1').val() // coltext1 //FFFFFF
    			+ '&coltext2=' + $('#widget_color2').val() // coltext2 //C1D2DA
    			+ '&font=' + $('#widget_font').val() // font //Arial
    			+ '&arrow=' + $('#widget_arrow').val() // arrow //top
    			+ '&"/><param name="movie" value="http://static.popula.de/widget/CountdownWidget.swf"/><param name="quality" value="best" /><param name="scale" value="noscale" /><param name="wmode" value="transparent" /><param name="align" value="middle" /><param name="allowScriptAccess" value="sameDomain" /></object>';
    	$('#widget_code').val(code);
    	$('#widget_counter_preview').val(code);
    	$('#counter_widget_object').html(code);
    };
    //refreshWidgetCounter();
    $('#widget_reset').click(function(){
        $('#widget_width').val(widget_width);
        $('#widget_bgcolor1').val(widget_bgcolor1);
        $('#widget_bgcolor2').val(widget_bgcolor2);
        $('#widget_color1').val(widget_color1);
        $('#widget_color2').val(widget_color2);
        $('#widget_font').val(widget_font);
        $('#widget_arrow').val(widget_arrow);
    	refreshWidgetCounter();
    	return false;
    });
    
    $("#loadWidget").click(function(){
    	refreshWidgetCounter();
    }); 
    
    $('#widget_code').focus(function(){
    	$(this).select();
    });
    $('#widget_code').click(function(){
    	$(this).select();
    });
    
    $('#weiterleiten_email_reset').click(function(){
    	$('#weiterleiten_email_reset_button').click();
    	$('#event_function_weiterleiten_email').hide();
    	return false;
    });

    // St�dteauswahl 
    // -------------------------------
    
    //$("#staedteauswahl").hide();
    //$(".staedteauswahlliste").hide();
    //$("#staedteauswahlliste_1").show();
    //$(".staedteauswahlliste").show();
    
    
    
    $("#staedteauswahl #staedteanzeigen").click(function() {    	
    	$("#staedteauswahlliste_1").show();
    	void(0); 
    	return false; 
    });
        
    $("#staedteauswahlliste_1 #schliessen a").click(function() {
    	$("#staedteauswahlliste_1").hide();
    	$("#staedteauswahl").show();
    }); 
    
    (jQuery().corner) ? $(".rounded").corner("6px") : '';

    // Ajax Comment load 
    // -------------------------------
    eventId 	= $("#ajaxGetEventComments").attr("class");
    locationId	= $("#ajaxGetLocationComments").attr("class");
    
    if(eventId)
    {
	    $("#ajaxGetEventComments").load(BASE_PATH + 'ajaxgetcomments?eventid='+eventId, function(data){
	    	// Callback
	    	//console.log(data);
	    });
    }
    
    if(locationId)
    {
	    $("#ajaxGetLocationComments").load(BASE_PATH + 'ajaxgetcomments?locationid='+locationId, function(data){
	    	// Callback 
	    	//console.log(data);
	    }); 
    }
}); 

$(window).load(function() {
	if(jQuery().liquidCanvas)
    {
	    if($('#Topic_boxcolor_1').val() !='' && $('#Topic_boxcolor_1').val() !=undefined && $('#Topic_tanz').val() == 1  ){
			var eventbox = $('#Topic_eventbox_1').val();
			var box = $('#Topic_boxcolor_1').val();
			$('.topic_weitere').css('background', "#"+eventbox);
			//$('.topic_weitere').liquidCanvas("[ fill{color:#"+eventbox+"}] => roundedRect{radius:6;}");
			$('.topic_title_1').css('background', "#"+eventbox);
			//$('.topic_title_1').liquidCanvas("[ fill{color:#"+eventbox+"}] => roundedRect{radius:6;}");
			$('#search_result_content_right').css('background', "#"+eventbox);
			//$('#search_result_content_right').liquidCanvas("[ fill{color:#"+eventbox+"}] => roundedRect{radius:6;}");
			$('.topic_text').css('background', "#"+eventbox);
			//$('.topic_text').liquidCanvas("[ fill{color:#"+eventbox+"}] => roundedRect{radius:6;}");
			$('.contend_ .left').css('background', "#"+box);
			//$('.contend_ .left').liquidCanvas("[ fill{color:#"+box+"} ] => roundedRect{radius:6;}");
			$('.topic_location').css('background', "#"+eventbox);
			//$('.topic_location').liquidCanvas("[ fill{color:#"+eventbox+"}] => roundedRect{radius:6;}");
	
		}
		
	    $('.overlay_div_box_top').liquidCanvas("[ fill{color:#6c8baa}] => rect");
	    $('.overlay_div_box_content').liquidCanvas("[ border{width:1; color:#cccccc;} fill{color:#fff} ] => rect");
	    
	    
	    //$('#waiting_div').liquidCanvas("[border{width: 1; color:#FFF1A8} fill{color:#FFF1A8}] => roundedRect{radius:6; topLeft: false; topRight: false}");
	    $('#insert_event_box div.box_top').liquidCanvas("[ fill{color:#6c8baa}] => rect");
	    $('#insert_location_box div.box_top').liquidCanvas("[ fill{color:#6c8baa}] => rect");
	    $('#my_popula_content_right .box_top').liquidCanvas("[ fill{color:#6c8baa}] => rect");
	    //$('#search_result_content_right .box_top').liquidCanvas("[ fill{color:#6c8baa}] => roundedRect{radius:6; bottomLeft: false; bottomRight: false}");
	    //$('#search_result_content_left .box_searchfilter, #search_result_content_left .box_glossarycontent').liquidCanvas("[ fill{color:#fafafa} border{width:1; color:#e1e1e1;}] => roundedRect{radius:6;}");
	    //$('#my_popula_overview_box .premium_link').liquidCanvas("[ fill{color:#f0f0f0} border{width:1; color:#BBB;}] => roundedRect{radius:6;}");
	    $('#my_popula_content_right #myevents .rights .box, #my_popula_content_right .mylocation_rights .box').liquidCanvas("[ border{width:1; color:#cccccc;}] => rect");
	    $('#breed_crumb.support_info').liquidCanvas("[border{width: 1; color:#f3f3c0} fill{color:#ffffcc}] => rect");
	    //$('#contact .gray_box').liquidCanvas("[ fill{color:#f0f0f0}] => roundedRect{radius:6;}");
	    //$('.overlay_div_box_top').liquidCanvas("[ fill{color:#6c8baa}] => roundedRect{radius:6; bottomLeft: false; bottomRight: false}");
	    //$('.overlay_div_box_content').liquidCanvas("[ border{width:1; color:#cccccc;} fill{color:#fff} ] => roundedRect{radius:6; topLeft: false; topRight: false}");
	    $('#myevents_filter').liquidCanvas("[ fill{color:#f0f0f0}] => rect");
	    $('#my_popula_content_right div.event_header').liquidCanvas("[ fill{color:#f0f0f0}] => rect");
	    $('#my_popula_overview_box li:first').liquidCanvas("[fill{color:#F9F9F9}] => rect");
	    $('#myhome #my_popula_overview_box li:first').liquidCanvas("[fill{color:#666}] => rect");
	//     $('.left').liquidCanvas("[ border{width:1; color:#000000;} fill{color:#000000}] => roundedRect{radius:5;}");
	   
	    
		
	   // $('.search_result_list_box .top').liquidCanvas("[ fill{color:#FFFFFF} border{width:1; color:#D8D8DB;} ] => roundedRect{radius:6; bottomLeft: false; bottomRight: false}");
	   // $('.search_result_list_box .bottom').liquidCanvas("[ fill{color:#FFFFFF} border{width:1; color:#D8D8DB;}] => roundedRect{radius:6; topLeft: false; topRight: false}");
    } 
}); 
