/*
	Slimbox v2.04 - The ultimate lightweight Lightbox clone for jQuery
	(c) 2007-2010 Christophe Beyls <http://www.digitalia.be>
	MIT-style license.
*/
(function(w){var E=w(window),u,f,F=-1,n,x,D,v,y,L,r,m=!window.XMLHttpRequest,s=[],l=document.documentElement,k={},t=new Image(),J=new Image(),H,a,g,p,I,d,G,c,A,K;w(function(){w("body").append(w([H=w('<div id="lbOverlay" />')[0],a=w('<div id="lbCenter" />')[0],G=w('<div id="lbBottomContainer" />')[0]]).css("display","none"));g=w('<div id="lbImage" />').appendTo(a).append(p=w('<div style="position: relative;" />').append([I=w('<a id="lbPrevLink" href="#" />').click(B)[0],d=w('<a id="lbNextLink" href="#" />').click(e)[0]])[0])[0];c=w('<div id="lbBottom" />').appendTo(G).append([w('<a id="lbCloseLink" href="#" />').add(H).click(C)[0],A=w('<div id="lbCaption" />')[0],K=w('<div id="lbNumber" />')[0],w('<div style="clear: both;" />')[0]])[0]});w.slimbox=function(O,N,M){u=w.extend({loop:false,overlayOpacity:0.8,overlayFadeDuration:400,resizeDuration:400,resizeEasing:"swing",initialWidth:250,initialHeight:250,imageFadeDuration:400,captionAnimationDuration:400,counterText:"Image {x} of {y}",closeKeys:[27,88,67],previousKeys:[37,80],nextKeys:[39,78]},M);if(typeof O=="string"){O=[[O,N]];N=0}y=E.scrollTop()+(E.height()/2);L=u.initialWidth;r=u.initialHeight;w(a).css({top:Math.max(0,y-(r/2)),width:L,height:r,marginLeft:-L/2}).show();v=m||(H.currentStyle&&(H.currentStyle.position!="fixed"));if(v){H.style.position="absolute"}w(H).css("opacity",u.overlayOpacity).fadeIn(u.overlayFadeDuration);z();j(1);f=O;u.loop=u.loop&&(f.length>1);return b(N)};w.fn.slimbox=function(M,P,O){P=P||function(Q){return[Q.href,Q.title]};O=O||function(){return true};var N=this;return N.unbind("click").click(function(){var S=this,U=0,T,Q=0,R;T=w.grep(N,function(W,V){return O.call(S,W,V)});for(R=T.length;Q<R;++Q){if(T[Q]==S){U=Q}T[Q]=P(T[Q],Q)}return w.slimbox(T,U,M)})};function z(){var N=E.scrollLeft(),M=E.width();w([a,G]).css("left",N+(M/2));if(v){w(H).css({left:N,top:E.scrollTop(),width:M,height:E.height()})}}function j(M){if(M){w("object").add(m?"select":"embed").each(function(O,P){s[O]=[P,P.style.visibility];P.style.visibility="hidden"})}else{w.each(s,function(O,P){P[0].style.visibility=P[1]});s=[]}var N=M?"bind":"unbind";E[N]("scroll resize",z);w(document)[N]("keydown",o)}function o(O){var N=O.keyCode,M=w.inArray;return(M(N,u.closeKeys)>=0)?C():(M(N,u.nextKeys)>=0)?e():(M(N,u.previousKeys)>=0)?B():false}function B(){return b(x)}function e(){return b(D)}function b(M){if(M>=0){F=M;n=f[F][0];x=(F||(u.loop?f.length:0))-1;D=((F+1)%f.length)||(u.loop?0:-1);q();a.className="lbLoading";k=new Image();k.onload=i;k.src=n}return false}function i(){a.className="";w(g).css({backgroundImage:"url("+n+")",visibility:"hidden",display:""});w(p).width(k.width);w([p,I,d]).height(k.height);w(A).html(f[F][1]||"");w(K).html((((f.length>1)&&u.counterText)||"").replace(/{x}/,F+1).replace(/{y}/,f.length));if(x>=0){t.src=f[x][0]}if(D>=0){J.src=f[D][0]}L=g.offsetWidth;r=g.offsetHeight;var M=Math.max(0,y-(r/2));if(a.offsetHeight!=r){w(a).animate({height:r,top:M},u.resizeDuration,u.resizeEasing)}if(a.offsetWidth!=L){w(a).animate({width:L,marginLeft:-L/2},u.resizeDuration,u.resizeEasing)}w(a).queue(function(){w(G).css({width:L,top:M+r,marginLeft:-L/2,visibility:"hidden",display:""});w(g).css({display:"none",visibility:"",opacity:""}).fadeIn(u.imageFadeDuration,h)})}function h(){if(x>=0){w(I).show()}if(D>=0){w(d).show()}w(c).css("marginTop",-c.offsetHeight).animate({marginTop:0},u.captionAnimationDuration);G.style.visibility=""}function q(){k.onload=null;k.src=t.src=J.src=n;w([a,g,c]).stop(true);w([I,d,g,G]).hide()}function C(){if(F>=0){q();F=x=D=-1;w(a).hide();w(H).stop().fadeOut(u.overlayFadeDuration,j)}return false}})(jQuery);


// AUTOLOAD CODE BLOCK (MAY BE CHANGED OR REMOVED)
if (!/android|iphone|ipod|series60|symbian|windows ce|blackberry/i.test(navigator.userAgent)) {
	jQuery(function($) {
				
	  jQuery("a[rel^='lightbox']").slimbox({
		  /* Put custom options here  css({'border':'dotted 1px blue'}).*/
		  // loop:true,
		  counterText:"Bild {x} von {y}",
		  closeKeys:[27,88,83], 	//27:escape, 88:x, 67:c, 83:s
		  previousKeys:[37,90],		//37:left arrow, 80:p, 90:z
		  nextKeys:[39,87]}, null, 	//39:right arrow, 78:n, 87:w
		  function(el) {
			  return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
	  });
	});
}

/* JQuery URL Parser
 * Version 1.0
 * Author: Mark Perkins
 * For full documentation and more go to http://projects.allmarkedup.com/jquery_url_parser/
 */
jQuery.url=function(){var segments={};var parsed={};var options={url:window.location,strictMode:false,key:["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],q:{name:"queryKey",parser:/(?:^|&)([^&=]*)=?([^&]*)/g},parser:{strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}};var parseUri=function(){str=decodeURI(options.url);var m=options.parser[options.strictMode?"strict":"loose"].exec(str);var uri={};var i=14;while(i--){uri[options.key[i]]=m[i]||""}uri[options.q.name]={};uri[options.key[12]].replace(options.q.parser,function($0,$1,$2){if($1){uri[options.q.name][$1]=$2}});return uri};var key=function(key){if(!parsed.length){setUp()}if(key=="base"){if(parsed.port!==null&&parsed.port!==""){return parsed.protocol+"://"+parsed.host+":"+parsed.port+"/"}else{return parsed.protocol+"://"+parsed.host+"/"}}return(parsed[key]==="")?null:parsed[key]};var param=function(item){if(!parsed.length){setUp()}return(parsed.queryKey[item]===null)?null:parsed.queryKey[item]};var setUp=function(){parsed=parseUri();getSegments()};var getSegments=function(){var p=parsed.path;segments=[];segments=parsed.path.length==1?{}:(p.charAt(p.length-1)=="/"?p.substring(1,p.length-1):path=p.substring(1)).split("/")};return{setMode:function(mode){strictMode=mode=="strict"?true:false;return this},setUrl:function(newUri){options.url=newUri===undefined?window.location:newUri;setUp();return this},segment:function(pos){if(!parsed.length){setUp()}if(pos===undefined){return segments.length}return(segments[pos]===""||segments[pos]===undefined)?null:segments[pos]},attr:key,param:param}}();

// get URL query string for styleswitcher
jQuery.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
	  // console.info(hash, 'hash');
    }
    return vars;
  },
  getUrlVar: function(name){	  
	// console.info(jQuery.getUrlVars()[name], 'jQuery.getUrlVars()[name]');
	 
	if ( typeof jQuery.getUrlVars()[name] == 'undefined' )
	{
	  return '';
	}
    return jQuery.getUrlVars()[name];
  }
});

// cookie functions http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = '; expires='+date.toGMTString();
	}
	else var expires = '';
	document.cookie = name+'='+value+expires+'; path=/';
}
function readCookie(name)
{
	var nameEQ = name + '=';
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function eraseCookie(name)
{
	createCookie(name,'',-1);
}
// /cookie functions


 function create_icon(icon)
 {
	return '<img src="layout/img/'+icon+'.gif" class="link-icon" />';
 }

	
/* ---- START ----------------------- */	
	
	jQuery.noConflict();		
	jQuery(document).ready(function(){	
	
	// verlag kurzbeschreibung	
	var kbsLink = '<p class="kbs"><a class="showhidelink" title="Kurzbeschreibung anzeigen">[+] Kurzbeschreibung</a></p>';
	
	jQuery('h3.kurzbeschreibung').replaceWith(kbsLink); 	
	jQuery('div.kurzbeschreibung').hide(); 	
	
	jQuery('.kbs a.showhidelink').css({'cursor':'ponter'}).click(function(){	
		// $(this).parents("p").next("div").slideToggle("slow");
		jQuery(this).parents('p').next('div').slideToggle();
		
		if(jQuery(this).text() == '[+] Kurzbeschreibung')
		{	
			jQuery(this).attr({title:'Kurzbeschreibung ausblenden'});
			jQuery(this).text('[-] Kurzbeschreibung');	
		}
		else
		{	
			jQuery(this).attr({title:'Kurzbeschreibung anzeigen'});
			jQuery(this).text('[+] Kurzbeschreibung');
		}
	}); 
															  
	// open external links with target _blank	
	jQuery('a[href^="http"], a[href$=".pdf"], a[href="/adressen/"]').click(function(){  
		console.info('TEST');																	  
		this.target = '_blank';
	});

	
	// do not cache relaunch.css during development
	/*var numRand = Math.floor(Math.random()*100001)
	jQuery('link[href^=layout/bioland/relaunch.css]').attr('href', 'layout/bioland/relaunch.css?foo='+ numRand);
	*/
	jQuery('.news-single-backlink a, .news-backlink a, .backlink').click(function () {
		// alert('Zurück');
		window.history.back();
		return false;
	});	
    // if backlinktext no « zurück, remove history.back
	if (jQuery('.news-single-backlink a').text().length > 9 )
	{
		jQuery('.news-single-backlink a').unbind('click');
	}
	
	jQuery('a:has(img)').addClass('img');
	
	jQuery('.column_2 tr, .column_3 tr, .column_4 tr, .books tr').find('th:eq(0)').addClass('th-1'); 
	jQuery('.column_2 tr, .column_3 tr, .column_4 tr, .books tr').find('th:eq(1)').addClass('th-2'); 	
	jQuery('.column_3 tr, .column-4 tr, .books tr').find('th:eq(2)').addClass('th-3'); 	
	jQuery('.column_4 tr').find('th:eq(3)').addClass('th-4'); 
	jQuery('.column_2 tr, .column_3 tr, .column_4 tr, .books tr').find('td:eq(0)').addClass('td-1'); 
	jQuery('.column_2 tr, .column_3 tr, .column_4 tr, .books tr').find('td:eq(1)').addClass('td-2'); 	
	jQuery('.column_3 tr, .column-4 tr, .books tr').find('td:eq(2)').addClass('td-3'); 	
	jQuery('.column_4 tr').find('td:eq(3)').addClass('td-4'); 
	jQuery('.books').find('tr:last').addClass('tr-last');

	
	/*
	Use larger icons for linklist - sehr schwierig zu formatieren
	jQuery('a[href$=.doc]').not('[class=img]').parents('ul').not('[class=linklist]').append(create_icon('doc'));
	jQuery('a[href*=.pdf], a[href*=:PDF]').not('[class=img]').parents('ul').not('[class=linklist]').append(create_icon('pdf'));
	
	jQuery('.linklist a[href$=.doc]').append(create_icon('doc_32'));
	jQuery('.linklist a[href*=.pdf], a[href*=:PDF]').append(create_icon('pdf_32'));
	*/
	
	jQuery('a[href$=".doc"]').not('[class=img]').append(create_icon('doc')).addClass('doc');
	jQuery('a[href$=".pdf"], a[href$=":PDF"]').not('[class=img]').append(create_icon('pdf')).addClass('pdf');
	jQuery('a:contains("["), a:contains("»")').addClass('jquery-simple-link');
	
	
	// if there follows a , or a . or a ) the link, img will get class link-icon2
    // IE has it's own html() 
	jQuery('p a img.link-icon').parents('p').each(function(){
		// alert($(this).html());
        var expr = /link-icon([^>]*)><\/a>([,\.\)]{1})/gi;
		var repl = 'link-icon2$1></a>$2';
		jQuery(this).html(jQuery(this).html().replace(expr,repl));	
	});	
									
									
		// delete cookie after relaunch
		var c = readCookie('css');	
		if (c) 
		{
			 eraseCookie('css')
		}

		// image transfer from the left to the right
		if(	! jQuery('#RechteSpalte').length )
		{
			jQuery('#page').append('<div id="RechteSpalte"></div>');
		}
		if( ! jQuery('#RechteSpalteBox').length ) 
		{
			jQuery('#LinkeSpalte .csc-textpic').clone().appendTo('#RechteSpalte');
			jQuery('#LinkeSpalte .csc-textpic').remove();
		} 
		else
		{			
			jQuery('#LinkeSpalte .csc-textpic').remove();
		}
		
		// transfer to typoscript
		var dir = jQuery.url.attr('directory');
		var splitDir = dir.split('/');
		var currentDir = splitDir[1] ;
		if ( currentDir == '') currentDir  = 'bioland'
		// console.info(dir, 'dir');
		// console.info(currentDir);
		jQuery('#mainmenu li').find('a[href^='+currentDir+']').parent().addClass('current');
		
		if ( currentDir == 'verlag' || currentDir == 'wissen' || currentDir == 'presse' )
		{
			jQuery('#submenu').addClass('submenu-right');
		}
		
		jQuery('#LinkeSpalte :header:first').addClass('jquery-firstHeader');
		jQuery('#RechteSpalte :header:first').addClass('jquery-firstHeader');		
		jQuery('.infobox :header:first').addClass('jquery-firstHeader');		
		jQuery('td :header:first').addClass('jquery-firstHeader');
		
		jQuery('.infobox .linklist:last').css({'margin-bottom':'6px'});
		
		jQuery('#RechteSpalte p:has(img)').addClass('p-image');
		
		jQuery('#RechteSpalteBox').attr('id','RechteSpalte');
		
		  var searchBox = jQuery('#qs input.suchfeld');
		  var searchBoxDefault = 'SUCHE';
		  searchBox.val(searchBoxDefault).css({'color':'#777'});
		  //Searchbox show/hide default text if needed
		  searchBox.focus(function(){
			  if(jQuery(this).val() == searchBoxDefault )  jQuery(this).val('').css({'color':'#333'}) ;
		  });
		  searchBox.blur(function(){
			  if(jQuery(this).val() == '') jQuery(this).val(searchBoxDefault).css({'color':'#777'});
		  });		
	
	

			
	// typo3 helper: if the anchor is on the same page do not reload
	jQuery('#maincontent a[href*=#]').click(function(){	
		// global var url_path of the current page				
		var url_path = jQuery.url.attr('path');									 
		var link_href = jQuery(this).attr('href');
		var link_path = jQuery.url.setUrl(link_href).attr('path');
		// reset jQuery.url
		jQuery.url.setUrl(window.location);
		// console.log('url_path: %s, link_path: %s',url_path, link_path );
		if(url_path == link_path) {
		  // go to the anchor
		 location.href = link_href;
		 return false;
		}				
	});	
									
									
	var path = 'http://www.bioland.de/kunden/einkauf/baecker/plz/';								
	var html = '<p class="float-right"><span>Weitere Postleitzahlenbereiche:</span> ' +       
	'<select name="redirect" onChange="location.href=this.options[this.selectedIndex].value;">' +
		'<option selected>PLZ-Bereich&nbsp;</option>' +
		'<option value="'+path+'00-29.html">PLZ-Bereich 00 - 29999</option>' +
		'<option value="'+path+'30-49.html">PLZ-Bereich 30 - 49999</option>' +
		'<option value="'+path+'50-69.html">PLZ-Bereich 50 - 69999</option>' +
		'<option value="'+path+'70-74.html">PLZ-Bereich 70 - 74999</option>' +
		'<option value="'+path+'75-79.html">PLZ-Bereich 75 - 79999</option>' +
		'<option value="'+path+'80-99.html">PLZ-Bereich 80 - 99999</option>' +
      '</select></p>';								
									
	jQuery('body#b1983 .tx-sunexcelread-pi1').prepend(html);
	
	
	var path = 'http://www.bioland.de/kunden/einkauf/metzger/plz/';								
	var html = '<p class="float-right"><span>Weitere Postleitzahlenbereiche:</span> ' +       
	'<select name="redirect" onChange="location.href=this.options[this.selectedIndex].value;">' +
		'<option selected>PLZ-Bereich&nbsp;</option>' +
		'<option value="'+path+'00-29.html">PLZ-Bereich 00 - 29999</option>' +
		'<option value="'+path+'30-49.html">PLZ-Bereich 30 - 49999</option>' +
		'<option value="'+path+'50-69.html">PLZ-Bereich 50 - 69999</option>' +
		'<option value="'+path+'70-74.html">PLZ-Bereich 70 - 74999</option>' +
		'<option value="'+path+'75-79.html">PLZ-Bereich 75 - 79999</option>' +
		'<option value="'+path+'80-99.html">PLZ-Bereich 80 - 99999</option>' +
      '</select></p>';								
									
	jQuery('body#b1984 .tx-sunexcelread-pi1').prepend(html);
	
									
	if(jQuery('body#b62').length > 0) // on page 62 http://www.bioland.de/kunden/einkauf.html
	{
		jQuery('select').css('border','solid 1px #ccc');
		jQuery('.select').hide();		
		// jQuery("a[href*='kunden/adressen/index.html']").css("color", "red");		
		jQuery("a[href*='kunden/adressen/index.html']").click(function(){											  
			jQuery(this).parents("p").next("div").toggle();
			return false;
		});	
		
	}				
									
									
	jQuery('.news-single-item p img').each(function(){
		if(	jQuery(this).attr('title'))
		{			
			if(	jQuery(this).attr('class')) {
								  
				var imgclass = jQuery(this).attr('class');
				jQuery(this).wrap('<p></p>');
				jQuery(this).parent('p').addClass(imgclass);
				jQuery(this).removeClass();			
			}
			
			var caption = '<br \><span class="caption">'+jQuery(this).attr("title")+'</span>';
			jQuery(this).after(caption);			
			
			var imgwidth = jQuery(this).width();
			jQuery(this).parent('p').css('width',imgwidth);	
		}												  
	});


	jQuery(".showhidecontent").hide(); 
	
	if(jQuery("#b20").length > 0) {
		var showhideLinkTitle = 'Links anzeigen';
	} else {
		var showhideLinkTitle = 'Text anzeigen';		
	}
	
	var showhideLinkStart = '<a href="#" class="showhide" title="'+showhideLinkTitle+'">';
	var showhideLinkEnd = '</a>';

	jQuery(".showhidecontentwrap h2").each(function(){
			// console.log( jQuery(this).html() );
			jQuery(this).html(showhideLinkStart + jQuery(this).html() + showhideLinkEnd);			  
	});		
	jQuery(".showhidecontentwrap h2 a").click(function(){
		jQuery(this).parent("h2").next("div.showhidecontent").toggle();		
		 if (jQuery(this).attr("title") == 'Text anzeigen')
		 {
		   jQuery(this).parent("h2").addClass('show');
		   jQuery(this).attr("title","Text ausblenden");
		   jQuery(this).children("img").attr("src","layout/img/minus.gif");
		 } 
	    else
		 {
		   jQuery(this).attr("title","Text anzeigen");
		   jQuery(this).children("img").attr("src","layout/img/plus.gif");
		   jQuery(this).parents("h2").removeAttr('class');
		 }
		 return false;
	});
									

    // Startseite - Mitte erstes Element ohne Linie oben
	jQuery("#b20 .csc-textpic").eq(0).css({"margin-top": "0", "border":"none"});	
	

	// Oster Gewinnspiel
	jQuery("#gewinnspielanmeldung").hide(); 	
	jQuery("#anmeldung-link").append(" <a href=\"#gewinnspielanmeldung\" title=\"Anmelde-Formular anzeigen\" >» Anmelde-Formular anzeigen</a>");	
	jQuery("#anmeldung-link a").click(function(){													  
		jQuery("#gewinnspielanmeldung").css({ "margin-left":"222px" });
		jQuery("#gewinnspielanmeldung").show(); 
		jQuery("#gewinnspiellogin").hide();
		return false;
	});	
	
	
	// Bildarchiv typo3 page 360
	// only if normal login - then hide loogin-form
	if(jQuery("#b360 #login-header").length > 0) 
	{
		jQuery("#b360 #login-form").hide(); 
		jQuery("#b360 #forgot-password").hide(); 
		jQuery("#b360 .tx-srfeuserregister-pi1").hide();	
	
		jQuery("#b360 #login-header").append("<a href=\"#\" title=\"Login-Formular anzeigen\" >» Login-Formular anzeigen</a>");	
		jQuery("#b360 #login-header a").click(function(){													  
			jQuery("#b360 #login-form").show(); 
			jQuery("#b360 #forgot-password").show(); 
			jQuery("#b360 #login-header a").hide();		
			return false;
		});	
	}
	
	// FOREN
	if(jQuery("#b390").length ) 
	{
		if(jQuery("#b390 #login-header").length ) 
		{		
			// tx-srfeuserregister-pi1 important for email-confirmation and following redirect
			jQuery("#b390 .tx-srfeuserregister-pi1").hide();
		}
		 // if tx_felogin_pi1[forgot] remove infotext
		 if ( jQuery.getUrlVar('tx_felogin_pi1%5Bforgot%5D').length )
		 {
			 jQuery("#c2445").hide();
		 }
	}
									
});
