var jsonUrl = "http://www.bmwi.de/BMWi/Navigation/Service/Suche/json.html";
var searchtermLength = 3;
var allResultsUrl = "http://www.bmwi.de/BMWi/Navigation/Service/suche.html";

function bmwiUsage(jsonUrlCms,searchtermLengthCMS,allResultsUrlCms){
	// set path to json url
	jsonUrl = jsonUrlCms;
	searchtermLength = searchtermLengthCMS;
	allResultsUrl = allResultsUrlCms;
}			

function getFlashVersion() {
	var playerVersion = swfobject.getFlashPlayerVersion(); // returns a JavaScript object
	var output = "You have Flash player " + playerVersion.major + "." + playerVersion.minor + "." + playerVersion.release + " installed";
}


$(document).ready(function(){
	
	$("body").addClass("javascriptTrue");
	

	// initialize treeeview
	if($(".tabContent #sitemap").is("div")) {
		$(".tabContent #sitemap > ul").treeview({
			persist: "location",
			collapsed: true,
			unique: true
		});
	}
					
	
	// tabnavi js support
	if($(".tabNavi").is("ul")){
		
		$(".tabNavi > li.elem").hover(
			function () {
				if($("#searchResults").css("display")!="block") {	
					$(".tabNavi li").removeClass("over");	  
					$(this).addClass("over");
					$(this).addClass("tab");
				}
				return false;
			}, function() {
				if($("#searchResults").css("display")!="block") {	
					$(".tabNavi li").removeClass("over");
				}
				$(".tabNavi li:first").addClass("over");
				$(".tabNavi li:first").addClass("tab");
		});
	}
	
	
//	// initialize scrollable 
//	$(".introtext p:last-child").append("<br/><br/><br/>")
//	$(".introtext").wrap("<div class=\"scrollableListContainerTop\" />");
//	$(".introtext").addClass("introitem");
//	$(".introtext").removeClass("introtext");
//	if ($('.scrollableListContainerTop').length > 0) {
//
//		$(".scrollableListContainerTop").after('<div class="scrollableListContainerActions"><a class="prevPage browse up"></a><a class="nextPage browse down"></a></div>');
//		
//		$(".scrollableListContainerTop").scrollable({ 
//			vertical:true,  
//			size: 1
//		// use mousewheel plugin 
//		}).mousewheel();
//	}

	if ($(".searchdetail").is("div")) {
	
		/* Alle Checkboxen in searchdetail aus/abwaehlen: */
		$(".searchdetail input:checkbox").bind("click change", function(e){

			var item = $(e.target)
			var status = item.attr('checked');
			var changeAll = false;
			var changeGroup = false;
			
			//check if "All" was triggered
			if (item.attr("id") == "searchAllTopics") {
				var inputGroupName = "searchTopic";
				changeAll = true;
			}
			else if (item.attr("id") == "searchAllDocumentTypes") {
				var inputGroupName = "searchDocumentType";
				changeAll = true;
			}
			//else test group button state
			else {
				//if false uncheck "All" 
				if (item.attr('checked') == false) {
					changeGroup = true;
					var changeAllState = false;
					
				//else test all group buttons then check/uncheck "All" 
				} else {
					changeGroup = true;
					var changeAllState = true;
					$(".searchdetail input[name='"+item.attr("name")+"']").each( function(index) {
						if($(this).attr('checked') == false){
							changeAllState = false;
							return false;
						}
			        });
					
				}
			}
			
			//toggle the relating group
			if(changeAll){
				$(".searchdetail input[name='"+inputGroupName+"']").each(function(index){
					$(this).attr('checked', status);
				});
			} 
			
			//toggle the relating "All" checkbox
			else if(changeGroup) {
				
				switch (item.attr("name")) {
					case "searchTopic":
						$(".searchdetail input#searchAllTopics").attr('checked', changeAllState);
						break;
					case "searchDocumentType":
						$(".searchdetail input#searchAllDocumentTypes").attr('checked', changeAllState);
						break;
				}
			}
			
		});
		
	}	
	
//#######################dynamische Suche#######################//
			
	
	var rsltsExpose = $("#searchResults").expose({api:true,lazy:true, color: '#6d707a', onBeforeClose: function(event) { $("#searchResults").fadeOut(250); clearSearchInput(); }});

	$("#searchInput").attr({ autocomplete:"off" });

	//query after change
	$("#searchInput").bind("keyup", function() { 
		getResult();
	});
				

	function getResult(){
		var searchterm=$("#searchInput").attr("value");
		if(searchterm.length >= searchtermLength){
			$.getJSON(jsonUrl+"?searchText="+escape(searchterm)+"&jsoncallback=?",{searchterm:escape(searchterm)},handleResult);
		}
		window.clearTimeout(true);
	}

	function handleResult(result) {
		var rslts = $("#searchResults");
		var searchterm=$("#searchInput").attr("value");
		var rsltString = "";
		var maxItems = 6;
		
		rsltString = ("");
		
		//check result length
		if(result.items.length > 0){
		
			//rsltString  = '<h3>BMWi Hauptangebot: '+ result.items.length +' <a href="#" id="searchResultClose"><\/a><\/h3>';
			rsltString  = '<h3>BMWi Hauptangebot <a href="#" id="searchResultClose"><\/a><\/h3>';
			rsltString += '<div class="listContainer clearfix"><ul class="resultList cf">';
		
			//parse results
			$.each(result.items, function(i,item){
				
				if (item.media.m != "") {
					rsltString += '<li class="clearfix">';
					rsltString += '<a class="imgLink" href="#"><img src="' + item.media.m + '" alt="" width="54" \/><\/a>';
				} else {
					rsltString += '<li class="indent clearfix">';
				}
				rsltString += '<h4><a href="'+item.link+'">'+item.title+'<\/a><\/h4>';
				rsltString += '<p>'+item.description+'<\/p>';
				rsltString += '<\/li>';
				if (i==maxItems) return false;
				
			});
			
			rsltString += '<\/ul>';
			rsltString += '<a href="'+allResultsUrl+'?searchText='+searchterm+'" class="linkIntern">Alle Ergebnisse<\/a><\/div>';
			
			rslts.html(rsltString);
		
		} else {
			rsltString = ('<h3>BMWi Hauptangebot <a href="#" id="searchResultClose"><\/a><\/h3>');
			rsltString += ('<div class="listContainer clearfix">');
			rsltString += ('<p class="emptyResult">');
			rsltString += ('<a href="'+allResultsUrl+'?searchText='+searchterm+'">Keine Ergebnisvorschl&auml;ge f&uuml;r diesen Suchbegriff, versuchen Sie es mit der Volltextsuche<\/a>');
			rsltString += ('<\/p>');
			rsltString += ('<\/div>');
			rslts.html(rsltString);
		}
		
		$("#searchResultClose").click(function() {
			$("#searchResults").fadeOut(250);
			clearSearchInput();
			rsltsExpose.close();
			return false;
		});
		//show results
		if(rslts.css("display")!="block"){
			rslts.fadeIn(250);
			rsltsExpose.load();
		}
	}
	
	function clearSearchInput(){
		$("#searchInput").val("");
	}

	var parent = $('#redirectId_355694').parent();               
	var grandParent = $('#redirectId_355694').parent().parent();  
	var setupClasses = $(grandParent).parent();
	var contentToLoad = $('div.redirectId_355694').html();


	if($('#redirectId_355694').length > 0) {
	   $(setupClasses).addClass('energySearchForm').removeClass('visitenkarteForm big topBox');
	   $(parent).hide();	
	   $(grandParent).prepend('<ul id="selStatClickMeUl"><li id="selAllEData">Alle Energiedaten</li></ul><ul id="enStatDataList"><!-- CONTENT GOES HERE --></ul>'); 

	   $('#selAllEData').click(function(){                                                                                                                              
			$('#enStatDataList').html(contentToLoad);
			$('#enStatDataList').slideToggle("normal");
	   });                                                                                                                                                              
	}   		

//Bild Zoom im Contentbereich

$(".imgright").addClass("toZoom");	
$(".float--right").addClass("toZoom");
	
	if ($(".zoomLink").is('a')) {
	
		$(".zoomLink").click(function(){							// If element with class zoomLink is clicked
			var daImg = $(this).parent().parent().children("img"); 	// Find image two parents above the Zoom-Link
			var origWidth = daImg.attr('width');					// Get width from the small image
			var origHeight = daImg.attr('height');					// Get height from the small image
			var relFak = ((480)/(origWidth));						// Calculate the relationship between the full width an the original small width
			var origSrc = daImg.attr('src');						// Save the original imagesource
			var daLink = $(this).find("img");
			var relFakBack = ((origWidth)/(164));
			var activElem =$(this).parent().parent();

		if( !daImg.hasClass("isZoomed") ) {						//Check if the image is already zoomed and continue only if not
				var newHeight = ((origHeight) * (relFak));			//Calculate the new height with the original height and the pre-calculated ralation
				activElem.animate({							//Animate the element with the class inlineImage to the full width
					width: "482"
				}, 1500 )											// How fast the animation should take place
				daImg.attr('src', $(this).attr('href') );			//Set the new source for the bigger image
				daImg.animate( { width: "480", height: newHeight }, 1490 );	//Animate the image inself
				daImg.addClass("isZoomed"),							//Add a class to mark the image zoomed.
				
				daLink.attr('src', '/bmwa/images/bmwi/de/zoomOut.gif');	//Switch backgroundimage for the link
				//daLink.animate( { left: "140px" }, 1490 );			//Change position of the link
				
			} else {
		//	alert(origWidth);
				daImg.removeClass("isZoomed");
				// Bilder verkleinern
				activElem.animate({ width: "164" }, 1150 )						//Animate the element with the class inlineImage to the full width
		//	alert(origWidth);
				var newHeight = ((origHeight) / (relFakBack));
		//	alert(newHeight);
				daLink.attr('src', '/bmwa/images/bmwi/de/zoomIn.gif');
				//daLink.animate( { left: "0px" }, 1100 );
				daImg.attr('src', $(this).attr(origSrc) );
				daImg.animate( { width: "164", height: newHeight }, 1000 );
				
				// origWidth + origHeight +origSrc wieder herstellen
				// Lupe von - zu +
				
			};
		return false;
		});
	}
	
//Fotoreihe Marginalspalte
	$(function(){
		
		$(".fotoreihe").each( function(i) {
		
			if($(this).is("div")) {
				$(this).find("li").addClass("showAllImg");
				$(this).carousel( { 
					animSpeed: "slow", 
					siteCounter: "true",
					btnsPosition: "inside",
					nextBtnInsert: "prependTo",
					prevBtnInsert: "prependTo",		
					nextBtn:'<a role="button"><span class="next">vor</span></a>',
					prevBtn:'<a role="button"><span class="previous">zur&uuml;ck</span></a>',			
					animSpeed:"fast"
				} );
			}
		
		});

		
    });

//Lightbox Aufruf

	
if($(".lightboxLink").is("div")) {
	if($(".lightboxLink").parent().is("td")) {
		$(".lightboxLink").parent().wrapInner("<div class='lightboxBorder'></div>");
		$(".lightboxLink a").prepend("vergrößern");
	}
	/* Lightbox aufrufen*/
	 var bild = "Bild";
	 var von = "von";
	 if($("html").attr("lang")=="en") {
		von = "of";
		bild = "Images";
	 }
	var relAttr = "0";
	jQuery.each($(".lightboxLink a"), function(i, val) {
		if(relAttr != $(val).attr("rel") || relAttr =="0") {			
			
			$(".lightboxLink a[rel='" + $(val).attr("rel") + "']").lightBox({
				 fixedNavigation: true,
				 overlayOpacity: 0.7,
				 activeImage: '',
				 imageLoading: '/bmwa/images/bmwi/loading.gif',	
				 imageBtnNext: '/bmwa/images/bmwi/de/btn_next.gif',
				 imageBtnPrev: '/bmwa/images/bmwi/de/btn_prev.gif',
				 imageTextClose: 'schliessen x',
				 txtImage: bild,
				 txtOf: von
			 });

			$(".lightboxLink a[rel='" + $(val).attr("rel") + "']").each(function() {
				$(this).click( function() {
					 $("#lightbox-container-image #lightbox-nav-btnPrev").after("<div id='lightbox-image-details-currentNumber'></div>");
					 $("#lightbox-image-details #lightbox-image-details-currentNumber").remove();
				});
			 });		
		}
		relAttr = $(val).attr("rel");
	});
	 


}


});


