function trackPg(pgname, areaname)
{
	et_eC_Wrapper('DBVbEK', pgname, areaname, 0, '', '', 0, 0, 0, 0, 0, 0, 0);
}

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

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

	return false;
}

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());
	});

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

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 setWorkOptions() {
	$('#grp-freelance-0,#grp-freelance-1').hide();

	if ($('#freelance-0')[0].checked)
		$('#grp-freelance-0').show();

	if ($('#freelance-1')[0].checked)
		$('#grp-freelance-1').show();
}

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('/Tools/zoom/?id='+ urlMatch[1] +'&uid=' + urlMatch[2]);
			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'; }
		},
		draggable: false,
		resizable: false,
		zIndex: 65535,
		width: 360,
		close: function() {
			if ($('#cart-dialog-hide').attr('checked'))
				setTimeout("$.post('/Cart/hidedialog')", 200);
		}
	});

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

		$.post('/Cart/' + action, {id: id}, function(data){

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

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

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

		}, 'json');
	});
}

function initMessageSending() {

	function messageSend() {
		alert('Nachricht gesendet!');
	}

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

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

}

function initMessageForwarding() {

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

	$('a.forward').click(function() {
		// zoomBoxIn('#forward-box');
		return false;
	});

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

}

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 ($('#search-block').length > 0) initSearchBox();
	if ($('.inputBox').length > 0) inputBox();
	if ($('.line .fold-button').length > 0) initFoldings();
	if (typeof document.body.style.maxHeight === "undefined") isIE6 = true;
		else isIE6 = false;

	switch (pageId)
	{
		case 'pg-0-1': {
			$('#frmLogin').submit(function(){
				$('#message').hide();
				$.post($('#frmLogin').attr('action'), $('#frmLogin').serialize(), function(data){
					switch (data.continuewith) {
						case '1':
							window.location.href = '/News'; break;
						case '2':
							window.location.href = '/News/interstitial/200910-lfa-video/'; break;
						default:
							$('#message').show(); break;
					}
				}, 'json');
				return false;	// Never really submit the form
			});
			break;
		}

		case 'pg-0-2':{

			$('dl.faq dt').click(function() {
				$(this).next('dd').slideToggle('fast');
				return false;
			});

			if (($.browser.msie) && (parseInt($.browser.version) < 7)) {
				$('#oldbrowser')
					.show()
					.find('#oldbrowser-browser').html('Internet Explorer').end()
					.find('#oldbrowser-href').attr('href', 'http://www.microsoft.com/germany/windows/internet-explorer/default.aspx').html('http://www.microsoft.com/germany/windows/internet-explorer/default.aspx');
			} else if (($.browser.mozilla) && (parseFloat($.browser.version.substring(0, 3)) < 1.9)) {
				$('#oldbrowser')
					.show()
					.find('#oldbrowser-browser').html('Firefox').end()
					.find('#oldbrowser-href').attr('href', 'http://www.mozilla-europe.org/de/firefox/').html('http://www.mozilla-europe.org/de/firefox/');
			}



			// initFestFrei();
			setWorkOptions();
			$('#freelance-0,#freelance-1').click(function() { setWorkOptions(); });

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

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

				frm = $('.form');
				$.post(frm.attr('action'), frm.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)
							$('#errmsg-' + data.e[i]).show();			// Show hidden error warnings (if any)
						}
					} else {						// form has no errors and was therefore processed correctly
						// No errors, proceed:
						location.href = '/Registration/confirm';
					}
				}, "json");
				return false;
			});

			break;
		}

		case 'pg-1-1': {
			var zIndexGallery = getZindex();

			initZoomBox();

			if (isIE6) $('.models').supersleight();  // IE6 png24-Alpha Transparenz

			$('ul.variants>li a').click(function(e){
				showBox($('#assetbrowser'), zIndexGallery);

				$('#assetbrowser').addClass('loading');
				$('#assetbrowser-content').html('');

				loadAssetBrowser = function(a_href) {
					$('#assetbrowser-content').load(a_href, function(){
						$('#assetbrowser').removeClass('loading');

						sIFR.replace(nobellt, {
							selector: '#assetbrowser h2',
							wmode: 'transparent'
						});
					});
				}

				setTimeout("loadAssetBrowser('" + this.href + "')", 400);

				e.preventDefault();
			});

			/*$('#modellist-current .model h3').click(function(){
				$(this).siblings('ul.variants:first').find('li.all-variants>a').trigger('click');
			});*/

			$('#assetbrowser-close').click(function(){
				hideBox($('#assetbrowser'), zIndexGallery);
			});

			$('#lnk-models-archive').click(function(){
				$('#modellist-current').fadeOut(function(){
					$('#modellist-archive').fadeIn(function(){
						sIFR.replace(nobellt, {
							selector: '#modellist-archive h2',
							wmode: 'transparent'
						});
					});
					trackPg('Vergangene Generationen', 'Fahrzeuge');
				});
				return false;
			});
			$('#lnk-models-current').click(function(){
				$('#modellist-archive').fadeOut(function(){
					$('#modellist-current').fadeIn();
					trackPg('Aktuelle Generationen', 'Fahrzeuge');
				});
				return false;
			});

			break;
		}

		case 'pg-2-1': {
			initCart();
			break;
		}

		case 'pg-2-1-a': {
			break;
		}

		case 'pg-2-1-1':{
			initCart();
			var zIndexGallery = getZindex();
			initZoomBox();
			$('#lnk-opengallery').click(function(){
				$picXL = $('#pic-xl');

				showBox($('#gallery'), zIndexGallery);

				if ($('#gallery').data('loaded') != true) {
					$('#gallery-content ul.gallery').load('/Article/Gallery/?ref=article&id='+articleId, function(){
						$('#gallery')
							.removeClass('loading')
							.data('loaded', true);
						trackPg('Galerie', 'News');

						sIFR.replace(nobellt, {
							selector: '#gallery h3',
							wmode: 'transparent'
						});
					});
				}

				return false;
			});

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

			break;
		}

		case 'pg-3-1':
		case 'pg-4-1':
		case 'pg-5-1':
			$('a.extlink').click(function(){
				if (confirm('Sie verlassen jetzt die Presse-Website und werden zu einer anderen Website weitergeleitet.\nUm später wieder hierhin zurückzukehren, schließen Sie das neue Fenster.'))
					{ window.open(this.href); }

				return false;
			});

			break;


		case 'pg-6-1':{

			// Call articles via ajax:
			$('li.teaser a').click(function(e){
				article_href = $(this).attr('href');
				self.lastCalledArticleId = article_href.match(/(\d+)$/)[1];

				$.post(article_href, {testgrants: 1}, function(data){
					if (data.granted != '1')
						$("#access-dialog").dialog('open');
					else
						self.location.href = article_href;
				}, 'json');

				e.preventDefault();
			});

			$('#pwdStartOver').click(function(e){
				$('#articlePwd').val('');
				$('#access-input').attr('class', 'status-input');
				e.preventDefault();
			});

			$("#access-dialog").dialog({
				modal: true,
				autoOpen: false,
				buttons: {
					"Abbrechen": function() {
						$('#pwdStartOver').trigger('click'); // reset dialog to default styles
						$(this).dialog("close");
					},
					"Freischalten": function() {
						$('#access-input').attr('class', 'status-testing');
						$.post('/Article/unlock', {id: self.lastCalledArticleId, pwd: $('#articlePwd').val()}, function(data){
							if (data.unlocked != '1') {
								$('#access-input').attr('class', 'status-fail');
							} else {
								self.location.href = '/Article/?id=' + self.lastCalledArticleId;
							}
						}, 'json');
					}
				},
				draggable: false,
				resizable: false,
				zIndex: 65535,
				width: 400,
				height: 190
			});

			break;
		}

		case 'pg-7-1':{
			scrollingEngaged = false;
			initCart();
			initZoomBox();
			window.scrollTo(0,0);

			// New image browser: -------------------------------------
			redrawFilters = function(){
				$('#imagebrowser label:has(input:radio:checked)').addClass('active');
				$('#imagebrowser label:not(:has(input:radio:checked))').removeClass('active');
				setTimeout("$('#imagebrowser #filters>li>ul:has(input:radio:checked) li.showall').show('slow');", 1000);
			}

			requery = function() {
				window.scrollTo(0,0);
				$('#imagebrowser ul.gallery')
					.html('<li id="imagebrowser-loader"></li>')
					.load('/Search/?' + baseQuery + '&t=1&p=1&' + $('#frmImgBrowser').serialize());
			}

			/*
			 * Click logic:
			 */
			$('#imagebrowser #filters>li>ul>li>label>input:radio').click(function(){

				// Click on 1st-level option deactivates OTHER 2nd-level options in the group
				$(this).parents('li:first').siblings().find('li input:radio').removeAttr('checked');

				// Click on 1st-level option selects first child-option, unless a child is already selected
				parentList = $(this).parents('li:first').children('ul');
				if (parentList.find('input:radio:checked').length == 0)
					parentList.find('input:radio:first').attr('checked', 'checked');

				setTimeout("requery()", 500);
				redrawFilters();

				if ($(this).parents('li:first[class^=collapsed]').length == 1)
					$(this).next('a').trigger('click');
			});

			$('#imagebrowser #filters>li>ul>li>ul>li>label>input:radio').click(function(){

				// Click on 2nd-level option triggers click on 1st-level parent option
				$(this).parents('li:first').parents('li:first').children('label').find('input:radio').trigger('click');
				redrawFilters();
			});


			/*
			 * Folding:
			 */
			$('#imagebrowser #filters a:not([id=showAll])').click(function(e){
				$(this).parents('li:first').find('ul:first').slideToggle('fast', function(){
					if ($(this).is(':hidden'))
						$(this).parents('li:first').addClass('collapsed');
					else
						$(this).parents('li:first').removeClass('collapsed');
				});
				e.preventDefault();
			});

			/*
			 * "Endless" scrolling
			 */
			$(window).scroll(function(){
				if ((! scrollingEngaged)
					&& (curPg < Math.ceil(resTotal/perPg))
					&& ($(window).height() + $(window).scrollTop() >
							$('#imagebrowser .gallery').height() + 287 )
														/* 287 is the distance from the very top of
														 * the page to the top of the gray image browser */ ) {
					scrollingEngaged = true;
					$.get('/Search/result/?t=1&p=' + (curPg + 1) + '&v=' + $('#viewtype input:radio:checked').val(), function(data){
						curPg++;
						$('#imagebrowser ul.gallery').append(data);
					});
				}
			});

			/*
			 * Viewtype filters:
			 */
			$('ul#viewtype input').click(function(){
				$('ul#viewtype').attr('class', 'active-vt-' + $(this).val());
				setTimeout("requery()", 500);
			});

			// ---------------------------------------------------------

			break;
		}

		case 'pg-8-1':{

			initZoomBox();

			$("#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/clear');
					else
						self.location.reload();
				}
			});


			$('a[id^=remove_]').click(function(){
				id = this.id.match(/(\d+)$/)[1];

				$.post('/Cart/remove', {id: id}, function(data){
					self.location.reload();
				});
			});

			$('#lnk-download').click(function(){
				$(this).attr('src', '/img/button_cart_dl_all.png');	// static image w/o animation
				$("#download-dialog-process").dialog('open');

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

				return false;
			});

			$('#lnk-clear').click(function(){
				if (confirm('Möchten Sie wirklich alle Dateien aus Ihrer Sammelmappe entfernen?'))
					$.getScript('/Cart/clear');
			});

			break;
		}

		case 'pg-9-1':{
			$('#tabs').tabs(
				{select: function(event, ui) {
						switch(ui.index) {
							case 0:
								trackPg('Meine Daten: Basisangaben', 'Meine Daten');
								break;
							case 1:
								trackPg('Meine Daten: Zugangsdaten', 'Meine Daten');
								break;
							case 2:
								trackPg('Meine Daten: E-Mail', 'Meine Daten');
								break;
						}
				}}
			);

			setWorkOptions();

			$('#freelance-0,#freelance-1').click(function() { setWorkOptions(); });

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

				// Clear error states
				$('.err').removeClass('err');
				$('.errmsg').hide();

				frm = $(this).parents('form:first');
				$.post(frm.attr('action'), frm.serialize(), function(data) {
					if ((l = data.e.length) > 0) {	// form has errors
						for (var i=0; i<l; i++) {
							$('#lbl-' + data.e[i]).addClass('err');		// Highlight error fields (if any)
							$('#errmsg-' + data.e[i]).show();			// Show hidden error warnings (if any)
						}
						$('#data-' + data.c + ' .update-status').removeClass('status-fail status-ok').addClass('status-fail');

					} else {						// form has no errors and was therefore processed correctly
						// No errors, proceed:
						$('#data-' + data.c + ' .update-status').removeClass('status-fail status-ok').addClass('status-ok');
					}
				}, "json");
				return false;
			});
			break;
		}

	}
}

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