function trackDL(href, grp)
{
	// Track group
	location.href = 'http://www.etracker.de/lnkcnt.php?et=DBVGuE&url=' + escape(href) + '&lnkname=' + grp;

	// Track single file:
	filename = href.replace(/^.*[\/\\]/g, '');
	ET_Event.download(filename, grp);

	return false;
}


function getZindex() {
	var dateNow = new Date();
	var zIndex = 1000+(Math.round((dateNow-datePageLoad) / 1000));
	return zIndex;
}

function showBox(boxId, zIndex, bgClickBlock){
	$('body').append('<div id="overlay'+zIndex + '" class="overlay box' + zIndex + '" style="z-index: ' + zIndex + '"></div>');
	docHeight = $(document).height();
	$('#overlay'+zIndex).height(docHeight).show();
	displayBox = $(boxId).parents('.displaybox');
	displayBox.children('.wrapper').css('z-index', zIndex+1);
	displayBox.attr('id', 'displaybox' + zIndex).addClass('box' + zIndex).show();
	if (!bgClickBlock) $('#overlay'+zIndex).click(function(){ hideBox(boxId, zIndex); });
	// if (isIE6) { $(window).scroll(function() { displayBox.attr('display', 'inline-block').attr('display', 'block'); }); }
	return false;
}

function hideBox(boxId, zIndex){
	$('#displaybox'+zIndex).hide();
	$('#overlay'+zIndex).hide().remove();
	if (isIE6) { $(window).unbind('scroll') };
	$('#flashVideoContainer').html('<div id="flashVideo"></div>');
}

function initZoomBox() {
	$('ul.gallery a.thumb-link').live('click', function() {
		picSrc = $(this).find('img').attr('src');
		urlMatch = picSrc.match(/(\d+)_(\w+)_\d\.jpg/);
		if (urlMatch)
		{
			$('#gallery-zoom').css('visibility','hidden');
			$('#gallery-zoom').load('AssetZoom.html?id='+  urlMatch[1] +'&uid=' + urlMatch[2]);
			et_eC_Wrapper( 'DBVGuE', 'Zoom von id ' + urlMatch[1], 'Galerie', 0, '', '', 0, 0, 0, 0, 0, 0, 0);
			return false;
		}
	});

	$('.displaybox').click(function(event) {
		if ($(event.target).is('.container, .container-content, .wrapper')) {
			event.stopPropagation();
			idRef = $(this).attr('id').match('\\d+');
			$("#overlay"+idRef).trigger('click');
		};
	});
}

function initCart() {

	$("#cart-dialog").dialog({
		modal: true,
		autoOpen: false,
		buttons: {
			"Ok": function() { $(this).dialog("close"); },
			"Anzeigen": function() { self.location.href = '/Cart.html'; }
		},
		draggable: false,
		resizable: false,
		zIndex: 65535,
		width: 360,
		close: function() {
			if ($('#cart-dialog-hide').attr('checked'))
				setTimeout("$.post('/Cart.html', {a: 'hidedialog'})", 200);
		}
	});

	$('input:checkbox[id^=cart_]').live('click', function(){
		action = this.checked ? 'add' : 'remove';
		id = this.id.match(/(\d+)$/)[1];

		$.post('/Cart.html', {a: action, id: id, type: 1}, function(data){

			$('#cart-dialog').attr('class', data.response);
			$('#cart-rsp-items').html(data.newcount);

			if ((data.hide == false) || (data.response == 'limit'))
				$("#cart-dialog").dialog('open');

			if (data.response == 'limit')
				$('#cart_' + data.id).removeAttr('checked');

			$('#cart-rsp-filesize').html((Math.round(100*(data.newsize/1024/1024))/100).toString().replace('.', ',') + ' MB');

		}, 'json');
	});
}


function initSearchBox() {
	// search box
	var searchForm = $('#search-form');

	$('#search-options label').click(function() {
		$(this).siblings().removeClass("active").end().addClass("active");
		$('#search-input-label span').text($(this).text());
	});

	$('#srch-b').toggle(function() {
		$('#search-form').show();
	},function(){
		$('#search-form').hide();
	});

	$('#search-close').click(function() {
		$('#search-form').hide();
	});

	searchForm.submit(function(){
		return ($.trim($('#search-input').val()).length > 1)
	})
}

function initHovers(hoverElement, hoverClassHolder) {
	$(hoverElement).hover(
		function() {
			$(this).parents(hoverClassHolder).addClass('hover');
		},
		function() {
			$(this).parents(hoverClassHolder).removeClass('hover');
		}
	);
}

function initFoldings() {
	$('.fold-button').live('click', function() {
		$(this).parent().toggleClass("fold");
		$(this).parent().next('.fold-box').slideToggle();
	});
}

function initFestFrei() {
	if ($("#rdTaetigkeit1").is(":checked")) $("#blockUnternehmen").show();
	if ($("#rdTaetigkeit2").is(":checked")) $("#blockFrei").show();


	$("#rdTaetigkeit1").click(function() {
		$("#blockFrei").slideUp(function() {
			$("#blockFrei input").attr("disabled","disabled");
		});
		$("#blockUnternehmen").slideDown();
		$("#blockUnternehmen input").removeAttr('disabled');
	});
	$("#rdTaetigkeit2").click(function() {
		$("#blockUnternehmen").slideUp(function() {
			$("#blockUnternehmen input").attr("disabled", "disabled");
		});
		$("#blockFrei input").removeAttr('disabled');
		$("#blockFrei").slideDown();
	});
}

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

function initMessageSending() {

	function messageSend(){
		$.post('/contact.html', {msg: $('#userinput-msg').val(), recipient: $('#recipient').val()}, function() {
			alert('Vielen Dank, Ihre Nachricht wurde gesendet!\n\nWir setzen uns schnellstmöglich mit Ihnen in Verbindung.');
		});
	}

    var zIndexMessage = getZindex();

	$('a.vcard').click(function() {
		$('#message-to').text($(this).children('.fn').text());
		$('#message-box .photo').replaceWith($(this).children('.photo').clone());
		$('#recipient').val($(this).children('.contact-id').val());
		// zoomBoxIn('#message-box');
        showBox('#message-box', zIndexMessage);
		return false;
	});

	$('#message-abort').click(function(){ hideBox('#message-box', zIndexMessage); });
	$('#message-send').click(function(){ messageSend(); hideBox('#message-box', zIndexMessage); });

}

function initMessageForwarding() {

	function forwardSend(){
		alert('Meldung weitergeleitet!');
	}

    var zIndexForward = getZindex();

	$('a.forward').click(function() {
        showBox('#forward-box', zIndexForward);
		return false;
	});

	$('#forward-abort').click(function(){ hideBox('#forward-box', zIndexForward); });
	$('#forward-send').click(function(){ forwardSend(); hideBox('#forward-box', zIndexForward); });

}

function initFormValidate() {
/*
	thisForm = $('#form');

	thisForm.submit(function() {

		thisForm.removeClass(errorClass);
		var errorClass = '';
		$('#form input:enabled').each(function(){
			thisElement = $(this);
			thisName = thisElement.attr('name');
			thisLabelWithErrorClass = $('label'+'.err-'+thisName);
			if (thisLabelWithErrorClass[0]) {

				if (thisElement.is(':text, :password') && thisElement.val() == '') {
					errorClass = errorClass + " err-" + thisName;
				};

				if (thisElement.is(':radio')) {
					if (!$("[name=" + thisName + "]:checked")[0]) {
						errorClass = errorClass + " err-" + thisName;
					}
				}

				if (thisElement.is(':checkbox:not(:checked)')) {
					errorClass = errorClass + " err-" + thisName;
				};

				if (thisElement.is('#rdTopic2:checked') && (!$('.nlTopics input:checked')[0])) {
					errorClass = errorClass + " err-" + thisName;
				}

			}
		});

		if ((errorClass) != '') {
			$("#errors-exist").show();
			thisForm.addClass(errorClass);
			return false;
		}
	});*/
}

function inputBox() {
	loginInputs = $('.inputBox label input');
	loginInputs.filter('[value!=]').addClass('input');
	loginInputs.blur();
	loginInputs.focus(function(){
		if ($(this).val() == '') $(this).addClass('input');
	});
	loginInputs.blur(function(){
		$(this).val($.trim($(this).val()));
		if ($(this).val() == '') $(this).removeClass('input').val('');
		loginInputs.filter('[value!=]').addClass('input');
	});
}

function init() {
	pageId = document.body.id;
	datePageLoad = new Date();

	if (typeof document.body.style.maxHeight === "undefined") isIE6 = true;
		else isIE6 = false;

/* --------- switch je nach body id --------- */
	if ($('.inputBox').length > 0) inputBox();
	if ($('#search-block').length > 0) initSearchBox();
	if ($('.fold-button').length > 0) initFoldings();

	switch (pageId)
	{
		case 'pg-1-2':
		case 'pg-7-2':
			initFestFrei();

			$('.btn1').click(function() {

				// Clear error states
				$('#errors-exist').hide();
				$('.err').removeClass('err');
				$('.error-message').hide();

				$.post($('#form').attr('action'), $('#form').serialize(), function(data) {
					if ((l = data.e.length) > 0) {	// form has errors
						$('#errors-exist').show();
						for (var i=0; i<l; i++) {
							$('#lbl-' + data.e[i]).addClass('err');		// Highlight error fields (if any)
							$('#error-message-' + data.e[i]).show();	// Show hidden error warnings (if any)
							location.href = '#errormsg';
						}
					} else {						// form has no errors and was therefore processed correctly
						// No errors, proceed:
						location.href = encodeURI(data.fwd_url);
					}
				}, "json");
				return false;
			});


		case 'pg-2-1': {
			// initClickMarker(".teaser .cart input", ".teaser");
			// initHovers(".teaser .cart, .teaser .teaser-media", "div:first");
			break;
		}

		case 'pg-2-1-1': {

			initCart();
            initMessageForwarding()
			initZoomBox();
			var zIndexGallery = getZindex();
			$('#article-image').click(function(){ $('#lnk-opengallery').trigger('click'); })
			$('#lnk-opengallery').click(function(){
				$picXL = $('#pic-xl');
				showBox($('#gallery'), zIndexGallery);
				et_eC_Wrapper( 'DBVGuE', 'Galerie von Artikel ' + aid, 'Galerie', 0, '', '', 0, 0, 0, 0, 0, 0, 0);

				if ($('#gallery').data('loaded') != true) {
					$('#gallery-content').load('/ArticleGallery.html?id='+aid, function(){
						$('#gallery')
							.removeClass('loading')
							.data('loaded', true);
					});
				}

				return false;
			});

			$('#closegallery').click(function(){
				hideBox($('#gallery'), zIndexGallery);
			});

			break;
		}

		case 'pg-3-1-1-a':{
			initMessageSending();
			initImageNavigation();
			break;
		}

		case 'pg-3-1-1-b':{
			initClickMarker(".pic-m .cart input", ".pic-m");
			initHovers(".pics-m .pic-m .pic-tools", "div:first")
			break;
		}

		case 'pg-3-1-1-c':{
			initClickMarker(".pic-m .cart input", ".pic-m");
			initHovers(".pics-m .pic-m .pic-tools", "div:first");
			initZoomBox();
			break;
		}

		case 'pg-3-1-c':{
			// initFoldings();
			break;
		}

		case 'pg-4-1-c':{
			// initFoldings();
			break;
		}

		case 'pg-5-1':{
			initMessageSending();
			break;
		}

		case 'pg-5-3':
			$('tbody td a').click(function(e) {
				ET_Event.link(escape($(this).attr('href')));
			});
			break;

		case 'pg-5-4-c':{
			// initFoldings();
			break;
		}

		case 'pg-6-1-1':{
			// initFoldings();
			/*initClickMarker(".teaser-s .cart input", ".teaser-s");
			initClickMarker(".pic-s .cart input", ".pic-s");
			initClickMarker("#search-filter li input", "li");
			initHovers(".teaser-s .cart, .pics-s .pic-s .pic-tools", "div:first")*/
			initCart();
			initZoomBox();

			// Images
			$('#result-images .paginator a').live('click', function(event) {
				event.preventDefault(); // don't follow hrefs
				$('#result-images').load($(this).attr('href') + '&' + $('#frmImageOptions').serialize());
				et_eC_Wrapper( 'DBVGuE', 'Blättern im Suchergebnis', 'Suche', 0, '', '', 0, 0, 0, 0, 0, 0, 0);
			});

			$('#frmImageOptions input:checkbox').live('click', function() {
				$('#result-images').load($('#frmImageOptions').attr('action') + '&' + $('#frmImageOptions').serialize());
			});

			$('#frmImageOptions fieldset a').live('click', function(event) {
				event.preventDefault(); // don't follow hrefs
				$(this).parents('fieldset').find('input:checkbox').removeAttr('checked');
				$(this).prev('input:checkbox').attr('checked', 'checked');

				$('#result-images').load($('#frmImageOptions').attr('action') + '&' + $('#frmImageOptions').serialize());
			});

			// Videos
			$('#result-videos .paginator a').live('click', function(event) {
				event.preventDefault(); // don't follow hrefs
				$('#result-videos').load($(this).attr('href') + '&' + $('#frmVideoOptions').serialize());
			});

			// News
			$('#result-news .paginator a').live('click', function(event) {
				event.preventDefault(); // don't follow hrefs
				$('#result-news').load($(this).attr('href') + '&' + $('#frmNewsOptions').serialize());
			});


			break;
		}

		case 'pg-7-1':{
            initZoomBox();

            $('a.cart-trash').click(function(event){
            	event.preventDefault();
            	id = $(this).attr('id').match(/(\d+)$/)[1];

            	if (confirm('Datei aus der Sammelmappe entfernen?')) {
            		$.post('/Cart.html', {a: 'remove', id: id, type: 1}, function() {
            			self.location.reload();
            		})
            	}

            });

            $("#download-dialog-process").dialog({
				modal: true,
				autoOpen: false,
				buttons: {
					"Abbrechen": function() { $(this).dialog("close"); }
				},
				draggable: false,
				resizable: false,
				close: function() { cartAborted = true; }
			});

			$("#download-dialog-finished").dialog({
				modal: true,
				autoOpen: false,
				buttons: {
					"Beenden": function() {
						if (dlClicked || confirm('Sie haben den Download noch nicht gestartet. Trotdem beenden?'))
							$(this).dialog("close");
					}
				},
				draggable: false,
				resizable: false,
				closeOnEscape: false,
				close: function() {
					if ($('#option-clearcart').attr('checked'))
						$.getScript('/Cart.html?a=clear', function(){setTimeout("self.location.reload();", 1000);});
					else
						self.location.reload();
				}
			});

			$('#lnk-download').click(function(event){
				event.preventDefault();

				$("#download-dialog-process").dialog('open');

				cartAborted = false;
				$.getScript('/Cart.html?a=process');

				//cartAborted = false;
			});

			break;
		}

		case 'pg-7-2-2':{
			initFormValidate();

			$('label select').click(function(){
				$(this).siblings('input').trigger('click');
				return false;
			});

			$('.nlTopics input').click(function(){
			    $("#rdTopic2").trigger("click");

			});

			$('#rdTopic1').click(function(){
				$('.nlTopics input').removeAttr('checked');
			});
		}

	}
}

$(function() { init(); });