function showsubpart(category) {
	$("#content_subparts ul.active").removeClass('active');
	$("#category_subpart_" + category.replace('category_', '')).addClass('active');
}

function formatZahl(zahl, k, fix) {
    if(!k) k = 0;
    var neu = '';
	var dec_point = '.';
	var thousands_sep = ',';

    // Runden
    var f = Math.pow(10, k);
    zahl = '' + parseInt(zahl * f + (.5 * (zahl > 0 ? 1 : -1)) ) / f ;

    // Komma ermittlen
    var idx = zahl.indexOf('.');
	
    // fehlende Nullen einfügen
    if(fix)    {
         zahl += (idx == -1 ? '.' : '' )
         + f.toString().substring(1);
    }

	var sign = zahl < 0;
	if(sign) zahl = zahl.substring(1);
    idx = zahl.indexOf('.');

	// Nachkommastellen ermittlen
    if( idx == -1) idx = zahl.length;
    else neu = dec_point + zahl.substr(idx + 1, k);

    while(idx > 0)    {
        if(idx - 3 > 0)
        neu = thousands_sep + zahl.substring( idx - 3, idx) + neu;
        else
        neu = zahl.substring(0, idx) + neu;
        idx -= 3;
    }

	neu = neu.toString().replace(',', '#');
	neu = neu.toString().replace('.', ',');
	neu = neu.toString().replace('#', '.');
	
    return (sign ? '-' : '') + neu;

}

function is_int(value){
  if((parseFloat(value) == parseInt(value)) && !isNaN(value)){
      return true;
  } else {
      return false;
  }
}

function in_array(item,arr) {
	for(p=0;p<arr.length;p++) if (item == arr[p]) return true;
	return false;
}

$(document).ready(function() {
	var cur_bgimage = $('#content_backgroundphoto').attr('src');
	var cur_category =$('#menubar_topbottom ul li.active').attr('class');
	if (cur_category == null) cur_category = 'category_0';

	cur_category = cur_category.replace(' active', '');
	$("#category_subpart_" + cur_category.replace('category_', '') + ' a').addClass('dark')
	showsubpart(cur_category);
	
	$(".placeholder").placeholder();

	/* BACKGROUND IMAGE - HOVEREFFECT */
	$('#main_menubar').bind("mouseleave", close);
	$('#menubar_topbottom ul li').bind("mouseover", function() {
		
		var t = $('.page_title_header').eq(0);
		t.html($(this).attr("rel"));
		t.attr("id", "title_" + parseInt($(this).attr("class").split("_")[1]));
		t.removeClass("active_page_header");
		$('#header_bottom_left, #bottom_right').hide();
		
		var category = $(this).attr('class');
		category = category.replace(' active', '');
		//var pos = $(this).css('background-position');
		$('#menubar_topbottom ul li').attr('style', '');
		//$(this).css('background-position',  pos.replace(' 0px', ' -43px'));
		$("#category_subpart_" + cur_category.replace('category_', '') + ' a').removeClass('dark');
		hoverbg(category);
		showsubpart(category);
	});// stop drop down menu from being closed
	var hideTimer = setTimeout(function() {  }, 1);//initialise so not undefined
	function close() {
		clearTimeout(hideTimer );
		hideTimer = setTimeout(function() {
			$('#content_backgroundphoto').attr('src', cur_bgimage);
			$('#menubar_topbottom ul li').attr('style', '');
			showsubpart(cur_category);
			$("#category_subpart_" + cur_category.replace('category_', '') + ' a').addClass('dark');
			
		
			var t = $('.page_title_header').eq(0);
			t.addClass("active_page_header");
			var m = $('#menubar_topbottom ul li.active').eq(0);
			var nID = "title_";
			if(typeof m.attr("class") != "undefined") {
				nID = nID + m.attr("class").split(" ")[0].split("_")[1];
				t.html(m.attr("rel"));
			} else {
				nID += "0";
				if (this_is_home) t.html(t.attr("rel"));
				else	t.html("");
				$('#header_bottom_left, #bottom_right').show();
			}
			
			t.attr("id", nID);
			
			
		}, 200);//close drop down menu*/
	}


	// add shadow to elements with class "add_shadow"
	var shadow_wrapper = '<div class="shadow"></div>';
	var shadow_image = '<img src="' + base_uri + '/reciter/theme/standard/img/icon_shadow.gif" alt="" class="shadow" />';
	$(".add_shadow").wrapInner(shadow_wrapper);
	$("div.shadow").append(shadow_image); 

	 // remove style-attribut form Google Customized Search which messes up border and size in IE6+7
	$("#s").attr("style","");
	$("#s").blur(function(){
		$(this).attr("style","");
	});
	
	function sortmyway(data_A, data_B)
{
	if ( data_A < data_B ) // data_A come before data_B
		return -1;
	if ( data_A > data_B ) // data_A come After data_B
		return 1;
	return 0; // data_A == data_B, no change.

}

//var sidebar_maxheight = $("#content_box").innerHeight();
$('#sidebar').css('min-height', $("#sidebar").innerHeight()+'px');

//$('#sidebar').css('max-height',sidebar_maxheight+50);

var beginsidebar = $("#sidebar").offset().top;

$(".marked-pos").css({position:"relative"});
	
	window.onscroll = function(e){
		var vals = [];
		var obj = {};
		var i = 0;
		var ptop = 0;
		var offset = 0;
		if ($('#marked').is(":visible")) {
		
		if ($("#content_box").height() > $("#sidebar").css('min-height')) $("#sidebar").css("max-height", $("#content_box").height());
		$(".marked-pos").each(function(){
			var num = Math.abs(Math.round((parseInt($(window).scrollTop()) - parseInt($(this).offset().top) + 200)));
			vals.push(parseInt(num));
			obj[num] = [this, i];
			i++;
		});
		vals.sort(sortmyway);
		if($(obj[vals[0]][0]).html() == "") $(obj[vals[0]][0]).append($("#marked"));
		if(i-1 == obj[vals[0]][1]) {
			if(vals[0] >= 200) {
				$(obj[vals[0]][0]).clearQueue();
				$(obj[vals[0]][0]).stop();
				//if ( ($(window).scrollTop()) + ' < ' +  ($('#sidebar').offset().top +  sidebar_maxheight - (endofsidebar) )) {
					ptop = 0;
					$('.sidebar_box').not('#marked').each(function(){
						ptop += $(this).height();
					});
					ptop = $(window).scrollTop() - beginsidebar - ptop;
				//}
				offset = 0;
				$('.sidebar_box').each(function(){
					offset += $(this).height();
				});

				if ( ptop < ( $('#content_box').height()- offset ) ) {
				$(obj[vals[0]][0]).animate({
						'padding-top' : ptop
					}, 500);
				}
			} else {
				$(obj[vals[0]][0]).animate({
					'padding-top' : 0
				}, 500);
			}
			//if(obj[vals[0]][0].offset().top <= $(window).scrollTop())
		} else {  }
		}
	};
	
	/* ##### Notepad ##### */

	$.post(base_uri + "/product/notepadsidebar/", function(data){
		$("#sidebar_notepadcontent").html(data);
	});
	
	$(".addtonotepad").click(function(){
		var product = this;
		$.post(base_uri + "/product/addtonotepad/", {"product":$(product).attr("rel"), "category_id": $("#content").attr('class')}, function(data){
			$(product).addClass('onnotepad');
			$.jGrowl(js_lang['notepad_addtonotepad']);
			$("#sidebar_notepadcontent").html(data);
			$(".notepadbutton").hide();
			$("#sidebar_notepadcontent").parent().parent().show();
		});
	});
	
	$(".note_trashcan").live("click", function(){
		var product = this;
		$.post(base_uri + "/product/delfromnotepad/", {"product":$(product).attr("rel")}, function(data){
			$.jGrowl(js_lang['notepad_removefromnotepad']);

			if ($(product).parent().parent().attr('id') == 'sidebar_notepadcontent') {
				$(".notepadcontent .note_trashcan").each(function(){
					if ($(this).attr("rel") == $(product).attr("rel")) $(this).closest('.note').remove();
				});
			}else {
				$(product).closest('.note').remove();
			}

			$("#sidebar_notepadcontent").html(data);
			if (data == '') {
				$(".notepadbutton").show();
				$("#sidebar_notepadcontent").parent().parent().hide();
			}
		});
	});
	
	/* BEGIN FORMCHECK */
	
	/* QUESTION FORM */	

	
	$("#question_form").submit(function(){
		
		$(".notepad_form textarea, .notepad_form input[type=text]:not(#dnf)").each(function(){
			$(this).inputNotes({
				tags: {
				  pattern: /<(\S+).*>(.*)<\/\1>/,
				  type: 'warning',
				  text: 'Do not use any HTML, it will be filtered out!'
				}
			 });
		});
		
		$("#check_mail").inputNotes({
			email: {
			  pattern: /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+$/,
			  type: 'warning',
			  text: js_lang['notepad_emailinc'],
			  inversedBehavior: true
			}
		 });
		 
		 $("#check_firstname, #check_lastname").each(function(){
			$(this).inputNotes({
			  minlength: {
				  pattern: /^(.){0,3}$/i,
				  type: 'warning',
				  text: js_lang['notepad_pflicht']
				}
		});
	});

		var hasnotes = false;
		
		$(this).find("input").each(function() {
			if ($(this).hasInputNotes()) hasnotes = true;
		});
	
		if ( $(this).attr("id") == "pricelist_form" ) {
			if ( $(this).find("input[type=checkbox]:checked").length < 1) alert(js_lang['notepad_checkb']);
			hasnote = true;
		}
			
		if ( hasnotes ) return (false);
		else return (true);
	
	});
	
	/* PRICELIST FORM */
	
	$("#pricelist_form").submit(function(){
		
		$(".notepad_form textarea").each(function(){
			$(this).inputNotes({
				tags: {
				  pattern: /<(\S+).*>(.*)<\/\1>/,
				  type: 'warning',
				  text: 'Do not use any HTML, it will be filtered out!'
				}
			 });
		});
		
		$("#check_mail").inputNotes({
			email: {
			  pattern: /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+$/,
			  type: 'warning',
			  text: js_lang['notepad_emailinc'],
			  inversedBehavior: true
			}
		 });
		 
		 $(this).find("#check_firstname, #check_lastname, #check_company, #check_street, #check_city, #check_phone, textarea").each(function(){
			$(this).inputNotes({
			  minlength: {
				  pattern: /^(.){0,3}$/i,
				  type: 'warning',
				  text: js_lang['notepad_pflicht']
				}
			});
		 });
		
		var hasnotes = false;
		
		$(this).find("input").each(function() {
			if ($(this).hasInputNotes()) hasnotes = true;
		});
	
		if ( $(this).find("input[type=checkbox]:checked").length < 1 && $(this).find(".notepadcontent div").length < 1)   {
			alert(js_lang['notepad_checkb']);
			hasnotes = true;
		}
	
		if ( hasnotes ) return (false);
		else return (true);
	
	});
	
	/* PHONE FROM */

	$("#phone_form").submit(function(){
		
		$(".notepad_form textarea, .notepad_form input[type=text]:not(#dnf)").each(function(){
			$(this).inputNotes({
				tags: {
				  pattern: /<(\S+).*>(.*)<\/\1>/,
				  type: 'warning',
				  text: 'Do not use any HTML, it will be filtered out!'
				}
			 });
		});
				 
		 $("#check_firstname,  #check_lastname, #check_phone").each(function(){
			$(this).inputNotes({
			  minlength: {
				  pattern: /^(.){0,3}$/i,
				  type: 'warning',
				  text: js_lang['notepad_pflicht']
				}
			});
		 });
		
		var hasnotes = false;
		
		$(this).find("input").each(function() {
			if ($(this).hasInputNotes()) hasnotes = true;
		});
	
		if ( hasnotes ) return (false);
		else return (true);
	
	});
	
	/* OFFER FORM */

	$("#offer_form").submit(function(){
		
		$(".notepad_form textarea").each(function(){
			$(this).inputNotes({
				tags: {
				  pattern: /<(\S+).*>(.*)<\/\1>/,
				  type: 'warning',
				  text: 'Do not use any HTML, it will be filtered out!'
				}
			 });
		});
		
		$("#check_mail").inputNotes({
			email: {
			  pattern: /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+$/,
			  type: 'warning',
			  text: js_lang['notepad_emailinc'],
			  inversedBehavior: true
			}
		 });
		 
		 $("#check_firstname, #check_lastname, #check_company, #check_street, #check_city, #check_phone, textarea").each(function(){
			$(this).inputNotes({
			  minlength: {
				  pattern: /^(.){0,3}$/i,
				  type: 'warning',
				  text: js_lang['notepad_pflicht']
				}
			});
		 });
		
		var hasnotes = false;
		
		$(this).find("input").each(function() {
			if ($(this).hasInputNotes()) hasnotes = true;
		});

		if ( hasnotes ) return (false);
		else return (true);
	
	});
	
	/* ##### Formvalidation Anfrage ##### */
	$('#request_form, #order_form').submit(function() {
		$("#check_name, #check_street, #check_city, #check_phone").each(function(){
			$(this).inputNotes({
			  minlength: {
				  pattern: /^(.){0,5}$/i,
				  type: 'warning',
				  text: js_lang['notepad_pflicht']
				}
			});
		 });
		 
		 $("#check_mail").inputNotes({
			email: {
			  pattern: /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+$/,
			  type: 'warning',
			  text: js_lang['notepad_emailinc'],
			  inversedBehavior: true
			}
		 });
		 
		 if ($("#check_name").hasInputNotes() ||
			 $("#check_street").hasInputNotes() ||
			 $("#check_city").hasInputNotes() ||
			 $("#check_phone").hasInputNotes() ||
			 $("#check_mail").hasInputNotes()) {
				return (false);
		} else { 			
			_gaq.push(['_trackPageview','/onout/3a-pro-bestellen/beschickt']);
			return (true);
		}
	});
	
	/* END FORMCHECK */	
	
	/** Preise Anfrage **/
	$('input.quantity').keyup(function() {
		if ($(this).val() == '' ) $(this).val('0');
		if (is_int($(this).val())) {
			var total = formatZahl(parseFloat($(this).attr("rel"))*parseInt($(this).val()), 2, true);

			$(this).parent().parent().find('span.total').html('<strong style="float: left;">Summe:</strong><strong style="float: right;">' + total + ' €</strong>');
			
			var sumtotal = 0;
			$('input.quantity').each(function(){
				if (is_int($(this).val()))	sumtotal += parseFloat($(this).attr("rel"))*parseInt($(this).val());
			});
			sumtotal = formatZahl(sumtotal, 2, true);
			$('.notepad_adressform.request').find(".sumtotal").html('<strong style="float: left;">Gesamtsumme: </strong><strong style="white-space:nowrap; float: right; position: absolute;  right: 0px;">' +  sumtotal + ' €</strong><div style="clear: both;"></div>').removeClass("hidden");
		}else {
			$(this).val('0');
		}
	});
	
	/* #### Print Tables #### */
	
	var tableToPrint = [];

	if ( $('.ph_3').hasClass('printdsheet') == false ) {

		$('#content_subparts > ul.active > li').each(function (index, domEle) {
			$(domEle).children().each(function(index, domLink) {
				// Anker parsen
				var anker_link = domLink.href;
				var anker_split = anker_link.split("#top");
				$('#list_tables div.shadow').prepend('<div style="float:left;width:400px;padding:5px;"><input class="addPrintMap" id="check'+anker_split[1]+'" type="checkbox" name="' + anker_split[1] + '" value="'+anker_split[1]+'">&nbsp;&nbsp;<label for="check'+anker_split[1]+'">' + domLink.innerHTML + '</label></div>');
			});
		});

		$('.ph_3').click(function(e){
			e.preventDefault();
			$('#list_tables').toggle();
			$('#list_tables .close_img').click(function(){
				$('#list_tables').toggle();
			});
		});

		$('.addPrintMap').click(function() {
			cID = '#check' + $(this).val();
			if($(cID).is(':checked')) {
				tableToPrint.push($(this).val());
			} else if($(cID).is(':checked') == false) {
				for(i=0;i<tableToPrint.length;i++) {
					if(tableToPrint[i] == $(this).val()) {
						tableToPrint.splice(i, 1);
					}
				}
			}
		});

		$('#printTables').click(function() {
			$('#list_tables').append('<textarea id="printCache" style="display:none;"></textarea>');
			/*for(i=0;i<tableToPrint.length;i++) {
				var TabCode = $('#top' + tableToPrint[i]).parent().html() + "<br />";
				if (TabCode != null) $('#printCache').append(TabCode);
			}*/
			$.ajax({
			  url: category_uri,
			  success: function(data) {
				for(i=0;i<tableToPrint.length;i++) {
					var TabCode = $(data).find('#top' + tableToPrint[i]).parent().html() + "<br />";
					$('#printCache').append(TabCode);
				}
				newwin = window.open(''+ base_uri +'/print.php', '_blank', 'width=665,height=600,scrollbars=yes,resizeable=yes');
			  }
			});
		});
	}else {
		$('.ph_3').click(function(e){
			$('#list_tables').append('<textarea id="printCache" style="display:none;"></textarea>');
			e.preventDefault();
			var ds_url = location.href;
			ds_url = ds_url.replace('althen.de/', 'althen.de/ajax/');
			ds_url = ds_url.replace('althensensors.com/', 'althensensors.com/ajax/');

			if ($('#frame').attr('src') != undefined) {
				ds_url = $('#frame').attr('src');
				window.open(ds_url, '_blank', 'width=665,height=600,scrollbars=yes,resizeable=yes');
			}else {
				$.ajax({
					  url: ds_url,
					  success: function(data) {
						$('#printCache').append(data);
						newwin = window.open(''+ base_uri +'/print.php', '_blank', 'width=665,height=600,scrollbars=yes,resizeable=yes');
					  }
				});	
			}
		});
	}

	$('.content_block table:not(.normal, table table) tr th:first-child').prepend('<div class="tablecorner_left"></div>');
	$('.content_block table:not(.normal, table table) tr th:last-child').prepend('<div class="tablecorner_right"></div>');
	$('#content_box .content_block table tbody tr td table:not(table table)').each(function(){
		var w = $(this).css('width');
		w = w.replace('px', '');
		w = parseInt(w)+6;
		$(this).css('width', w+'px');
	});

	$("a[rel^='prettyPhoto']").prettyPhoto();
	
	$(".text ul, .text ol").each(function(){
		var list = this;
		var prev = $(list).prev("p").find("strong, b");
		if (prev) prev.unwrap();
	});

	/* GOOGE TRACKING FOR LINKLIST DOWNLOADS */
	
	$(".linklist a").click(function(e){
		var text = $(this).attr("href"); 
		text = text.split("/");
		text = text[text.length-1];
		text = text.split(".");
		if (text.length > 1) {
			var endung = text[text.length-1];
			delete(text[text.length-1]);
			if (text.length > 2) text = text.join(".");
			else text = text[0];
			_gaq.push(['_trackEvent','Downloads','Click',category_an+'-'+text+'-'+endung]);
		}
	});
		
		
	function setCookie(key,value) {
		var now =new Date();
		var timeout = new Date(now.getTime()+86400000);
		document.cookie=key+"="+value+";expires="+timeout.toGMTString()+";";
	}

	function getCookie() {
		value = "";
		if(document.cookie) {
			valuestart = document.cookie.indexOf("=") + 1;
			valueend = document.cookie.indexOf(";");
			if(valueend == -1) valueend = document.cookie.length;
			value = document.cookie.substring(valuestart,valueend);
		}
		return value;
	}

	if (getCookie() !== 'false') {
		$("#symboldinfo").addClass("visible").find(".icon").html("X");
	}
		
	$("#symboldinfo").click(function(){
		if ($(this).hasClass("visible")) {
			$(this).removeClass("visible").find(".icon").html("?");
			setCookie('showSym', false);
		}else {
			$(this).addClass("visible").find(".icon").html("X");;
			setCookie('showSym', true);
		}
	});

	window.onresize = function(e){
		var w = $(window).width();
		if (w <= 1225 && $("#symboldinfo").hasClass("visible")) $("#symboldinfo").click();
	}
	
});
