var count_a = 1;
var slideInterval = false;
//alert(window.navigator.userAgent);

$(document).ready(function() {
	$(".placeholder").placeholder();

	Date.format = 'dd.mm.yyyy';
	$('.date-pick').datePicker({clickInput:true, createButton: false, horizontalOffset:79});
	
	$('.gallery ul li a').live('click', function(e){
		e.preventDefault();

		//Set Current Opened-Gallery
		current_gallery = $(this).closest('.gallery').attr('id');
		$('.gallery_imagefull:not(.hidden)').each(function(){
			if ($(this).parent().find('.gallery').attr('id') != current_gallery) {
				var opengallery = this;
				$(opengallery).addClass('hidden');
				$(opengallery).animate({
					height : 0
				}, 500, function(){
					$(opengallery).attr('style', '');
				});
			}
		});
		var link = this;
		var imagefull = $(link).closest('.gallery').parent().find('.gallery_imagefull img');

		//Add data to Fullscale-Image
		$(imagefull).attr('src', $(link).attr('href'));
		$(imagefull).attr('rel', $(link).attr('rel'));

		//Scroll list to clicked Image
		$(link).closest('.gallery').parent().find('#controls li[rel='+$(link).attr('rel')+']').trigger('click');

		var image_container = $(imagefull).parent();

		//If Fullscale-Image is hidden show it and Add Buttons
		if ($(image_container).hasClass('hidden')) {

			if ( $(image_container).find('.prevBtn').length == 0 ) {
				//Copy Prev-Button
				var button = $(link).closest('.gallery').parent().find('#controls .prevBtn').clone(true);

				//Add Click-Event so the Fullscale-Image will be switched too on click
				$(button).click(function(){
					var thisbutton = this;
					var imagenr = $(thisbutton).parent().find('img').attr('rel');
					imagenr--;
					var newsrc;
					if (imagenr < 1) {
						newsrc =  $(thisbutton).parent().parent().find('.gallery ul li a:nth-child(1)').attr('href');
						imagenr = $(thisbutton).parent().parent().find('.gallery ul li a:nth-child(1)').attr('rel');
					}else newsrc =  $(thisbutton).parent().parent().find('.gallery ul li a[rel='+imagenr+']').attr('href');
					$(thisbutton).parent().find('img').attr('src', newsrc);
					$(thisbutton).parent().find('img').attr('rel', imagenr);
				});

				$(image_container).append(button);

				//Copy Next-Button
				button = $(link).closest('.gallery').parent().find('#controls .nextBtn').clone(true);

				//Add Click-Event so the Fullscale-Image will be switched too on click
				$(button).click(function(){
					var thisbutton = this;
					var imagenr = $(thisbutton).parent().find('img').attr('rel');
					imagenr++;
					var newsrc =  $(thisbutton).parent().parent().find('.gallery ul li a[rel='+imagenr+']').attr('href');
					if (newsrc == undefined) {
						imagenr = 1;
						newsrc =  $(thisbutton).parent().parent().find('.gallery ul li a[rel='+imagenr+']').attr('href');
					}
					$(thisbutton).parent().find('img').attr('src', newsrc);
					$(thisbutton).parent().find('img').attr('rel', imagenr);
				});
				$(image_container).append(button);
			}

			//Remove Hidden-Class so Fullscale-Image is visble, show Fullscale-Image
			$(image_container).removeClass('hidden');
			var containerheight = 400;
			//$(image_container).height(0);
			$(image_container).animate({
				display : 'block',
				height : '400px'
			}, 500, function(){
				//$(image_container).height(auto);
				});

		}
	});

/* AJAX URIS */
/*  MEEH
$('#menubar_topbottom a').each(function(){
	var href= $(this).attr('href');
	href = href.replace( base_uri , '');
	$(this).attr('href', base_uri+'#!'+href);
});

$('#menubar_topbottom a').click(function(e){
	//e.preventDefault();
	var path = $(this).attr("hash");
	path = path.replace('!#');
	$.ajax({
	  url: base_uri+'/ajax'+path,
	  success: function(html){
		$("#content").append(html);
	  }
	});

}); */
	if (!($.browser.msie && $.browser.version.substr(0,1)<7)) {
		$('#marketplaceoptions a').live('click', function(e) {
			e.preventDefault();
			$.ajax({
				  url: base_uri+'/ajax/fahrzeugmarkt/'+collator_action,
				  success: function(html){
					$("#car_content").replaceWith(html);
				  }
				});
		});

		$('body').delegate('#marketplaceoptions select, .sorting_options select, #pagination_results select',"change", function() {
		/*$('#marketplaceoptions select, .sorting_options select').live('change', function(){*/
			var set = '';
			$('#marketplaceoptions select, .sorting_options select, #pagination_results select').each(function(){
				if ( $(this).attr('value').length > 0) {
					set += $(this).attr('id')+'__'+$(this).attr('value')+'/';
				}
			});

			$.ajax({
				type: "GET",
			  url: base_uri+'/ajax/fahrzeugmarkt/'+collator_action+'/1/'+set,
			  success: function(html){
				  html = $(html);
				  html = html[0];
				$("#car_content").replaceWith(html);
			  }
			});
		});
	}

	$('.add_part').click(function(){
		var cl_part = $(this).parent().find('div.parts:first');
		$(cl_part).after($(cl_part).clone());
		count_a += 1;
		$(cl_part).next().find('input').each(function(){
			$(this).attr({'value': '', 'name': $(this).attr('name').replace('1', count_a)});
		});
		$(cl_part).next().prepend('<div class="delete_part" title="Löschen"></div>');
	});

	$('.delete_part').live('click', function(){
		$(this).parent().remove();
	});

	/*$(".cfblock").click(function(){
		$(".cfblock").next(".content_block").slideToggle();
	});*/

	/*
	 * Kontaktformular ein-/ausblenden
	 */
	$(".closeblock_button").parent().css('height','13px').find('.contactdesc').hide();
	$(".closeblock_button").parent().find('.contactformheadline h2').css('border', 'none');
	$(".closeblock_button").parent().find('.contactform').hide();
	$(".closeblock_button").parent().find('.contactdesc').hide();
	$(".contact_send_button").each(function() {
	    $(this).css('display', 'none');
	});

	$(".closeblock_button, .contactformheadline").toggle(
		function(){
			//$(this).hide();
			$('.closeblock_button').hide();
			var block = $(this).parent();
			$(block).css('height','auto');
			$(block).find('.contactform').slideDown('slow');
			$(block).find('.contactdesc').slideDown('slow');
			$(block).find('.contactformheadline h2').css('border-bottom','1px solid #686D71');

			window.setTimeout(function() {
			    $(".contact_send_button").each(function() {
				$(this).css('display', 'block');
			    });
			}, 500);
		},
		function(){
			/*var block = $(this).parent();
			$(block).css('height','13px');
			$(block).find('.contactform').slideUp('slow');
			$(block).find('.contactdesc').slideUp('slow');
			$(".contact_send_button").each(function() {
			    $(this).hide();
			});*/
		}
	);

	$('#content_infobox').css('margin-bottom', '-30px');
	$('#content_infobox').css('opacity', '0');
	//$('#logoanimation').css('left', '-84px');


	/**
	 * Teile und Zubehör
	 */
	$('.zubehoer_wrapper').each(function() {
	    $(this).hide();
	});

	$('a.openProducts').toggle(function() {
		var openWhat = $(this).attr('id');
		$('div.zubehoer_wrapper[rel='+openWhat+']').slideDown();
		$(this).show();
		$(this).html('Produkte ausblenden');
		var target = openWhat.replace('button_', '');
		window.location = '#' + target;
	}, function() {
		var openWhat = $(this).attr('id');
		$('div.zubehoer_wrapper[rel='+openWhat+']').slideUp();
		$(this).show();
		$(this).html('Produkte anzeigen');
	});

	/**
	 *  Team
	 */

	$('a.next').click(function() {
	    $(this).parent().animate({
		opacity: 0,
		'left' : '-150px'
	    }, 500, function() {
		var next_id = '#' + $(this).children('a.next').eq(0).attr('rel');
		var my_id = '#' + parseInt($(this).attr('id'));
		$(my_id).removeClass('active_team');
		$(next_id).addClass('active_team');
		$(next_id).css('left', '0px');
		$(next_id).animate({
		    opacity: 1,
		    'left': '-110px',
			'filter': ''
		}, 500, function() {
		    
		});
	    });
	});

	$('a.back').click(function() {
	    $(this).parent().animate({
		opacity: 0,
		'left' : '0px'
	    }, 500, function() {
		var next_id = '#' + $(this).children('a.back').eq(0).attr('rel');
		var my_id = '#' + parseInt($(this).attr('id'));
		$(my_id).removeClass('active_team');
		$(next_id).addClass('active_team');
		$(next_id).animate({
		    opacity: 1,
		    'left': '-110px',
			'filter': ''
		}, 500, function() {

		});
	    });
	});


	// Click handler for slideshow icons
	$('.slide_icon').click(function() {
	    clearInterval(slideInterval);
	    // Get new link
	    var link = $('div[rel='+newMargin+']').children("div").eq(0).children("a").eq(0).attr("href");
	    $('.footerbox a.seenews').attr("href", link);
	    
	    $('.active_icon').removeClass('active_icon');
	    $(this).addClass('active_icon');
	    var newMargin = $(this).attr("id") * parseInt($('.news_box').css('width'));
	    $('.thenews').animate({
		marginLeft: "-" + newMargin + 'px'
	    }, 1000, function() {
		startSlideshow();
	    });
	});

	startSlideshow();

});

function startBgAnimation(img) {
    /*
     * Muss hier nochmal gesetzt werden sonst gibt es
     * Probleme mit dem Browsercache
     */
    $('#content_backgroundphoto').attr('src', img.src);
    $('#content_backgroundphoto').append('<img src="' + img.src + '" />');
    $('#content_backgroundphoto').css('margin-left', '-540px');
    $('#content_backgroundphoto').css('opacity', '0');
    
    //$('#content_backgroundphoto').css('filter' , "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='crop',src='" + img.src + "')");
    $('#content_backgroundphoto').animate({
	opacity: 1,
	'margin-left': '-568px',
	'filter': ''
    }, 1200, 'easeOutCubic', function() {
	$('#content_backgroundphoto').css('filter', '');
    });

    $('#content_backgroundphoto img').css("opacity", "none");

   window.setTimeout(function() {
	$('#content_infobox').animate({
	    opacity: 1,
	    'margin-bottom':'0px',
		'filter': ''
        }, 800, 'easeOutCubic', function() {
	});
    }, 400);
}

function showInfoboxImage() {
    $('#content_infobox').css('margin-bottom', '0px');
    $('#content_infobox').css('opacity', '0');
    window.setTimeout(function() {
	$('#content_infobox').animate({
	    opacity: 1,
	    'margin-bottom':'0px',
		'filter': ''
        }, 800, 'easeOutCubic', function() {});
    }, 400);
}

/*function startSlideshow() {
	$('.news_box.active_news').show();
	window.setInterval(function() {
		$('.news_box.active_news').fadeOut(1000, function() {
			if($(this).next('.news_box').length > 0) {
				$(this).next('.news_box').fadeIn(1000, function() {
					$('.footerbox a.seenews').attr("href", $(this).find("a").eq(0).attr("href"));
					$(this).addClass('active_news');
					//startSlideshow();
				});
				
				$('.slide_icon.active_icon').removeClass("active_icon");
				$('.slide_icon#' + $(this).attr("rel")).addClass("active_icon");
				$(this).removeClass('active_news');
			} else {
				$('.news_box').eq(0).fadeIn(1000, function() {
					$('.footerbox a.seenews').attr("href", $(this).find("a").eq(0).attr("href"));
					$(this).addClass('active_news');
					//startSlideshow();
				});
				
				$('.slide_icon.active_icon').removeClass("active_icon");
				$('.footerbox .slide_icon').eq(0).addClass("active_icon");				
				$(this).removeClass('active_news');
			}
		});
	}, 5000);
}*/

function startSlideshow() {
	
	slideInterval = window.setInterval(function() {
	    var margin = parseInt($('.thenews').css('marginLeft'));
	    var newMargin = margin-parseInt($('.news_box').css('width'));
	    
	    var link = '/aktuelles/verkauf/';
	    
	    if(newMargin != -parseInt($('.thenews').css('width'))) {
		// Get new link
		link = $('div[rel='+newMargin+']').children("div").eq(0).children("a").eq(0).attr("href");
		$('.footerbox a.seenews').attr("href", link);
	    
		var c = $('.slide_icon.active_icon');
		var n = $('.slide_icon.active_icon').next('.slide_icon');
		
		c.removeClass('active_icon');
		n.addClass('active_icon');
		
		$('.thenews').animate({
		    marginLeft: newMargin + 'px'
		}, 1000);
	    } else {
		// Get new link
		link = $('div[rel=0]').children("div").eq(0).children("a").eq(0).attr("href");
		$('.footerbox a.seenews').attr("href", link);
		
		$('.active_icon').removeClass('active_icon');
		$('.slide_icon').eq(0).addClass('active_icon');
		
		$('.thenews').animate({
		    marginLeft: '0px'
		}, 500);
	    }
	}, 5000);
}
