$(document).ready(function() {

	// ----------------- Selectboxen stylen -----------------//
	
	$("select").not($('select[multiple]')).selectbox();
	$(' .sbOptions li:last-child a').css('border','0'); // Letzter Option border wegnehmen
	
	
	// ----------------- Blättern ----------------- //
	
		
		$img_wide = $('.img_wide'); 
		$pfeil = $img_wide.find('.pfeil')
		$pfeil.hide();
		$img_wide.mouseenter(function(){ 
			$pfeil.show();
			}).mouseleave(function(){ 
			$pfeil.hide();
			})
		
		
		
		// ----------------- Menü ----------------- //		
		
		
		
		
		
		$('#mainnav>ul>li:not(".aktiv")').hover(function() {
		
		if($(this).children('ul').length) {
			$(this).children('ul').toggle();
			$(this).toggleClass('aktiv');
			$('a.aktiv + span + ul').toggle();
		}
	
		});	
	
	// ----------------- Abgerundete Ecken ----------------- //
	
					$('img').each(function() {
						if($(this).hasClass('floated_right')) {
							$(this).removeClass('floated_right').wrap('<div class="floated_right"></div>');
						} else if ($(this).hasClass('floated_left')) {
							$(this).removeClass('floated_left').wrap('<div class="floated_left"></div>');
						} else if ($(this).hasClass('floated_left_overflow')) {
							$(this).removeClass('floated_left_overflow').wrap('<div class="floated_left_overflow"></div>');
						} else if ($(this).hasClass('img_wide')) {
							$(this).removeClass('img_wide').wrap('<div class="img_wide"></div>');
						}
						
					});
					
				
						
	
	$('#header, #footer, .teaser_image, .img_wide').corner('8px');
	$('.subnav, #leftnav, #leftnav .aktiv, .sidebar, .sbHolder, .sbOptions, .floated_right:not(".logo_container"), .floated_left, .rounded_corners, .floated_left_overflow, .cboxElement img').not('.scrolllist .floated_right').corner('5px');
	
	if ( !$.browser.msie || ($.browser.msie && parseInt($.browser.version)) > 8) { 
		$('input, textarea').corner("3px");
	}
	
	
	
	// ----------------- Colorbox -----------------//
	
	$("a[rel='detail']").colorbox({rel:'nofollow'}); // Slidebox aktivieren und Gruppierung verhindern
	$("a[rel='grouped_detail']").colorbox().corner('3px');
	$("a[rel='grouped_detail2']").colorbox();



	// ----------------- Formatierung - Könnte man noch mit PHP machen!? ----------------- //
	
	$('#leftnav > li:first-child').addClass('menufirst');
	$('#leftnav li:last-child').addClass('menulast');
	
	$('.sidebar h4:last-child').css('margin-bottom','0px');	
	$('.sidebar .sidebox:last-child').addClass('last');
	$('.sidebar p:last-child').addClass('last');
	$('.little_box:nth-child(2n+2)').css('margin-right','15px');
	
	$('.artikel:not(".border, .last")').css('margin-bottom','0');
	
	$('form:not("#AUSWAHL") ol li:nth-child(2)').addClass('single');
	$('.float, #AUSWAHL').parent().css('overflow','visible');
	
	$('.likesend').parent('div.artikel').css('overflow', 'visible');
	
	// ----------------- Formulare ----------------- //
	
	//$('form ol>li').css('float', 'left');
	//($('form li').hasClass('single')) ?	$('form ol li.single').nextAll("form ol li:nth-child(2n)").css('clear', 'left') : $('form ol li:nth-child(2n+3)').css('clear', 'left'); // Bestimmtes Feld einzeilig darstellen
	
	
	
	
	// ----------------- Produkt - Nach jedem 5ten li, margin geben ----------------- //
	
	$('.separated_list li:nth-child(5n+5):not(:last-child)').css('margin-bottom', '20px');
	
	
	
	
	// ----------------- Mehr lesen Blöcke ----------------- //
	
	$('.mehr').hide(); // Mehr Text verstecken (zB Startseite)
	$('.bg, .mehrlesen').click(function() { // Wenn h2 oder weiter lesen geklickt wird, Inhalte togglen
		var parent = $(this).parent();
		$('.mehr', parent).slideToggle();
		if ($('h2').is('.bg, .bg_open')) {
			$('h2', parent).toggleClass('bg bg_open'); // BG der h2 tauschen
		}
		$('.mehrlesen', parent).toggle();
		
		if($(this).parent().next().attr('class') == 'scrolllist') {
			$(this).parent().next('.scrolllist').toggle();
			
		}
	});
	
	
	
	
	// ----------------- Label in Input darstellen ----------------- //
	
	$('.inline-label').each(function() {
	
		var fID = $(this).attr('id'); // id des Inputs
		var label = $('label[for="'+fID+'"]').hide(); // Entsprechendes Label verstecken
		
		if($(this).val() == '') { 
			$(this).val(label.text()) // Label value, input value zuweisen
			.blur(function() {
				if ($(this).val() == '') { // Wenn leer
					$(this).val(label.text()); // wieder label value zuweisen
				}
			}).click(function(){
				if($(this).val() == label.text()) { 
					$(this).val('') } // bei click inhalt leeren
			})
		}
	});
	

	
	
	// ----------------- Übersichtsplan in Besucherinfo ----------------- //
	

	var haus = $('#lageplan area'); // Die einzelnen Häuser
	var oldText = $('.map h4').html(); // Originaltext "Klicken Sie auf das.."
	var keinHaus = $('.kein_haus').html(); // Wenn keins Haus-Text
	var hausVorb = $('.haus_vorbereitung').text();
	haus.bind('mouseenter mouseleave click', function(event) {
		var hausID = $(event.target).attr('href'); // href-Wert des jeweiligen Hauses holen
		var hausIDid = $(event.target).attr('id'); // id-Wert des jeweiligen Hauses holen
		var hausIDplain = $(event.target).attr('href').replace(/[ /]/g,""); // href-Wert des jeweiligen Hauses holen
		var hausInfo = '.haus'+hausID; // zB haus007 daraus machen

			switch (event.type) {
			  case "mouseenter":
			  
				    if (hausID == '' || ($(hausInfo).length == 0 && hausID.indexOf('0') != -1)) { // Wenn #, kein Haus Text zeigen
				    	$('.map h4').replaceWith(keinHaus);
				    	$(this).css('cursor','auto');
				    	
				    } else if (hausIDplain.indexOf('0') == -1){
				   		$(this).css('cursor','auto');

				    		var alt=$(event.target).attr('alt');
				    		$('.map h4').replaceWith('<h4>'+alt+'</h4>');
							
				    	
				    	
				    	
				    } else { // ansonsten den jeweiligen Titel des Haus zeigen
				    	
				    if (hausIDid != '-1') {
				    	var text = $('.haus_titel', hausInfo).html();
				    	$('.map h4').replaceWith('<h4>'+text+'</h4>');
				    } else {
						$(this).css('cursor','auto');
						var text = $('.haus_titel', hausInfo).html();
						var textneu = text.replace("-1", hausVorb);
				 
						$('.map h4').replaceWith('<h4>'+textneu+'</h4>');
					
					
				}
				    	
				    }
			  break;
			    
			  case "mouseleave":
			    $('.map h4').replaceWith('<h4>'+oldText+'</h4>'); // Standardsatz anzeigen
			   break;
			    
			  case "click":
			  
				  if (hausID == '' || hausIDplain.indexOf('0') != -1 || hausIDid == '-1'){
				  	event.preventDefault();
				  }
			    
			    if ($(hausInfo).length != 0 && hausID != '' && hausIDid != '-1') {
			    	
				    // Klasse für letztes Element toggeln, wenn Hausdetail gezeigt wird			
				    (hausID != '#') ? $('.map').removeClass('last') : $('.map').addClass('last');
				    
				    $('.haus').hide(); // Letztes Haus entfernen
				   
				    if (hausInfo != '.haus#') {
				    	$(hausInfo).show(); // Aktuelles anzeigen
				    }
			    }
			    

			    break;
		
			} // switch
		
		
	});
	
	
	
	
	// ----------------- Mehr-spaltige Listen ----------------- //

	
	$('.four_cols .last').next().addClass('dontend'); // Verhindern dass eine H2 das letzte Element der Spalte ist
	$('.sitemap>li>a').not('.three_cols>li:last-child>a').addClass('dontend');
	$('.three_cols').addClass('clear');

	var items= $('.three_cols').children(); // Anzahl der li's
	var itemsCount = items.length; // Anzahl der li's
	
	var height = 0; // Höhe der Spalten
	
	items.each(function(idx, elem) {
		height = height+$(this).outerHeight(true);
	});
	
	var itemsPerRow = itemsCount/3; // Elemente pro Spalte
	
	if(items.parent().hasClass('sitemap')) {
		height = height/(itemsCount/5);
	} else {
		height = height/(itemsCount/itemsPerRow);		
	}
	
	$('.three_cols').prepend('<div class="last_col"></div>');
	if (itemsCount >4) { // Spalten ab 5 Elemente 	$('.three_cols li h3').addClass('dontend');machen
		$('.three_cols').columnize({ 
			columns : 3,
			overflow : {
				id : ".last_col",
				height : height,
				doneFunc : function(){ // Wenn 3-spaltig und 4-spaltig auf einer Seite, zweite Spalte teilen, wenn erste fertig geteilt
					$('.four_cols').columnize({
						width:170, height : 1020
					});
				}
			}
		});
	}	
	
	$('.column .last:last-child, .column li:last-child ul').css('margin-bottom','0');





	// ----------------- Home > Fertighaus > Dach  ----------------- //


	//var scrollListWidth = 0; // Breite des Scrollbereichs

	$('.scrolllist').hide() // Eigentliche Auflistung verbergen
					.parent().prepend('<div class="scrollnavigation"></div>'); // Container um Scrollbereich

	// Elemente aus der Liste Klonen, floating Klasse entfernen und in Scrollbereichcontainer kopieren
	$('.scrolllist .artikel > img').wrap('<div class="dach_elem"></div>');
	$('.scrolllist .floated_right').addClass('dach_elem');
	$('.scrolllist .artikel').children('.dach_elem, h3').clone().removeClass('floated_right').appendTo('.scrollnavigation');
	
	// Jeweils eine geklonte h3 und img in Container packen		
	$('.scrollnavigation > *:nth-child(2n)').each(function() {
		$(this).prev().andSelf().wrapAll('<div class="scrolllistelement"></div>');
	})
	.parent('.scrolllistelement').each(function() {
		// Jedem Elementcontainer Breite zuweisen, dann Bild vor h3 stellen und absolut positionieren
		$(this).css('width', '200').children('img').prependTo($(this)).css({'position':'absolute', 'bottom':'40px'});
		
		//scrollListWidth = scrollListWidth + $(this).outerWidth(true); // Breite des Containers immer wieder anpassen
	})
	.click(function() { // Wenn Element geklickt wird
		$('.scrolllist').show(); // Liste wieder zeigen
		$('.artikel:not(":last-child")').removeClass('last'); 
		var id = $(this).find('h3').text().toLowerCase(); // Inhalt der h3 holen, da der Wert der id des jeweiligen Listenelements entspricht
		var ziel = '#'+id.replace(/[ -./]/g,""); // id zusammen bauen und .,- und / entfernen
		var targetOffset = $(ziel).offset().top; // Abstand des Element nach oben berechnen
		$('html, body').animate({scrollTop: targetOffset}, 400, function() { // Zum jeweiligen Element scrollen
			location.hash = ziel;
		});
	}) // click
	
	// Wenn fertig zusammengebaut, alle in Container packen und finale Breite zuweisen
	.wrapAll('<div class="scrollcontainer clear"></div>').parent().css('width', $('.scrolllistelement').length *220);
	

	
	// ----------------- Imageslider  ----------------- //
		
	var imgContainer = $('.teaser_image');
	///var slides = $('.teaser_image img'); // Die einzelnen Slides	
	var slides = $('.teaser_image .slide'); // Die einzelnen Slides
	var anzahlSlides = slides.length +2; // Anzahl der Slides + Klon von erstem und letztem Slide
	var aktuellesBild = 1; // Zweites Slide zuerst, weil erstes ein Klon vom letzten ist
	var cur = 0;
	
	
	if (anzahlSlides > 3) {
	
	if (imgContainer.hasClass('controls')) {
		var breiteContainer = 367;
		
	} else {
		var breiteContainer = 998;
	}
	
	
	
	imgContainer.css({'overflow':'hidden', 'width':breiteContainer}).wrap("<div class='sliderContainer'></div>") // Breite und overflow ändern, wenn js aktiviert
	.children(slides).css({'margin':'0', 'max-width':breiteContainer}) // Standard CSS, wenn kein js, zurücksetzen
	
	
	if (imgContainer.hasClass('controls')) {
	$('.sliderContainer').css({'width': breiteContainer, 'margin' : '0 auto'}).append('<span class="pfeil" id="pfeilLinks">Links</span><span class="pfeil" id="pfeilRechts">Rechts</span>').parent().hide();
	
	$('.innenansicht').click(function() {
		$('.sliderContainer').parent().slideToggle();
							
		return false;
		
	}).one('click', function(){
		positionPager();
	});
	
	}
	
	
	
	$('.pfeil').bind('click', function(){
		clearInterval(start_slideshow); // Sobald auf einen Pfeil geklickt wird, automatische Slideshow stoppen
		slidesContainer.stop('true','true'); // Fehlerhafte Darstellung bei zuvielem Klicken unterbinden
	
		if($(this).attr("id") == "pfeilLinks") { aktuellesBild--; } // Nummer aktueller Slide verringern
	
		if($(this).attr("id") == "pfeilRechts") { aktuellesBild++; } // Nummer aktueller Slide erhöhen
		
		bilderBlaettern();
	});
	
	
	slides.wrapAll("<div id='slidesContainer'></div>"); // Container für Slides erstellen
	
	var slidesContainer = $('#slidesContainer'); // Slidecontainer
	
	slidesContainer.css({ 
	'width': breiteContainer * anzahlSlides, // Slidecontainer ist so breite wie alle Slides zusammen
	'marginLeft':breiteContainer*(-1)}); // Zweites Slide zuerst anzeigen, weil erstes ein Klon vom letzten ist
	
	slides.first().addClass('erstes').clone().appendTo(slidesContainer); // Erstes und letztes Slide klonen und an Anfang bzw. Ende des
	slides.last().addClass('letztes').clone().prependTo(slidesContainer); // Containers stellen, damit endloses Sliden möglich ist
	
	
	imgContainer.parent().prepend('<ul class="curImage clear"></ul>');
	
	for (i = 0; i < slides.length; i++) {
		cur = i+1;
		$(".curImage").append("<li>" + cur + "</li>");
	 }
	 
	 $(".curImage li").click(function() {
		var index = $(".curImage li").index(this);
	 aktuellesBild = index+1;
	 bilderBlaettern();
	 });
	 
	 positionPager();

	 
	 var start_slideshow = setInterval( slideshow, 4000 ); // Alles vier Sekunden blättern
	 
	 }
	 
	 function positionPager() {
	 
	 var curImageWidth = $(".curImage").outerWidth(true);
	 var left = (breiteContainer/2)- (curImageWidth/2);
	 $(".curImage").css('left', left).children('li:first-child').addClass('current');
	 }

	function bilderBlaettern() {
		
		$(".curImage li").each(function(idx, ele) {
		
			(idx+1 == aktuellesBild) ? $(ele).addClass('current') : $(ele).removeClass('current');
			
			if (aktuellesBild == anzahlSlides-1) {
				$(".curImage li:first-child").addClass('current');
			}
			
			if(aktuellesBild == 0) { // Wenn beim ersten Slide (Klon vom letzten), auf Original springen
				$(".curImage li:last-child").addClass('current');
			}
		});
		
		slidesContainer.animate({'marginLeft':breiteContainer*(-aktuellesBild)},function(){ // Slidecontainer verschieben
		
			if(aktuellesBild == anzahlSlides-1) { // Wenn bei letztem Slide (Klon vom ersten), auf Original springen
				slidesContainer.css({'marginLeft':breiteContainer*(-1)});	
				aktuellesBild = 1;
			} 
		
			if(aktuellesBild == 0) { // Wenn beim ersten Slide (Klon vom letzten), auf Original springen
				slidesContainer.css({'marginLeft':breiteContainer*(anzahlSlides-2)*(-1)});	
				aktuellesBild =  anzahlSlides-2;
			}
		});	
		

	
	}
		
	function slideshow() { // Blättern starten + Nummer aktuelles Bild erhöhen
		aktuellesBild++;
		bilderBlaettern();
	}
	
	
	
	
	// ----------------- jCarousel (Bilderbuch)  ----------------- //
	
	$('#bilderbuch').jcarousel({
		scroll:7, // Wieviele Elemente sollen gescrollt werden
		start:parseInt(document.getElementById('SCval').value), // Wo soll das Carousel beginnen,
		wrap:"both",
	    itemVisibleOutCallback: {onAfterAnimation: function(carousel, item, i, state, evt) { 
	    	carousel.remove(i); 
	    	
	    	}        
	    },
	    
	    itemLoadCallback: mycarousel_itemLoadCallback
	});
	
	showArtikel(); // Click Event binden
		var URL = document.location.href;	
		
		if (URL.indexOf("bilderbuch") != -1) {
		
	$('.pfeil').bind('click', function(event) {
	
		event.preventDefault();
		
		if ($(this).attr('id') == 'pfeilLinks') {
		
			if($('.carVisible:first').hasClass('activeLi')) { carGlobal.prev(); }
			
			$('.activeLi').prev().addClass('activeLi');
			$('.activeLi').next().removeClass('activeLi');
			
			var id = $('.activeLi').children().children('img').attr('id');
			bildLaden(id);

			
		} else {
			
			if($('.carVisible:last').hasClass('activeLi')) { carGlobal.next(); }
			
			$('.activeLi').next().addClass('activeLi');
			$('.activeLi').prev().removeClass('activeLi');
			var id = $('.activeLi').children().children('img').attr('id');
			bildLaden(id);
			
			
		}
		
		return false;
	});	
	}

}); // dom ready




// ----------------- jCarousel - CallBack ----------------- //

function mycarousel_itemLoadCallback(carousel, state) {
    
    // Checken ob Caoursel schon vorhanden
    if (carousel.has(carousel.first, carousel.last)) {
        return;
    }

	// Daten holen (aktuelles erstes und letztes Bild+ XML)
    jQuery.get(
           'php/dynamic_ajax_php.php'+document.getElementById('bbparam').value, // Datei aus der das Array mit den Daten (bildpfad, id) kommt
        {
            first: carousel.first,
            last: carousel.last
        },
        function(xml) {
            mycarousel_itemAddCallback(carousel, carousel.first, carousel.last, xml);
            addCount(xml);
            
            getCurrent(carousel);
            bildLaden($('.carVisible:first img').attr('id'));
            	
        },
        'xml'
    );
};

function mycarousel_itemAddCallback(carousel, first, last, xml) {
    // Breite des Carousel setzen
    var total = parseInt(jQuery('total', xml).text());
    carousel.size(total);

	// Aus dem XML jedes Bild holen und ans Carousel hängen
    jQuery('image', xml).each(function(i) {
    var id = jQuery(this).attr('id');
        carousel.add(first + i, mycarousel_getItemHTML(jQuery(this).text(),id));
    });
};


// Aus XML-Daten, HTML zusammenbauen
function mycarousel_getItemHTML(url,id, idx, total) {
    return '<div class="item_inner"><img src="' + url + '" width="82" height="55" alt="" id="' + id +'"  class="carThumb"/><div class="imgcount"></div></div>';
};

// Anzahlanzeige in Thumb erstellen
function addCount(xml) {
	 var total = parseInt(jQuery('total', xml).text());
	
	$('.jcarousel-item .item_inner ').hover(function() {
		$(this).children('.imgcount').html($(this).parent().attr('jcarouselindex')+"/"+total).slideToggle();
	});
	
	$('.jcarousel-item').corner('5px');
}

// Passende Haus- bzw- Ausstellerdetails bei Click anzeigen
function showArtikel() {
		
	$('.jcarousel-item').live('click', function(){  
	
		var id = $('img', $(this)).attr('id');
		$('.jcarousel-item').removeClass('activeLi');	
		$(this).addClass('activeLi');
		bildLaden(id);
		
		return false 
	});

}

function bildLaden(id) {
	$('#hausinfo').load('php/data.php', {id:id}, function(response, status, xhr) { // Haus- bzw- Ausstellerdetail
	  if (status == "error") {
	    var msg = "Die Daten konnten leider nicht geladen werden: ";
	    $("#hausinfo").html(msg + xhr.status + " " + xhr.statusText);
	  }
	});
}



function getCurrent(carousel) {


	$('.jcarousel-list li').each(function() {
		if ($(this).has('.item_inner').length) {
			$(this).addClass('carVisible');
			
			$('.carVisible:first').addClass('activeLi');
			$('.carVisible:last-child').removeClass('activeLi');
		}
	})
	
	carGlobal = carousel;
	
}	



