$(document).ready(function(){

	$(function () {
	
		if ($("#top_navi_bar").is(':visible')) {
		  
				centrize();
      	check_pics();
      	infotoggle();
      	fielder();
      //	medientipp();
      	equalize();
      	equalize_doubles();
      	fabo();
      	odevs();
      	scrollable();
      	poser();
      	registration();
      	table_selection();
      	suche_switch();
      	sort_order();
      	tell_a_friend();
      	search_autocomplete();  
			
		}else{
		};
		
	})

});

function search_autocomplete() {
	$("#suchfeld").autocomplete("/search/ajaxsearch/", { width: 303, selectFirst: false, minChars: 3, matchContains: true, matchSubset: false, max: 50, formatResult: function(data, value){ if (data.length > 1) return data[1]; else return value; } });
}

function tell_a_friend() {
	$('#show_tell_a_friend').click(function(){
		$('.weiterempfehlen').show();
		return false;
	});
	$('#hide_tell_a_friend').click(function(){
		$('.weiterempfehlen').hide();
		return false;
	});
//	$('.weiterempfehlen:not(.success)').hide();
	$('.weiterempfehlen').hide();
}

function suche_switch () {
	suche_n = $('fieldset#main_search');
	suche_e = $('fieldset#main_search_extended');
	
	suche_e.hide();
	
	$('a#e_search').click(function () { 
      suche_n.hide();
      suche_e.show();
    });
    
    $('a#n_search').click(function () { 
      suche_e.hide();
      suche_n.show();
    });
}

function sort_order() {
	$('.sort_select select').each(function(){
		$(this).change(function(){
			$(this).parent().parent().submit();
		});
	});
}

function medientipp () {

	mt_rost = $('.medientip').innerHeight();
	mt_trigger = $('.medientip .mt_bild > a');
	tr_rost = $(mt_trigger).innerHeight();
	mtip = $('.medientip .mt_floater');
	
	diff = parseInt(( mt_rost - tr_rost) / 2 );
	mt_trigger.css({'padding-top': diff - 5});
}

$(function () {
  $('.medientip').each(function () {
    // options
    var distance = 25;
    var time = 250;
    var hideDelay = 500;

    var hideDelayTimer = null;

    // tracker
    var beingShown = false;
    var shown = false;
    
    var trigger = $('.mt_bild > a > img', this);
    var popup = $('.mt_floater', this).css('opacity', 0);

    // set the mouseover and mouseout on both element
    $([trigger.get(0), popup.get(0)]).mouseover(function () {
      // stops the hide event if we move from the trigger to the popup element
      if (hideDelayTimer) clearTimeout(hideDelayTimer);

      // don't trigger the animation again if we're being shown, or already visible
      if (beingShown || shown) {
        return;
      } else {
        beingShown = true;

        // reset position of popup box
        popup.css({
          top: 75,
          left: 150,
          display: 'block' // brings the popup back in to view
        })

        // (we're using chaining on the popup) now animate it's opacity and position
        .animate({
          left: '-=' + distance + 'px',
          opacity: 1
        }, time, 'swing', function() {
          // once the animation is complete, set the tracker variables
          beingShown = false;
          shown = true;
        });
      }
    }).mouseout(function () {
      // reset the timer if we get fired again - avoids double animations
      if (hideDelayTimer) clearTimeout(hideDelayTimer);
      
      // store the timer so that it can be cleared in the mouseover if required
      hideDelayTimer = setTimeout(function () {
        hideDelayTimer = null;
        popup.animate({
          left: '-=' + distance + 'px',
          opacity: 0
        }, time, 'swing', function () {
          // once the animate is complete, set the tracker variables
          shown = false;
          // hide the popup entirely after the effect (opacity alone doesn't do the job)
          popup.css('display', 'none');
        });
      }, hideDelay);
    });
  });
});

function poser() {
	
	var poser = $('.trigger');
	poser.parent().css({'position': 'relative'});
	
	poser.hover(function(e) {
		
		var pos = $(this).parent().offset(); // finding absolute positions to set "dada" exactly over the hovered object
		var shoplink = $(this).attr('href'); // we'll be passing the link to "dada"
		var floater_content = $(this).parent().find('.floater').html(); // looking for "floater" inside of the same parent and taking it's html
	
		var x = pos.left;
		var y = pos.top;
		
		var dada = $("<div class=\"dada\"><div class=\"bubble\"></div></div>"); // dada is being linked to the same place as the original "a href"
 		$('body').append(dada);
 		
 		var dada = $('.dada');
 		var bubble = $('.bubble');
 		bubble.html(floater_content);
	   	dada.show().css({'left':x, 'top':y});
//	   	dada.click(function() {document.location.href = shoplink} );
    	
    	dada.hover(function(e) {
    		bubble.animate({
        		top: '-=' + 25 + 'px',
        		opacity: 1
        	}, 500);
        	
		}, function() {
		
			bubble.hide();
			dada.hide();
			dada.remove();
			bubble.remove();
		});
    	
	}, function() {
		return;
	});
	
}

function scrollable () {

	var scroller = $("div.scrollable");

	scroller.scrollable({
        speed: 500,
        onBeforeSeek: function() { 
            this.getItems();      
        },
        onSeek: function() { 
            this.getItems(); 
        }
	});
}


function centrize () {

	kinder =$(".centrize");
	
	for (i=0; i<kinder.length; i++) {
		
		kind_width = $(kinder[i]).width();
		papa_width = $(kinder[i]).parent().innerWidth();
		
		if ( kind_width < papa_width ) {
			var zusatz = parseInt((papa_width - kind_width)/2);
			$(kinder[i]).css({'padding-left': zusatz});
		}
	}
}

function check_pics() {
	pics = $(".c2 .textnbild img, .c3 .textnbild img, .cl2cl3 .textnbild img, .cl3cl2 .textnbild img");
	
	for (i=0; i<pics.length; i++) {
		pic = $(pics[i]);
		size = pic.width();
		parent_size = pic.parent().parent().innerWidth();
		
		if (size < (parent_size - 30)) {
			pic.css({'margin': '0 10px 5px 0'});
		}
		else {
			pic.css({'margin': '0 0 10px 0'}).css({'float': 'none'});
		}
	}	
}

function infotoggle () {
	
	unseen = $(".in_video");
	obscured = $( $("div.infoblock.toggling > h3:not(.expanded)").next() );
	trigger = $("div.infoblock.toggling > h3");
	
	trigger.hover(function() {
		$(this).addClass('h_hover');
	}, function() {
		$(this).removeClass('h_hover');
	});
	
	var saved = new Array();
	$("div.ibl_save_state").each(function(){
		if ($.cookie($(this).attr('id') + '_hidden') !== null)
		{
			saved[$(this).attr('id')] = 1;
			if ($.cookie($(this).attr('id') + '_hidden') == 1)
			{
				$(this).find('h3').addClass('collapsed').removeClass('expanded').next().hide();
			}
			else
			{
				$(this).find('h3').removeClass('collapsed').addClass('expanded').next().show();
			}
		}
	});
	
	//obscured.hide();
	// hide only those blocks who wasn't saved in user cookies
	$(obscured).each(function(){
		if (!($(this).parent().attr('id') && saved[$(this).parent().attr('id')]))
		{
			$(this).hide();
		}
	});
	unseen.hide();
	
	trigger.click(function() {
		$(this).next().slideToggle("fast");
		$(this).toggleClass("collapsed").toggleClass("expanded");
		if ($(this).parent().hasClass('ibl_save_state'))
		{
			$.cookie($(this).parent().attr('id') + '_hidden', ($(this).hasClass('collapsed') ? 1 : 0), { path: '/' });
		}
		equalize();
		equalize_doubles();
	});
}

function fielder () {
	$('input.suchfeld').example(function() {
		return $(this).attr('title');
	});

	
	findbut = $("input.but_fin");
	login = $("input#login");
	logout = $("input#logout");
	
	findbut.hover(function() {
		$(this).attr({ 
          src: "/img/but_finden_hover.gif"
        });
	}, function() {
		$(this).attr({ 
          src: "/img/but_finden_norm.gif"
        });
	});
	
	findbut.mousedown(function() {
		$(this).attr({ 
          src: "/img/but_finden_down.gif"
        });
	}, function() {
		$(this).attr({ 
          src: "/img/but_finden_norm.gif"
        });
	});
	
	login.hover(function() {
		$(this).attr({ 
          src: "/img/but_login_hover.gif"
        });
	}, function() {
		$(this).attr({ 
          src: "/img/but_login_norm.gif"
        });
	});
	
	login.mousedown(function() {
		$(this).attr({ 
          src: "/img/but_login_down.gif"
        });
	}, function() {
		$(this).attr({ 
          src: "/img/but_login_norm.gif"
        });
	});
	
	logout.hover(function() {
		$(this).attr({ 
          src: "/img/but_logout_hover.gif"
        });
	}, function() {
		$(this).attr({ 
          src: "/img/but_logout_norm.gif"
        });
	});
	
	logout.mousedown(function() {
		$(this).attr({ 
          src: "/img/but_logout_down.gif"
        });
	}, function() {
		$(this).attr({ 
          src: "/img/but_logout_norm.gif"
        });
	});
	
}

function registration () {
	

	form_fields = $('form#registration input, form#registration textarea');
	
	bib = $('form#registration #wr_bib');
	fachstelle = $('form#registration #wr_fach');
//	bib_box = $('form#registration #wr_bib input:checkbox');
	bib_box = $('form#registration #bib');
	koeb = $('form#registration #wr_koeb');
//	koeb_box = $('form#registration #wr_koeb input:checkbox');
	koeb_box = $('form#registration #koeb');
//	bib_box.attr('checked', false);
//	koeb_box.attr('checked', false);
	
	type = $('form#registration input[name=option_type]:radio');
	type_org = $('form#registration input#organisation');
	
	lastat = $('form#registration input[name=custom_delivery_address]:radio');
	licont = $('div#liefer_cont');
	
	if (!type_org.attr("checked"))
	{
		bib.hide();
		koeb.hide();
		fachstelle.hide();
	}
	else
	{
		if (bib_box.attr("checked"))
		{
			koeb.show();
		}
		else
		{
			koeb.hide();
		}
	}
	
//	bib.hide();
//	koeb.hide();
	
	var evt = $.browser.msie ? "click" : "change";
	
	type.bind(evt, function () {
		if(type_org.attr("checked")){
			bib.slideDown("fast");
			if (bib_box.attr("checked"))
				koeb.slideDown("fast");
			fachstelle.slideDown("fast");
			$('input#firma').addClass('required').parent().find('label').append("<span class=\"must\">*</span>");
			$('input#vorname').removeClass('required').parent().find('span.must').remove();
			$('input#nachname').removeClass('required').parent().find('span.must').remove();
		}else{
//			bib_box.attr('checked', false);
//			koeb_box.attr('checked', false);
			bib.slideUp("fast");
			koeb.slideUp("fast");
			fachstelle.slideUp("fast");
			$('input#firma').removeClass('required').parent().find('span.must').remove();
			$('input#vorname').addClass('required').parent().find('label').append("<span class=\"must\">*</span>");
			$('input#nachname').addClass('required').parent().find('label').append("<span class=\"must\">*</span>");
		}
	});
	
	lastat.bind(evt, function () {
		if($('input#la_status_2').attr("checked")){
			licont.slideDown("fast");
        }else{
        	licont.slideUp("fast");
        }
	});
	
	bib_box.bind(evt, function () {
		if(bib_box.attr("checked")){
			koeb.slideDown("fast");
        }else{
			koeb.slideUp("fast");
//			koeb_box.attr('checked', false);
        }
	});
	
	if ($.browser.name != "msie") {
			form_fields.focus(function () {
		         $(this).animate({
		        	fontSize: "2em",
		        	lineHeight: "16"
		      	}, 100 ).addClass('f_hover');
		    });
		    form_fields.blur(function () {
		         $(this).animate({
		        	fontSize: "1em"
		      	}, 100 ).removeClass('f_hover');
		    });
		}
		else {
			return;
		}
}

function odevs() {
	$("ul.doubles > li:odd").addClass('odd');
	$("ul.doubles > li:even").addClass('even');
}

function equalize() {
	parents = $("div.equalize");
		
	for (i=0; i<parents.length; i++) {
		papa = $(parents[i]);
		deti = $(papa.find(".eqs"));
		
		var rost = new Array();
		
		for (a=0; a<deti.length; a++) {
			kind = $(deti[a]);
			rost[a] = kind.innerHeight();
		}
		
		biggest = $.protify(rost).max();
		
		for (a=0; a<deti.length; a++) {
			kind = $(deti[a]);
			rost = kind.innerHeight();
			
			if(biggest > rost) {
				diff = (biggest - rost);
				kind.css({'padding-bottom' : diff});
			}
		}
		
		if (papa.hasClass('layoff')) {
			papa.children(':first').css({'margin-right':'5px'}).addClass('ch_first');
			papa.children(':last').css({'margin-left':'5px'}).addClass('ch_last');
		}
		
	}

}

function fabo() {

	if (($.browser.name == "msie") && ($.browser.version < 7)) {
		return;
	}
	else {
		
		$(".zusatz a:not(.video,.skip_fabo) img").parent().fancybox({
		'zoomOpacity': true,
		'overlayShow': true,
		'overlayOpacity': 0.5
		});
		
		$("a.fanbox img").parent().fancybox({
		'zoomOpacity': true,
		'overlayShow': true,
		'overlayOpacity': 0.5
		});
		
		
		$(".zusatz a.video").fancybox({
		'hideOnContentClick': false,
		'frameWidth': 640,
		'frameHeight': 480,
		'overlayShow': true,
		'overlayOpacity': 0.5
		});
		
	}
}


function equalize_doubles() {

	parents = $("ul.doubles");
	
	for (i=0; i<parents.length; i++) {
		papa = $(parents[i]);
		evens = $(papa.find(">li:even"));
		odds = $(papa.find(">li:odd"));
		
		for (a=0; a<evens.length; a++) {
			if ( odds[a] != null ) {
				
				e_li = $(evens[a]);
				o_li = $(odds[a]);
				
				e_cont = $(e_li.find(">.object_description"));
				o_cont = $(o_li.find(">.object_description"));
				
				e_rost = e_cont.height();
				o_rost = o_cont.height();
				
				
				if(e_rost > o_rost) {
					diff = (e_rost - o_rost);
					o_cont.css({'padding-bottom' : diff + 10});
				}
				
				if(e_rost < o_rost) {
					diff = (o_rost - e_rost);
					e_cont.css({'padding-bottom' : diff + 10});
				}
				
			}
		}
		
	}
	
}

function table_selection() {
	table = $('table');
	cbox = $(table.find('input.row_selector'));
	sbox = $(table.find('input.select_all'));
	var evt = $.browser.msie ? "click" : "change";
	
	sbox.bind(evt, function () {
	
		var items = $(this).parent().parent().parent().parent().parent().find('input.row_selector');
	
		if($(this).attr("checked")){
			items.attr('checked', true);
			colorize(items);
        }else{
        	items.attr('checked', false);
        	colorize(items);
        }
	});

	cbox.bind(evt, function() {
		sbox.attr('checked', false);
		var items = $(this);
		colorize(items);
	});
	
	function colorize(items) {
		if(items.attr("checked")){
			items.parent().parent().find('td').addClass('selected_to_delete');
        }else{
        	items.parent().parent().find('td').removeClass('selected_to_delete');
        }
	}
}


/* .css({'border-top':'5px solid red'}) */



