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)
		{
			LI = $(this).parents('li:first');

			$('#gallery-zoom').css('visibility','hidden');
			$('#gallery-zoom').load('/AssetZoom.html?id='+  urlMatch[1] +'&uid=' + urlMatch[2], function(){

				LI_prev = LI.prev();
				lnkPrev = LI_prev.find('.thumb-link>img').attr('id');
				LI_next = LI.next();
				lnkNext = LI_next.find('.thumb-link>img').attr('id');

				if (lnkPrev != undefined)
				{
					$('a#gallery-prev')
						.click(function(e){
							LI_prev.find('a.thumb-link').trigger('click');
							e.preventDefault();
						});
				}
				else
				{
					$('a#gallery-prev').hide();
				}

				if (lnkNext != undefined)
				{
					$('a#gallery-next')
						.click(function(e){
							LI_next.find('a.thumb-link').trigger('click');
							e.preventDefault();
						});
				}
				else
				{
					// See if we can fetch new objects via endless scrolling
					$('a#gallery-next').hide();
					$(window).trigger('scroll', LI);
				}

			});

			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() {
	if ($("#dialog-cart").length == 1)
		$("#dialog-cart").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
		});

	/*
	$('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);
			$('#cart-count').html(data.newcount > 0 ? 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');
	});*/
	
	$('.link-cart').live('click', function(e){
		e.preventDefault();
		
		$.get($(this).attr('href'), function(data){
			if (data.response == 'added')
			{
				$('.link-cart-' + data.id).each(function(){
					$(this)
						.removeClass('link-dl-incart').addClass('link-dl-incart-1')
						.attr('href', $(this).attr('href').replace('a=add', 'a=remove'));
				});
			} else if (data.response == 'removed') {
				
				$('.link-cart-' + data.id).each(function(){
					$(this)
						.removeClass('link-dl-incart-1').addClass('link-dl-incart')
						.attr('href', $(this).attr('href').replace('a=remove', 'a=add'));
				});
				
				// Trigger possibly attached custom event:
				$('.link-cart-' + data.id).trigger('afterCartRemove', data);
				
			} else if (data.response == 'limit') {
				$('#dialog-cart-content').html('Ihre Sammelmappe enthält bereits die maximale Datenmenge. Das gewünschte Element wurde nicht hinzugefügt.');
				$("#dialog-cart").dialog('open');
			}
			
			$('#cart-count').text(data.newcount > 0 ? data.newcount : '');
			
		}, '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();
		$('#search-input').focus();
	},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-1':
			setTimeout("$('#login-name').focus()", 500);
			break;

		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-3-1-2':
		case 'pg-4-1-1':
			initZoomBox();
			initCart();
			var zIndexGallery = getZindex();

			$('#models .model').click(function(){
				// $(this).find('a:first').trigger('click');
			});


			/* 						:not(:last) omits link to lexus site */
			$('#models .model a,#nav3 li:not(:last) 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');
					});
				}

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

				e.stopPropagation();	// prevent the click on .model from firing
				e.preventDefault();
			});

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

			break;

		case 'pg-2-1-1':

			initCart();
            initMessageForwarding()
			initZoomBox();
			var zIndexGallery = getZindex();
			var zIndexAssetbrowser = zIndexGallery + 1;
			$('#article-image').click(function(){ $('#lnk-opengallery').trigger('click'); })
			$('#lnk-opengallery').click(function(){
				$picXL = $('#pic-xl');
				showBox($('#gallery'), zIndexGallery);

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



			$('#related-models a').click(function(e){
				showBox($('#assetbrowser'), zIndexAssetbrowser);

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

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

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

				e.stopPropagation();	// prevent the click on .model from firing
				e.preventDefault();
			});

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

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

			$('#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-imgbrowser':
			scrollingEngaged = false;
            initZoomBox();
            initCart();

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

				redrawFilters();
            	
            	// location.href = '/Search.html?' + $('#frmImgBrowser').serialize();
            	
			}
            removeOption = function(id) {
            	if ($('#filters-summary li').length < 2) {
            		alert('Kriterium kann nicht entfernt werden:\nEs muss mindestens ein Suchkriterium vorhanden sein.');
            	} else {
	            	$('#' + id).removeAttr('checked');
	            	requery();
            	}
            }

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

				$('#filters-summary').html('');
				$('#imagebrowser input:radio:checked').each(function(){
					if (this.value != '')
						$('#filters-summary').html($('#filters-summary').html() + '<li><span onclick="removeOption(\'' + this.id + '\');" title="entfernen">&times;</span> ' + this.title + '</li>');
				});
				if ($('#userquery').val().length > 0)
					$('#filters-summary').html($('#filters-summary').html() + '<li>Suchbegriff <strong>' + $('#userquery').val() + '</strong></li>');
			}

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

			/*
			 * Click on filters
			 */

			// FIRST level click
			$('#imagebrowser ul.lev1>li>label>input:radio').click(function(){
				setTimeout("requery()", 500);
			});

			// SECOND level click
			$('#imagebrowser ul.lev2>li>label>input:radio').click(function(){
				// 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');

				if (parentList.length == 0)
					$(this).parents('ul.lev1:first').find('ul.lev3').find('input:radio').removeAttr('checked');

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

			// THIRD level click
			$('#imagebrowser ul.lev3>li>label>input:radio').click(function(){
				$(this).parents('li:first').parents('li:first').children('label').find('input:radio').trigger('click');
			});

			/*
			 * Filter folding
			 */
			$('#filters a.lev1').click(function(e){
				$(this).parents('li:first').toggleClass('expanded');
				this.blur();
				e.preventDefault();
			});
			$('#filters a.lev2').click(function(e){
				$(this).parents('li:first').toggleClass('collapsed');
				this.blur();
				e.preventDefault();
			});
			$('#filters li.lev3 label a').click(function(e){
				$(this).parents('li:first').toggleClass('lev3-collapsed');
				this.blur();
				e.preventDefault();
			});

            /*
			 * "Endless" scrolling
			 */
			$(window).scroll(function(e, LI){

            	if ((LI != undefined /* event was triggered and contains the last clicked LI element */) ||
            		((! scrollingEngaged)
					&& (curPg < Math.ceil(resTotal/perPg))
					&& ($(window).height() + $(window).scrollTop() >
							$('#imagebrowser ul.gallery').height() + 210 ))
														/* 210 is the distance from the very top of
														 * the page to the top of the gray image browser */ ) {
					scrollingEngaged = true;
					$.get('/Search.html?a=result&mt=5&p=' + (curPg + 1) + '&v=' + $('#viewtype input:radio:checked').val(), function(data){
						curPg++;
						$('#imagebrowser ul.gallery').append(data);

						if (LI != undefined) {
							LI_next = $(LI).next();
							lnkNext = LI_next.find('.thumb-link>img').attr('id');
							if (lnkNext == undefined)
							{
								$('a#gallery-next').hide();
							} else {
								$('a#gallery-next')
									.show()
									.click(function(e){
										LI_next.find('a.thumb-link').trigger('click');
										e.preventDefault();
									});
							}
						}
					});
				}
            });

			redrawFilters();
            break;

		case 'pg-7-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.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 initMagnifier()
{
	window.timerMagnifier = false;
	
	magnifierIdle = function()
	{
		$('#magnifier').hide();
	}
	
	$('#magnifier').mouseleave(function(){ magnifierIdle(); });
	
	$('.thumb-img').live('mouseover mouseout', function(e){
		
		thumb = $(this);
		
		if (e.type == 'mouseover') {
			window.timerMagnifier = setTimeout(function(){
				
				// Retrieve meta data:
				imgids = thumb.attr('src').match(/\/((\d+)_([0-9a-f]+)_)/i);
				
				$.get('/GetAssetInfo.html?id=' + imgids[2] + '&uid=' + imgids[3], function(data){
					$('#magnifier-img')
						.attr('src', thumb.attr('src').replace(/_\d\.jpg/, '_5\.jpg?' + Math.random()))
						.load(function(){
							$(this).unbind('load');
							$('#magnifier-descr').text(data.titel);
							$('#magnifier-daterelease').text(data.date_release);
							$('#magnifier-link-incart')
								.attr('class', 'link-download link-cart link-cart-' + imgids[2] + ' link-dl-incart' + (data.in_cart == 1 ? '-1' : ''))
								.attr('href', '/Cart.html?id=' + imgids[2] + '&a=' + (data.in_cart == 1 ? 'remove' : 'add'));
							$('#link-download-1').attr('href', '/dl.html?id=' + imgids[2] + '&uid=' + imgids[3] + '&v=1');
							$('#link-download-2').attr('href', '/dl.html?id=' + imgids[2] + '&uid=' + imgids[3] + '&v=2');
							
							if (data.model.id > 0) {
								// We have model data:
								$('#magnifier-modelinfo').show();
								$('#magnifier-modeldata').text('Toyota ' + data.model.name + (data.model.info.length > 0 ? ' (' + data.model.info + ')' : ''));
								if (data.model.status == 0)
									$('#magnifier-modeldata-old').show();
							} else {
								$('#magnifier-modelinfo').hide();
								$('#magnifier-modeldata-old').hide();
							}
							
							thumbPos = thumb.offset();
							$('#magnifier')
								.css('top', thumbPos.top - 150 + 'px')
								.css('left', thumbPos.left - 150 + 'px')
								.show();
						});
					
				}, 'json');
				
			}, 150);
		} else /* mouseout */{
			clearTimeout(window.timerMagnifier);
		}
		
	});
}

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