(function($){


var _ni = new function ()
{
	this.fAjaxBack = function(data)
	{
		var a = data.split("\n");
		var c = parseInt(a[0]);
		a = a.slice(1);

		$('#control').html('');

		switch (c) {
			case 0:
				var index = a[0].indexOf(" ");
				var id  = a[0].substr(0, index);
				var val = a[0].substr(index+1);
				$('#event_location').val(val);
				$('#eventLocation_id').val(id);
				_ni.fFormHide();
				_ni.fResult();
				break;
			case 1:
				var ul = $('<ul class="error">');
				for(i = 0; i<a.length; i++) {
					$(ul).append($('<li>').text(a[i]));
				}
				$('#control').html($(ul));
				break;
			case 2:
				var ul = $('<ul class="info">');
				for(i = 0; i<a.length; i++) {
					var index = a[i].indexOf(" ");
					var id   = a[i].substr(0, index);
					var val  = a[i].substr(index+1);
					if (id > 0) {
						var li = $('<li>')
									.text(val)
									.attr('rel', a[i])
									.click(function(){
										var s     = new String($(this).attr('rel'));
										var index = s.indexOf(" ");
										var id    = s.substr(0, index);
										var val   = s.substr(index+1);

										$('#eventLocation_id').val(id);
										$('#event_location').val(val);
										_ni.fResult()
									})
								;
						$(ul).append($(li));
					}
				}
				var force = $('<input>')
								.attr({type: 'button', value: 'Meine Location ist nicht dabei - ich möchte eine neue Vorschlagen'})
								.css({cursor:'pointer'})
								.mouseover(function(){$(this).css();})
								.mouseout (function(){$(this).css();})
								.click(function(){
										$('#event_location').flushCache();
										$.post(
											'/termine/location_insert.ajax.php',
											{
												eventLocation_name  : $('#eventLocation_name')  .val(),
												eventLocation_street: $('#eventLocation_street').val(),
												eventLocation_number: $('#eventLocation_number').val(),
												eventLocation_city  : $('#eventLocation_city')  .val(),
												eventLocation_code  : $('#eventLocation_code')  .val(),
												eventLocation_phone : $('#eventLocation_phone') .val(),
												eventLocation_uri   : $('#eventLocation_uri')   .val(),
												force               : '1'
											},
											_ni.fAjaxBack
										);
								})
							;

				$('#control')
					.append('<div class="info">Meintest Du vielleicht: </div>')
					.append($(ul))
					.append($(force))
				;
				break;
		}
	}
	this.fReset = function()
	{
		$('#eventLocation_id').val('');
		$('#event_location_info span').text('');
		$('#event_location_info').hide();
		$('#event_location').val('').show().focus();
		$('#insert_location_button').show();
	}

	this.fFormHide = function()
	{
		var e = $('#insert_location_form');
		$(e).find('.form-element, .form-submit').fadeTo(300, 0, function(){
			$(e).hide(300);
			$('#insert_location_button').val('+'+$('#insert_location_button').val().substr(1));
		});
		$('#control').html('');
		return false;
	}
	this.fResult = function () {
		$('#event_location, #insert_location_button').hide();
		$('#event_location_info span').text($('#event_location').val());
		$('#event_location_info').show();
		if ( $('#insert_location_form').css('display') == 'block' ) {
			_ni.fFormHide();
		}
	}
	this.fSubmitEvent = function ()
	{
		if (! ($('#eventLocation_id').val() > 0) && $('#insert_location_form').css('display') == 'block')  {
			$('#submit-location').click();
		}
		else {
			$('#formEvent').submit();
		}
	}
	this.fGalleryInsert = function (id)
	{
		var s = $('#gallery_hidden').val();
		var a = (s == "")? new Array() : s.split(',');
		for(i=0; i<a.length; i++) {
			if (id === a[i]) {
				alert('Diese Galerie ist bereits verknüpft');
				return;
			}
		}
		$('#gallery_items_empty').hide('slow');


		a[a.length] = id;
		$('#gallery_hidden').val(a.join(','));
		$.get('gallery_get.ajax.php', {id: id}, function(data){
            data = eval("("+data+")");
				if (data.id > 0) {

					var view = $('#view_galleryItem').html();
					for(key in data) {
						view = view.split('{'+key+'}').join(data[key]);
					}
//					$('#view_tmp').html(view);
//					$('#view_tmp div:first').hide();
//					$('#view_tmp div.delete')
//						.mouseover(function(){
//							$(this).css('background', 'red');
//						})
//						.mouseout(function(){
//							$(this).css('background', '');
//						})
//						.click(function(){
//							$(this).parent().parent().removeClass('item').hide('slow', function(){
//								if ($('#gallery_auto div.item').size() == 0) {
//									_ni.fGalleryDelete($(this).attr('rel'));
//									$('#gallery_auto').hide('slow').remove();
//								}
//							});
//						})
//					;
					//$('#view_tmp div.insert').hide();
					//$('#gallery_items').append($('#view_tmp').html());

					var tmp = $(view);
					$(tmp).filter('div:first').hide();
					$(tmp).filter('div.delete')
						.mouseover(function(){
							$(this).css('background', '#ddd');
						})
						.mouseout(function(){
							$(this).css('background', '');
						})
						.click(function(){
							$(this).parent().parent().removeClass('item').hide('slow', function(){
								if ($('#gallery_auto div.item').size() == 0) {
									_ni.fGalleryDelete($(this).attr('rel'));
									$('#gallery_auto').hide('slow');
								}
							});
						})

					$('#gallery_items').append($(tmp));





					$('#gallery_items div:last-child').show('slow');
					$('#gallery_items div:last-child div.insert').hide();
					$('#gallery_items div:last-child div.delete')
						.mouseover(function(){
							$(this).css('background', '#ddd');
						})
						.mouseout(function(){
							$(this).css('background', '');
						})
						.click(function(){
							_ni.fGalleryDelete($(this).attr('rel'));
							$(this).parent().parent().hide('slow', function(){$(this).remove()});
						})
					;


				}

		});



	}
	this.fGalleryDelete = function (id)
	{
		var s = $('#gallery_hidden').val();
		var a = (s == "")? new Array() : s.split(',');
		var b = [];
		for (i=0; i<a.length; i++) {
			if (a[i] != id) {
				b[b.length] = a[i];
			}
		}
		if (b.length > 0) {
			$('#gallery_hidden').val(b.join(','));
		}
		else {
			$('#gallery_hidden').val('');
			$('#gallery_items_empty').show('slow');
		}

	}
}

$(document).ready(function(){
	jQuery(function() {
		jQuery('.lightbox').lightBox();
	});
	$('#event_title').focus();
	$("#event_time_Ymd, #event_timeend_Ymd").datepicker({ dateFormat: 'dd.mm.yy',dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'], firstDay: '1',monthNames: ['Januar','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember']});
	$("#event_location")
		.autocomplete("location_like.ajax.php", {
			max: 12,
			highlight: false,
			scroll: true,
			scrollHeight: 300,
			formatItem: function(data, i, n, value) {
				return value.substr(value.indexOf(" ")+1);
			},
			formatResult: function(data, value) {
				return value.substr(value.indexOf(" ")+1);
			},
			matchSubset: false
		})
		.result(function(event, data, formatted) {
			var s = new String(data);
			$('#eventLocation_id').val(s.substr(0, s.indexOf(" ")));
			_ni.fResult();
		})
	;
	$('#event_location_info input').click(_ni.fReset);
	var time = [];
	for (i = 0; i <= 23; i++) {
		for (j = 0; j <= 45; j += 15) {
			time[time.length] = ((i<10)?'0'+i:i)+':'+((j<10)?'0'+j:j);
		}
	}
	$("#eventLocation_city")
		.autocomplete(
			"location_city.ajax.php",
			{
				max: 10,
				highlight: false,
				scroll: true,
				scrollHeight: 300,
				matchSubset: true
			}
		)
	;
	$("#eventLocation_street")
		.autocomplete(
			"location_street.ajax.php",
			{
				max: 10,
				highlight: false,
				scroll: true,
				scrollHeight: 300,
				matchSubset: true
			}
		)
	;

	$("#event_time_Hi, #event_timeend_Hi")
		.autocomplete(
			time,
			{
				max: 12,
				highlight: false,
				scroll: true,
				scrollHeight: 300,
				matchSubset: true
			}
		)
	;

	$('#insert_location_form .form-element, #insert_location_form .form-submit').css('opacity', '0');
	$('#insert_location_button')
		.click(function(){
			var e = $('#insert_location_form');
			if ( $(e).css('display') == 'none' ) {
				$(e).show(300, function(){
					$(e).find('.form-element, .form-submit').css({opacity: 0}).fadeTo(300, 1);
					$('#insert_location_button').val('-'+$('#insert_location_button').val().substr(1));
				});
			}
			else {
				$(e).find('.form-element, .form-submit').fadeTo(300, 0, function(){
					$(e).hide(300);
					$('#insert_location_button').val('+'+$('#insert_location_button').val().substr(1));
				});
			}
		})
	;
	$('#submit-location-cancel').click(_ni.fFormHide);
	$('#submit-location').click(function(){
		$.post(
			'/termine/location_insert.ajax.php',
			{
				eventLocation_name  : $('#eventLocation_name')  .val(),
				eventLocation_street: $('#eventLocation_street').val(),
				eventLocation_number: $('#eventLocation_number').val(),
				eventLocation_city  : $('#eventLocation_city')  .val(),
				eventLocation_code  : $('#eventLocation_code')  .val(),
				eventLocation_phone : $('#eventLocation_phone') .val(),
				eventLocation_uri   : $('#eventLocation_uri')   .val()
			},
			_ni.fAjaxBack
		);
		return false;
	});
	if ($('#eventLocation_id').val() > 0) {
		_ni.fResult();
	}
	$('#submit-event').click(_ni.fSubmitEvent);
	$('textarea.resizable:not(.processed)').TextAreaResizer();
	$('iframe.resizable:not(.processed)').TextAreaResizer();


	$('#event_keyword').change(function(){
		if ($('#event_keyword').val() != "") {
			$.get('gallery_like.ajax.php', {q: $('#event_keyword').val()}, function(data) {
                data = eval("(" + data + ")");

				$('#gallery_auto_items').html('');
				if (data.length) {

					for(i=0; i<data.length; i++) {
						var view = $('#view_galleryItem').html();
						for(key in data[i]) {
							view = view.split('{'+key+'}').join(data[i][key]);
						}
						$('#gallery_auto_items').append($(view));
					}
					$('#gallery_auto_items div.insert, #gallery_auto div.delete')
						.mouseover(function(){
							$(this).css('background', '#ddd');
						})
						.mouseout(function(){
							$(this).css('background', '');
						})
					;
					$('#gallery_auto_items div.delete')
						.click(function(){
							$(this).parent().parent().removeClass('item').hide('slow', function(){
								if ($('#gallery_auto div.item').size() == 0) {
									$('#gallery_auto').hide('slow');
								}
							});
						})
					;
					$('#gallery_auto_items div.insert')
						.click(function(){

							_ni.fGalleryInsert( $(this).attr('rel') );
							$(this).parent().parent().removeClass('item').hide('slow', function(){
								if ($('#gallery_auto div.item').size() == 0) {
									$('#gallery_auto').hide('slow');
								}
							});
						})
					;


					$('#gallery_auto').show('slow');
				}
				else {
					$('#gallery_auto').hide('slow');
				}
			});
		}
	});

	$("#gallery_input")
		.autocomplete("gallery_like.ajax.php?autocomplete=1", {
			max: 12,
			highlight: false,
			scroll: true,
			scrollHeight: 300,
			formatItem: function(data, i, n, value) {
					eval ('var x = '+value);

					var view = $('#view_galleryItem').html();
					for(key in x) {
						view = view.split('{'+key+'}').join(x[key]);
					}
					var tmp = $(view);
					$(tmp).find('div:first').hide();
					return $(tmp).html();


//					$('#view_tmp').html(view);
//					$('#view_tmp div div:first').hide();
//					view = $('#view_tmp').html();
//					$('#view_tmp').html('');

					return view;



			},
			formatResult: function(data, value) {
				eval ('var x = '+value);
				return x.id;
			},
			matchSubset: false
		})
		.result(function(event, data, formatted) {
			$('#gallery_input').val('');
			eval ('var x = '+data);
			_ni.fGalleryInsert(x.id);

		})
	;
	if ($('#gallery_hidden').val() != '') {
		var a = $('#gallery_hidden').val();
		$('#gallery_hidden').val('');
		a = a.split(',');
		for (i=0; i<a.length; i++) {
			_ni.fGalleryInsert(a[i]);
		}
	}
	$('#event_file').change(function(){
		
		var s = $('label[for=event_filedesc]').text();
		var e = s.substr(-1);
		if ($(this).val() == '') {
			if (e == '*') {
				$('label[for=event_filedesc]').text(s.substr(0, s.length -1 ));
			}
		}
		else {
			if (e != '*') {
				s += '*';
				$('label[for=event_filedesc]').text(s);
			}
		}

	});
	$('#event_file').trigger('change');
});


})(jQuery);
