var log = function(d){
    //console.log(d);
}
var hide_on_empty = true //false;

$(document).ready(function() {  

    log("ready")
// Link Behaviour
    $('a.external').attr('target', '_blank');
    $('form#frmSearch').attr('target', '_blank');
// language Select						   
    if ($('.languageSelect ul')) {
        $('.languageSelect ul li').hover(function(e){
                $(this).addClass('hover');
            },
            function(){
                $(this).removeClass('hover');
            }
        );
    }
	
	
// Top Nav
	$('ul.topNav > li').each(function() {
		$(this).css('width', $(this).width()); //für IE6
	});

	$('ul.topNav li ul').each(function() {
		$(this).parent().css('overflow', 'visible');
		$(this).css('height', $(this).height()).hide();
		$(this).attr('tobeHeight', $(this).height()); /* zum Abspeichern der Originalhöhe zwecks späterer Wiederwendung */
		$(this).parent().css('overflow', 'hidden');
	});
		
	
	$('ul.topNav > li').hover(function() {
		$(this).css('overflow', 'visible');
		$(this).addClass('active');	//für IE6	
		
		$(this).css('z-index', '3');
		$(this).find('ul').stop(false, false).css('height', '0').css('opacity', '0.6').animate({
			height: $(this).find('ul').attr('tobeHeight'),
			opacity: 1
		}, 600);
		
	}, function() { 		
		$(this).removeClass('active'); //für IE6
		$(this).css('z-index', '2');
		$(this).find('ul').stop(false, false).animate({
			height: 0,
			opacity: 0.6
		}, 400, function() {
			$(this).css('overflow', 'hidden');
		});
	});
	
	function tobeRunter() {
		if($('ul.topNav > li ul').is(':animated')) {
			//Animation am laufen, nicht öffnen
		} else {
			$(this).css('overflow', 'visible');
			$(this).addClass('active');	//für IE6	
			
			$(this).css('z-index', '3');
			$(this).find('ul').stop(true, true).slideDown('normal');
		}
	}

// Productfinder
	$('#pageBodyWelcome .containerRight .hover ul').hide();
	
	$('#pageBodyWelcome .containerRight .hover').hover(function() {		
		$(this).find('ul').stop(true, true).slideDown('normal');
	}, 
	function () {
		$(this).find('ul').slideUp('normal');
	});


// Search Box	
		$('.searchBox form').submit(function() {
			return false;
		});		
		$('.searchBox p input#search').attr('autocomplete', 'off');		
//		$('.searchBox').css("display", "block");		
		

        $('.searchBox form input').click(function(){
			$('#pane1').jScrollPane({ scrollbarWidth:5 });
		});
											  
        $('.searchBox form input').focus(function(){
				$('.searchBox form').addClass('open');
				$('#pane1').jScrollPane({ scrollbarWidth:5 });
				$(this).val('');
			}
       );
		
	$(document).click(function(e) {
       if (!$(e.target).parents().andSelf().is('.searchBox')) {
       		 $('.searchBox form').removeClass('open');
			 $('.searchBox form input').val(lang.search);
          }
    });
	
// Search Box

// lightbox
    if($('a[rel^="lightbox"]').length > 0) {
        $('a[rel^="lightbox"]').colorbox({ maxWidth: 1000 });
    }
    if($('a[rel^="inlineLightbox"]').length > 0) {
        $('a[rel^="inlineLightbox"]').each(function() {
            var $t = $(this);
            $t.colorbox({ inline:true, href: $t.attr('href') });
        }); 
    }
	
	  $('.downloads form').live('submit', function() {
	     if($('select[name="name"]', $(this)).val()=='') {
	         return false;
       }
       return true;
    });


//Manager Imagehover {
	$('#fachartikel .artikel a img, .download a img').css('opacity', '0.7');
	
	$('#fachartikel .artikel a img, .download a img').hover(function() {
		$(this).stop(true, true).animate({opacity: 1}, 300);														
	}, function() {
		$(this).animate({opacity: 0.7}, 300);
	});
	
//Downloadmanager Akkordeon
	$('div.download div.hide, div.artikel  div.hide').hide();
	$('div.download div.hide, div.artikel  div.hide').prev('h5').css('cursor', 'pointer').css('width', '550px').css('padding-right', '26px').css('background', 'url(/ecomaXL/pics/bg_arrow_accord_closed.png) right 3px no-repeat');
	$('div.download div.hide, div.artikel  div.hide').parent().css('margin-bottom', '0.5em');
	
	$('div.download div.hide, div.artikel  div.hide').prev('h5').click(function() {
		if($(this).next('div.download div.hide, div.artikel  div.hide').is(':hidden')) {
			$(this).css('margin-bottom', '0.5em').css('background', 'url(/ecomaXL/pics/bg_arrow_accord_open.png) right 3px no-repeat');
		} else {
			$(this).css('margin-bottom', '0.5em').css('background', 'url(/ecomaXL/pics/bg_arrow_accord_closed.png) right 3px no-repeat')
		}
		$(this).next('div.download div.hide, div.artikel  div.hide').stop(true, true).slideToggle('normal');
	});
//dlList-Akkordeon
	
	
//Tribojournal-Abonnement Abbestellung

var array = [];

$('form.contact input#tribojournal_unsubscribe').click(function() {
	
	if($('form.contact input#tribojournal_unsubscribe').is(':checked')) {	
	
		$('form.contact fieldset.checkup input:checked').each(function() {
			array[array.length] = $(this).attr('id');
		});
		
		$('form.contact fieldset.checkup input:checkbox').attr('checked', '');
		
	} else { 
	
		for(i = 0; i < array.length; i++) {
			$('input#'+array[i]).attr('checked', 'checked');
		}
		
		array = [];
	}
	
});

//Tribojournal-Abonnement Abbestellung


//Produktausgabe A - Z	

	//entfernt die Klick-Funktion von inaktiven Ankern
	$('#pageBody #content #a-z ol li.inactive a').removeAttr('href');
	
	//erzeugt den Code für den Limiter dann, wenn er gebraucht wird
	var paginierungVorhanden = $('#a-z #paginierung').length;
	var anzahlProdukte = $('#a-z table tbody tr').length;
	
	if(paginierungVorhanden > 0 || anzahlProdukte > 12) {
		$('#foot').append('<form action=""><fieldset><select size="1"><option value="12">12 '+ lang.entries +'</option><option value="24">24 '+ lang.entries +'</option><option value="50">50 '+ lang.entries +'</option></select></fieldset></form>');
	}


	//setzt neues Limit in der URL
	var value = 12;
	$('#a-z form select').change(function() {
		var value = $(this).attr('value');
		var url = window.location.href;
		
		url = url.replace(/page=\d+/, '');
		
		if(window.location.search != '') {			
			var limitVorhanden = url.search(/\blimit/);			
			if(limitVorhanden != -1) {
				window.location = url.replace(/limit=\d+/, 'limit=' + value);				
			} else {
				window.location = url + '&limit=' + value;	
			}			
		} else {
			window.location = url + '?limit=' + value;
		}		
	});
	
	//highlighted aktuelles Limit in der Selectbox
	var aktuelleUrl = window.location.href;
	var aktuellesLimit = window.location.href.match(/limit=(\d+)/);
	
	if(aktuellesLimit) {
		$('#a-z form select option[value="'+aktuellesLimit[1]+'"]').attr('selected', 'selected');
	}
	
//Produktausgabe A - Z


// Tribo? Logisch! Formular
	$('form#triboLogisch input#suchbegriff').focus(function() {
		$(this).attr('value', '');											
	});
	
	
// Tribo? Logisch! Formular


// top
	$(".top").click(function(){
		$('html, body').animate({ scrollTop: $("#wrapper").offset().top }, 'slow');
		return false;
	});	
	
	/*
	 *
	 * produktfinder
	 * @author ys
	 *
	 */
	if($('div#application').length > 0) {
		var hash = (location.hash) ? location.hash : '#'+firstApplicationId;
		location.hash = hash;
		appHash(hash, true);
	}
	$('div#application li div a').live('click', function() {
		$(this).parent().addClass('done');
		location.hash = $(this).attr('rel');
		return false;
	});
	$('div#application li div a span').live('click', function() {
		$(this).parents('div:first').removeClass('done')
		location.hash = $(this).attr('id');
		return false;
	});
	/*
	 * Auskommentiert von mah, weil das nicht benötigt wird, da "normales Formular". Hatte in IE8 gebuggt
	 * ggf zum launch löschen
	 * $("#application .downloads form ,.colRight .colRightBox form").live('submit', function() {
    if($(this).find('option:selected').val() != '') {
			window.open($(this).find('option:selected').val()).focus();
		}
		return false;
	});*/
	function appHash(old, first) {
        
		window.setTimeout(function() {
			if(old != location.hash || first == true) {
				if(first == true) {
					$('div#application').html('<ul></ul>');
				}
				if($('div#application #detail, div#application .downloads').length > 0) {
					$('div#application #detail, div#application .downloads').remove();
				}
				$('div#application ul').append('<li><img src="/ecomaXL/pics/pi_application_load.gif" alt="" style="margin:3em auto; display:block" /></li>');
				$.post('/ecomaXL/applications_json.php', { 'id': location.hash.replace('#', ''), 'presence_id': lang.presence_id }, function(data) {
					var list = new Array();              
                                        
					if(data.breadcrumb) {
						var count = 1;
						var items = data.breadcrumb.length;
						var level = data.level;
						$.each(data.breadcrumb, function(key, value) {
							if (parseInt(items - 1) >= count) {
								var getMargin = level -  2;
								list.push('<li style="margin-left:'+getMargin * 20+'px;"><div class="done"><a href="#" rel="'+value.id+'">'+unescape(value.displayName)+'<span id="'+data.breadcrumb[count++].id+'"></span></a></div></li>');
								level--;
							}
						});
						list.remove(-1);
						list.reverse();
					}
					if(data.children) {
						$.each(data.children, function(key, value) {
							list.push('<li style="margin-left:'+(data.level - 1) * 20+'px"><div><a href="#" rel="'+value.id+'">'+unescape(value.displayName)+'<span id="'+data.breadcrumb[0].id+'"></span></a></div></li>');
						});
					}
                                                          
					if(data.product) {
						var content = '';
                        
						//log(data.product.certificates.length);
                        
						if(data.product.certificates.length > 0) {
							var option = '';
							$.each(data.product.certificates, function(key, value) {
								option += '<option value="'+value.name+'">'+unescape(value.displayName)+'</option>';
							});
							content += appSnippet(lang.certificate, lang.type, option);
						}
						if(data.product.productInformations.length > 0) {
							var option = '';
							$.each(data.product.productInformations, function(key, value) {
								option += '<option value="'+value.name+'">'+unescape(value.displayName)+'</option>';
							});
							content += appSnippet(lang.product, lang.lang, option);
						}
						if(data.product.safetyDataSheets.length > 0) {
							var option = '';
							$.each(data.product.safetyDataSheets, function(key, value) {
								option += '<option value="'+value.name+'">'+unescape(value.displayName)+'</option>';
							});
							content += appSnippet(lang.safetydata, lang.country, option);
						}
                        
                        //no entries
                        window.data = data;
                        if(content.length == 0 && hide_on_empty){
                            setTimeout(function(){
                                $('.downloads h6').first().hide();
                            },500);  
                        }
                        //
                        
						if(data.product.id) {
							content += '<h6>Links</h6><dl class="infoBoxDownloads"><dt><a href="product_detail/id/'+unescape(data.product.id)+'/">'+lang.links+'</a></dt></dl>';
						}
						content = '<div class="downloads"><h6>Downloads</h6>'+content+'</div>';
					content += '<div id="detail"><h5>'+unescape(data.product.displayName)+'</h5><p>'+unescape(data.product.benefit)+'</p></div>';
					}
					// ausgabe
					var html = '';
					$.each(list, function(key, value) {
						html += value;
					});
					window.setTimeout(function() {
						$('div#application').html('<ul>'+html+'</ul>').append(content);
					}, 300);
				}, 'json');
			}
			appHash(location.hash, false);
		}, 100);
	}
    window.appHash = appHash;
    
	function appSnippet(headline, label, option) {
		
		var snippet = '<p><strong>'+headline+'</strong></p>'
+		'<form action="/ecomaXL/get_blob.php" method="get">'
+			'<p>'
+				'<select name="name" id="'+headline+'">'
+					'<option disabled="disabled" selected="selected" value="">'+label+'</option>'
+					option
+				'</select>'
+				'<input type="submit" class="send" name="send" />'
+			'</p>'
+		'</form>';
		return snippet;
	}
	Array.prototype.remove = function(from, to) {
		var rest = this.slice((to || from) + 1 || this.length);
		this.length = from < 0 ? this.length + from : from;
		return this.push.apply(this, rest);
	}
	
	
	$('#search').live('keyup', searchRequest);
});


/**
 * Wird ausgeführt, wenn ein Zeichen in die Suchbox (#search) eingegeben wurde.
 * Es wird erst ab 4 Zeichen Länge ein AJAX-Request abgesendet, der 
 * den Rückgabewert der Suche in #pane1 lädt
 * 
 */    
function searchRequest() {
    if($('#search').val().length<4) return;
    
	if(lang.presence_id == 4) {
		var siteParameter = 'such_ergebnis';
	} else {
		var siteParameter = 'search_request';
	}
	$.post(
        '/ecomaXL/index.php?site='+siteParameter,
        {
            presence_id : lang.search_presence,
            search: $('#search').val()
        },
        function(data) {
            $('#pane1').html(data).jScrollPane({ scrollbarWidth:5 });
        }
    );
}

function sendpage(url){ open(url, 'sendpage', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no,width=420,height=300'); }
function open_print(url) { open(url, 'popup', 'toolbar=no,location=no,directories=no,status=no,menubar=yes,scrollbars=yes,resizable=yes,copyhistory=no,width=515,height=500');}
function popup(url){MAINWIN=open(url, 'popup', 'toolbar=no,location=no,directories=no,status=no,menubar=yes,scrollbars=no,resizable=yes,copyhistory=no,width=500,height=595');}
