var carousel_items = new Array();
jQuery(function($) {
	init();	
});

function init() {

	/**** Facetten ****************************************************/
	$('#content .navi ul.suche_verf .alle').live('click', function () {
		var $element = $(this).parent().parent();
		$.get($(this).attr('href'), function (data) {
			$element.replaceWith(data);
		});
		return false;
	});

	/**** Empfänger hinzufügen ****************************************/
	$('.eing a.add-recipient').click(function() {
		var n = $('.input-fields .section').length;

		var id_name, id_email;
		var div_name, div_email;

		div_name  = $($('.input-fields .section.first .line').get(0));
		div_email = $($('.input-fields .section.first .line').get(1));

		id_name  = $('.eing input', div_name).attr('id');
		id_email = $('.eing input', div_email).attr('id');
		name_name  = $('.eing input', div_name).attr('name');
		name_email = $('.eing input', div_email).attr('name'); 
		
		
		$('.eing input', div_name).attr('id', id_name + '-' + n);
		$('.eing input', div_name).attr('name', name_name.replace(/\d/g, n));
		$('.beschr label', div_name).attr('for', id_name + '-' + n);
		$('.eing input', div_email).attr('id', id_email + '-' + n);
		$('.eing input', div_email).attr('name', name_email.replace(/\d/g, n));
		$('.beschr label', div_email).attr('for', id_email + '-' + n);
		
		var p = $(this).parents('.inputfeld');
		var c = $('.input-fields .section.first').html();
		$('.input-fields', p).append('<div class="section">' + c + '</div>');
		
		// reset id's
		$('.eing input', div_name).attr('id', id_name);
		$('.eing input', div_name).attr('name', name_name);
		$('.beschr label', div_name).attr('for', id_name);
		$('.eing input', div_email).attr('id', id_email);
		$('.eing input', div_email).attr('name', name_email);
		$('.beschr label', div_email).attr('for', id_email);
		
		if(n+1 >= 5) {
				$(this).hide();
		}
		if(n+1 >=2) {
			$('.eing a.remove-recipient').show();
		}
		
	});
	
	$('.eing a.remove-recipient').hide();
	$('.eing a.remove-recipient').click(function() {
		var n = $('.input-fields .section').length;
		if(n > 1) {
			 $('.input-fields .section:last-child').remove();
			 $('.eing a.add-recipient').show();
			 if(n == 2)	 {
				 $(this).hide();
			 }
		}												 
	});

	   /**** Produkt weiterempfehlen: Empfänger hinzufügen ********************/
    $('.eing a.add-recipient2').click(function() {
        var inputField = $(this).parents('.inputfeld').find('.input-fields');
        var n = inputField.find('.section').length;
        var copy = inputField.find('.section.first').clone();
        
        copy.removeClass('first');
        $('input', copy).attr('name', function() {
            return this.name.replace('[0]', '[' + n + ']');
        });
        $('input', copy).attr('id', function() {
            return this.id.replace('-0', '-' + n);
        });
        $('label', copy).attr('for', function() {
            return this.htmlFor.replace('-0', '-' + n);
        });
        $('input', copy).attr('value', '');
        $('.fehler', copy).removeClass('fehler');
        
        copy.appendTo(inputField);
    });
    
	/**** Passwortsicherheit ******************************************/
	$('#pass_neu').keyup(function() {
	 	var pwVerdictNames = [
			"sehr niedrig",
			"niedrig",
			"mittel",
			"hoch",
			"sehr hoch"
		];
		var pwVerdictClass = [
			'sa_1',
			'sa_1',
			'sa_2',
			'sa_3',
			'sa_3',
			'sa_0'
		];

		var verdict = "zu kurz";
		var level = 0;
		if (this.value.length >= 6 ) {
			var result = testPassword(this.value);
			level   = result.level;
			verdict = pwVerdictNames[level];
		} else if (this.value.length == 0) {
			level   = 5;
			verdict = '';
		}

		$('.pw_sicherheit')
			.removeClass('sa_0')
			.removeClass('sa_1')
			.removeClass('sa_2')
			.removeClass('sa_3')
			.addClass(pwVerdictClass[level]);
		$('.pw_sicherheit .sich_txt span').text(verdict);
	});


	/**** Apothekertipps **********************************************/

	$('.apo_tipps .apo_tipp_selected_subjects .apo_tipp_subjects').hide();

	if ($('.apo_tipps .apo_choice a.selected').length) {
		var i = $('.apo_choice a').index($('.apo_choice a.selected')[0]);
		$($('.apo_tipps .apo_tipp_selected_subjects .apo_tipp_subjects').get(i)).show();
	}
	$('.apo_choice a').click(function() {
		var i = $('.apo_choice a').index(this);
		$($('.apo_tipps .apo_tipp_selected_subjects .apo_tipp_subjects').hide().get(i)).show();

		$('.apo_choice a').removeClass('selected');
		$(this).addClass('selected');
	});

	/**** Freundschaftswerbung ****************************************/
	$('.kunden_werben_kunden .kwk_box .content input').each(function(i, val) {
		if (i > 0) {
			$(this).hide();
		}
	});
	$('.kunden_werben_kunden .kwk_box .content .ic_plus').click(function() {
		$('.kunden_werben_kunden .kwk_box .content input').show();
		$(this).hide();
	});


	/**** Online Bestellschein ****************************************/
	
	
	$('.textfeld .best_line .ob_plus').click(function() {
		 
		 		 
		 for(i=0; i<5; i++)
		 {			 
			 $('.input_group').append(
									  $('.best_line:first-child').clone()
									  .removeClass('fehler')
									  .find('.fehler').removeClass('fehler').end()
									  .find('.best_art input').attr('value', '').end()
									  .find('.best_anz input').attr('value','2').end()
									  );
			}

	});


	/**** Carousel ****************************************************/	
	$('ul.scroll_sprite').each(function(i, val) {
		carousel_items.push(new Array());
		$('li', this).each(function(j, val) {
			var	mySrc     = $('a > img', this).attr('src');
			var myHref    = $('a', this).attr('href');
			
			/*** Transport alt and title tags too ***/
			var myAlt			= $('a > img', this).attr('alt');
			var myTitle		= $('a > img', this).attr('title');
			
			var myHTML    = $('div', this).html();

			var item = {url: mySrc, link: myHref, html: myHTML, alt: myAlt, title: myTitle};
			carousel_items[i].push(item);
		});
	});
	$('ul.scroll_sprite').jcarousel({
		scroll: 1,
		wrap: null,
		initCallback: dm_carousel_initwrap,
		itemVisibleInCallback:  {onBeforeAnimation: dm_carousel_itemVisibleInCallback},
		itemVisibleOutCallback: {onAfterAnimation:  dm_carousel_itemVisibleOutCallback}
	});
	$('ul.scroll_sprite li .prod_beschr').hide();

	/**** Datennutzung ***********************************************/
	$('.daten_nutzung .btn_angaben_uebernehmen').click(function() {
		$('.daten_nutzung input.oneway:checked')
			.attr('disabled', 'disabled')
			.parent('div.line').addClass('inakt');
	});

	/**** Tabs *******************************************************/
	$('.tab_line a').click(function() {
		$($(this).parents().get(0)).find('a').removeClass('akt');
		$(this).addClass('akt');
		$(this).blur();

		var i = $($(this).parents().get(0)).find('a').index(this);
		
		
		$($(this).parents().get(0)).nextAll('.tab').hide();
		$($($(this).parents().get(0)).nextAll('.tab').get(i)).show();
		
		$('.tab_container .btn_line a').hide();
		$('.tab_container .btn_line').find('a:eq(' + i + ')').show();
		
		

	});
	
	

	/**** Fliptext ***************************************************/
	$('.flip_text').css('display', 'none');
	$('a.flip_link').click(function() {
		$(this).hide();
		$($(this).nextAll('.flip_text').get(0)).show();
	});

	$('a.flip_link_close').unbind('click').click(function() {
		var f = $($(this).parents().get(0));
		f.hide();
		$(f.prevAll('a.flip_link').get(0)).show();
	});


	/**** Suche ******************************************************/
	var suche_input_default = 'Begriff, PZN, Medikament, PLZ';
	
	if ($('#suche_input').val() == '') {
		$('#suche_input').val(suche_input_default)
	}
	
	$('#suche_input')
		.blur(function() {
			if ($(this).val() == '') $(this).val(suche_input_default);
		})
		.focus(function() {
			if ($(this).val() == suche_input_default) $(this).val('');
		});
		
		
	
	/**** Miniwarenkorb **********************************************/
	$('#suche .suche_griff').click(function() {
		if ($('#suche').hasClass('suche_closed')) {
			$('#suche').removeClass('suche_closed');
			$('#suche').addClass('suche_open');
		} else {
			$('#suche').addClass('suche_closed');
			$('#suche').removeClass('suche_open');
		}
	});

	/**** Mein DocMorris / Kunden werben Kunden **********************/
	var kwk_tell_a_friend_default = 'E-Mail-Adresse des Freundes';
	$('#kwk-tell-a-friend input')
		.val(kwk_tell_a_friend_default)
		.blur(function () {
			if ($(this).val() == '') $(this).val(kwk_tell_a_friend_default);
		})
		.focus(function () {
			if ($(this).val() == kwk_tell_a_friend_default) $(this).val('');
		});
		
	/**** Kontaktformular ********************************************/
	$('#kontaktformular #betreff').change(function() {
		$('#betreff-auswahl .betreff-auswahl').hide();
		var idx = $('option', this).index($(':selected', this)) - 1;
		if (idx >= 0) {
			$($('#betreff-auswahl .betreff-auswahl').get(idx)).show();
		}
	});
	$('#betreff-auswahl .betreff-auswahl').hide();

	/**** Accordion **************************************************/
	$('.accordion').each(function(i, val) {
		$('.accordion-item', this).each(function(i, val) {
			if ($('input:radio:not(:checked)', this).length || ($('input:radio', this).length == 0))
				$('.accordion-fold', this).hide();
			if ((i == 0) && (($('.accordion-head input:radio', this).length == 0)
				|| ($('.accordion-head input:radio:checked', this).length > 0))) {
				$('.accordion-fold', this).show();
				$('.accordion-head', this).addClass('akt');
			}
		});
	});
	$('.accordion-select').click(function() {
		var accordion = $(this).parents('.accordion').get(0);
		if ($(this).parents('.accordion-item').find('.accordion-fold:hidden').length) {
			$('.accordion-item .accordion-fold', accordion).slideUp('fast');
			$('.accordion-item .accordion-head', accordion).removeClass('akt');
			$(this).parents('.accordion-item').find('.accordion-fold').slideDown('fast');
		}
		$(this).parents('.accordion-item').find('.accordion-head').addClass('akt').blur();
	});

	/**** Auswahl Rezeptart ******************************************/
	init_rezart();

	/**** Daten prüfen/Ändern ****************************************/
	$('h2 a.link_daten_aendern').click(function() {
		$('div[id^=daten_][id$=_edit]').hide();
		$('div[id^=daten_][id$=_output]').show();
		$(this).parent().next().hide();
		$(this).parent().next().next().show();
		$('.btn-main').hide();
	});
	$('h2 a.link_daten_aendern.new-page').unbind('click');
	$('div[id^=daten_][id$=_edit] a.btn_bearbeitungabbrechen').click(function() {
		$(this).parents('div[id^=daten_][id$=_edit]').hide();
		$('div[id^=daten_][id$=_output]').show();
		$('.btn-main').show();
	});
	$('div.editfeld a.btn_datenspeichern').click(function() {
	});

	/**** Tooltips ***************************************************/
	$('.show-tooltip').tooltip({
		showURL:false,
		opacity: 1,
		track: true,
		fade: 150
	});
	$('.show-tooltip-click').tooltip({
		showURL:false,
		track: true,
		opacity: 1,
		extraClass: 'tooltip big',
		showBody: " - ",
		fade: 150,
		trigger: ['click', 'mouseout']
	});
	$('.show-tooltip-mouseover-marke').tooltip({
		showURL:false,
		track: true,
		opacity: 1,
		extraClass: 'tooltip',
		fade: 150,
		trigger: ['mouseover', 'mouseout'],
		bodyHandler: function() {
			var id = $(this).attr('class');
			var p = id.indexOf('show-tooltip-id');
			id = id.substring(0, p - 1) + id.substring(p + 15, id.length);
			p = id.indexOf('tooltip-');
			if (p < 0) {
				return '';
			}
			if (id.indexOf(' ', p) < 0) {
				id = id.substring(p);
			} else {
				id = id.substring(p, id.indexOf(' ', p) - 1);
			}
			return $('#' + id).html();
		}
	});	
	$('.show-tooltip-mouseover-id').tooltip({
		showURL:false,
		track: true,
		opacity: 1,
		extraClass: 'tooltip big',
		fade: 150,
		trigger: ['mouseover', 'mouseout'],
		bodyHandler: function() {
			var id = $(this).attr('class');
			var p = id.indexOf('show-tooltip-id');
			id = id.substring(0, p - 1) + id.substring(p + 15, id.length);
			p = id.indexOf('tooltip-');
			if (p < 0) {
				return '';
			}
			if (id.indexOf(' ', p) < 0) {
				id = id.substring(p);
			} else {
				id = id.substring(p, id.indexOf(' ', p) - 1);
			}
			return $('#' + id).html();
		}
	});
	$('.show-tooltip-id').tooltip({
		showURL:false,
		track: true,
		opacity: 1,
		extraClass: 'tooltip big',
		fade: 150,
		trigger: ['click', 'mouseout'],
		bodyHandler: function() {
			var id = $(this).attr('class');
			var p = id.indexOf('show-tooltip-id');
			id = id.substring(0, p - 1) + id.substring(p + 15, id.length);
			p = id.indexOf('tooltip-');
			if (p < 0) {
				return '';
			}
			if (id.indexOf(' ', p) < 0) {
				id = id.substring(p);
			} else {
				id = id.substring(p, id.indexOf(' ', p) - 1);
			}
			return $('#' + id).html();
		}
	});
	
	$('.show-tooltip-rezart').tooltip({
				
		left: -185,
		trigger: ['click', 'mouseout'],
		showURL: false,							  
		bodyHandler: function() { 
		
		var content = $('#eigenanteil').clone();
		var fbetragdiff = $(this).children('.fbetragdiff').html();
		var geszz = $(this).children('.geszz').html();
		var eigenanteil = $(this).children('.eigenanteil').html(); 
		
		content.css('display', 'block');
		content.find('.insfbetragdiff').html(fbetragdiff + " &euro;");
		content.find('.insgeszz').html(geszz + " &euro;");
		content.find('.insres').html(eigenanteil + " &euro;");
		
		return content;
		
		}
									  
									  });

	/**** Reset ******************************************************/
  $('.reset12').click(function() {
  	$(this).parents('form').get(0).reset();
  	$('select', $(this).parents('form')).trigger('change');
  	return false;
  });
  	/**** Hauptnavi **************************************************/
  	$("#hauptnavi a:not(.active)").hover(function() {
		var aElem = $(this).parent().next().find("a");
		aElem.addClass("nobg");
		$(this).addClass("nobg");
	}, function() {
		var aElem = $(this).parent().next().find("a");
		aElem.removeClass("nobg");
		if (!$(this).hasClass("firstchild") && !$(this).parent().prev().find('a').hasClass('active')) {
			$(this).removeClass("nobg");
		}
	});
  	$("#hauptnavi a.active").each(function() {
		var aElem = $(this).parent().next().find("a");
		aElem.addClass("nobg");
		$(this).addClass("nobg");
  	});
	
	
	input_submit();
	
	DOCMORRIS.init();
	
}

DOCMORRIS = {

	init : function () {

		// Order Form UE
		if ($("form[name=onlineOrderForm]").length > 0) {
			DOCMORRIS.orderForm.sortEmptyDown();
		}	
		
		// themenshop
		if ($('.themenshop').length > 0) {
			DOCMORRIS.themenshop.init();
		}
		
		// fix layout of two row badge
		DOCMORRIS.layoutFix.badge();
		
		// handles html bestellschein
		DOCMORRIS.bestellschein.init();
		
	},
		
	orderForm : {
		
		sortEmptyDown : function () {
			var iLines = $("form[name=onlineOrderForm] .input_group div div").length-2;
			for (var i=iLines; i>=0; i--) {
				if ($("form[name=onlineOrderForm] .input_group div div:eq("+i+") input:eq(0)").val() !== '') {
					$("form[name=onlineOrderForm] .input_group div:eq(0)").prepend($("form[name=onlineOrderForm] .input_group div div:eq("+i+")"));
				}
			}
		}
	},
	
	layoutFix : {
		
		badge : function () {
			$('.stoerer table').each(function () {											/* changed by heiko.hardt 12.09.2010 from: $('.stoerer span').each(function () { */
                var iLineHeight = parseInt($(this).css('font-size').replace('px', '')) + 4; // get computed font-size --> LineHeight 
				if ($(this).height() > iLineHeight) {
					$(this).addClass('tworows');
				};
				
				if($(this).closest('.prod_img').find('a').length > 0 ) {
					$(this).closest('.stoerer')
					.css('cursor', 'pointer')
					.click( function(){
									 location.href = $(this).closest('.prod_img').find('a').attr('href');
									  });
				}
				
				if($(this).closest('.prod_det_img').find('a').length > 0 ) {
														
					$(this).closest('.stoerer')
					.css('cursor', 'pointer')
					.click( function(){
									 location.href = $(this).closest('.prod_det_img').find('a').attr('href');
									  });
				}
				
				
				
			})
		}
		
	},
	
	themenshop : {
		
		init : function () {
			
			// bind events show/hide to toggle trigger
			$('.toggle, .toggle_trigger_all').live('click', DOCMORRIS.themenshop.showTopic);
			$('.toggle, .toggle_trigger_less').live('click', DOCMORRIS.themenshop.hideTopic);

			DOCMORRIS.themenshop.hideTopic();
			
		},
		
		showTopic : function () {
			$('.toggle, .toggle_trigger_less').show();
			$('.toggle_trigger_all').hide();

			sIFR.replace(archer_semibold, {
				  selector: '.teaser_box_small.toggle .teaser_text h2',
				  wmode: 'transparent',
				  css: '.sIFR-root { background-color: #FFFFFF; color: #333333; }',
				  ratios: [8, 1.41, 10, 1.33, 14, 1.31, 16, 1.26, 20, 1.27, 24, 1.26, 25, 1.24, 26, 1.25, 35, 1.24, 49, 1.23, 74, 1.22, 75, 1.21, 79, 1.22, 80, 1.21, 81, 1.22, 1.21]
			});
			
		},
		
		hideTopic : function () {
			$('.toggle, .toggle_trigger_less').hide();
			$('.toggle_trigger_all').show();
		}
		
	},
	
	bestellschein : {
		
		init : function () {
		
			$('#triggerHTMLBestellschein').click(function () {
				$('#rahmen').hide(); // hide page
				$('body').append($('#print1')); // move bestellschein below body
				$('#print1').show(); // show bestellschein
				return false;
			});
			
			$('#print1 .btn_zurueck').click(function () {
				$('#print1').hide(); // hide bestellschein
				$('#rahmen').show(); // show page
				return false;
			});
			
			$('.btn_bestellschein_drucken.print').click(function () {
				window.print();
				return false;
			});
			
		}
		
		
	}
	
};

function makeModal(errortext) {
		$('.layer .fehler').html(unescape(errortext));
		if ($.browser.msie) {
			$('iframe').hide(); // fix iframe issue in IE
		}
		tb_show(null, "#TB_inline?height=90&amp;width=544&amp;inlineId=modal_box&amp;modal=true", null);
}

function bindToolTip() {
	$('iframe').contents().find('.show-tooltip-click').tooltip({
		showURL:false,
		track: true,
		opacity: 1,
		extraClass: 'tooltip big',
		showBody: " - ",
		fade: 150,
		trigger: ['click', 'mouseout'],
		top: 350,
		left: 270
	});
}


/**** Auswahl Rezeptart ********************************************/
function init_rezart() {
	$('input[name=rez_art]').click(function() {
		var q = $(this).parents().get(1);
		$(q).find('.rez_wahl').removeClass('selected');
		var p = $(this).parents().get(0);
		$(p).addClass('selected');
		
		var i = $(q).find('.rez_wahl input[name=rez_art]').index(this);
		$(this).parents().find('.packungsgroesse table').hide();
		$($(this).parents().find('.packungsgroesse table').get(i)).show();
	});
}

/**** Schriftgroessenaenderung **************************************/
var container = "body";

$(document).ready(function(){

  // Schriftgrš§e Normal
  $(".fontsize .standard").click(function() {
      $(container).css('font-size', 11).removeClass();
      setFontsize('fsStandard');
     });

  // Schriftgrš§e Mittel
  $(".fontsize .middle").click(function() {
      $(container).css('font-size', 14).removeClass().addClass("middle");
      setFontsize('fsMiddle');
     });

  // Schriftgrš§e Gro§
  $(".fontsize .big").click(function() {
      $(container).css('font-size', 18).removeClass().addClass("big");
      setFontsize('fsBig');
     });
});
function setFontsize(size) {
    jQuery.ajax( {
        type : "POST",
        url : "web/shop/setFontsize.do",
        dataType : "html",
        data : "dmnwFontsize="+size
    });
}

/**** Hilfsfunktionen für Formulare ********************************/
function form_remove_default(obj, val) {
	if (obj.value == val) {
		obj.value = '';
	}
}
function form_restore_default(obj, val) {
	if (obj.value == '') {
		obj.value = val;
	}
}


/**** Hilfsfunktionen für Carousel ********************************/
var dm_carousel_timers = [];
function dm_carousel_itemVisibleInCallback(carousel, item, i, state, evt) {
	// The index() method calculates the index from a
	// given index who is out of the actual item range.
	var j = $('ul.scroll_sprite').index(carousel.list);
	var idx = carousel.index(i, carousel_items[j].length);
	var item = carousel_items[j][idx - 1];
	var obj = carousel.add(i, dm_carousel_getItemHtml(item));
	var box = $('.scroll_box').get(j);

	$('img', obj).mouseover(function(e) {
 		var i = $('li img', box).index(this);
 		var info = $($('.scroll_box_item_info').get(j));
 		
 		var p_this = $(this).offset();
 		var p_box  = $(this).parents('.scroll_box').offset();
		
	
		
		var position_y = $(this).parents('.scroll_box').position().top + 100;
		
		
		
		
		$(this).closest(".col_1").addClass('ie67_zindex_fix');

 		info.html(dm_carousel_getInfoHtml(item))
			.removeClass('hidelayer')
			.addClass('showlayer')
			
			
			if( e.clientY+ 80 + $(info).height() > $(window).height())
		{
			position_y -= 100 + $(info).height();
		}
		
			
			info.css({'top': position_y, 'left': p_this.left - p_box.left + 30})
		//	.css({'top': p_box.top - 70, 'left': p_this.left - p_box.left + 30})
			.unbind('mouseover')
			.mouseover(function() {
				window.clearTimeout(dm_carousel_timers[j]);
			})
			.unbind('mouseout')
			.mouseout(function() {
				dm_carousel_start_hide_info(j, i);
				
			});

		window.clearTimeout(dm_carousel_timers[j]);

		$('li img', box).css({'width': 48, 'height': 48});
		$(this).css({'width': 60, 'height': 60});

	}).mouseout(function() {
		var i = $('li img', box).index(this);
		dm_carousel_start_hide_info(j, i);
		
	});
}
function dm_carousel_start_hide_info(j, i) {
	dm_carousel_timers[j] = window.setTimeout("dm_carousel_hide_info(" + j + "," + i + ")", 300);
}
function dm_carousel_hide_info(j, i) {
	var box = $($('.scroll_box').get(j));
	var obj = $('li img', box).get(i);

	$($('.scroll_box_item_info').get(j))
		.removeClass('showlayer')
		.addClass('hidelayer');
	
	$(obj).css({'width': 48, 'height': 48});
	
	dm_carousel_timers[j] = null;
	$(".col_1").removeClass('ie67_zindex_fix');
}
function dm_carousel_itemVisibleOutCallback(carousel, item, i, state, evt) {
	carousel.remove(i);
}
function dm_carousel_getItemHtml(item) {
 	return '<a href="' + item.link + '"><img src="' + item.url + '" width="48" height="48" alt="' + item.alt + '" title="' + item.title + '" /></a>';
}
function dm_carousel_getInfoHtml(item) {
	return '<div class="prod_beschr">' + item.html + '</div>';
}

function dm_carousel_initwrap(o, state) {
	
	
	var parent_scroll_box = $(o.list).closest(".scroll_box");
	
	if ((o.size() > 4) && !parent_scroll_box.hasClass("no_infinite")) o.options.wrap = "circular";
}


function dm_render_history_back_button() {
	document.write('<div class="btn-history-back"><a class="pfeil_link rev" href="#" onclick="history.back(); return false;">zurück</a></div>');
}

function reinit() {
	init();
}







/* ************************************************************
Created: 20060120
Author:  Steve Moitozo <god at zilla dot us> -- geekwisdom.com
Description: This is a quick and dirty password quality meter
		 written in JavaScript so that the password does
		 not pass over the network.
License: MIT License (see below)
Modified: 20060620 - added MIT License
Modified: 20061111 - corrected regex for letters and numbers
                     Thanks to Zack Smith -- zacksmithdesign.com
---------------------------------------------------------------
Copyright (c) 2006 Steve Moitozo <god at zilla dot us>

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

   The above copyright notice and this permission notice shall
be included in all copies or substantial portions of the
Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
---------------------------------------------------------------

 CHANGED BY:
   Docmorris N.V.

************************************************************ */
var testPassword_log = "";

function testPassword(passwd) {
  var intScore  = 0;
  var strLog = ""

  // PASSWORD LENGTH
  lengthScore = passwd.length * 3;
  intScore += lengthScore;
  strLog += "Length " + passwd.length + " : +" + lengthScore + "\n";


  if (passwd.match(/[a-z]/))  // [verified] at least one lower case letter
  {
  	intScore += 4
  	strLog += "At least lower case: +4\n"
  }

  if (passwd.match(/[A-Z]/))  // [verified] at least one upper case letter
  {
  	intScore += 10
  	strLog += "At least one upper case: +10\n"
  }

  if (passwd.match(/(.*[A-Z].*[A-Z])/))  // [verified] at least two upper case letter
  {
  	intScore += 15
  	strLog += "At least two upper case: +15\n"
  }


  // NUMBERS
  if (passwd.match(/\d+/)) // [verified] at least one number
  {
  	intScore += 10
  	strLog += "At least one number: +10\n"
  }

   if (passwd.match(/(.*[0-9].*[0-9])/))  // [verified] at least one number
  {
  	intScore += 15
  	strLog += "At least two numbers: +15\n"
  }


  // SPECIAL CHAR
  if (passwd.match(/[^a-zA-Z0-9]/))   // [verified] at least one special character
  {
  	intScore += 15
  	strLog += "At least one special char: +15\n"
  }

  // [verified] at least two special characters
  if (passwd.match(/(.*[^a-zA-Z0-9].*[^a-zA-Z0-9])/))
  {
  	intScore += 15
  	strLog += "At least two special char: +15\n"
  }


  // COMBOS
  if (passwd.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/))   // [verified] both upper and lower case
  {
  	intScore += 12
  	strLog += "Both upper and lowercase letters: +12\n"
  }

  if (passwd.match(/([a-zA-Z])/) && passwd.match(/([0-9])/)) // [verified] both letters and numbers
  {
  	intScore += 12
  	strLog += "Both letters and numbers: +12\n"
  }

  // [verified] letters, numbers, and special characters
  if (passwd.match(/([a-zA-Z0-9].*[^a-zA-Z0-9])|([^a-zA-Z0-9].*[a-zA-Z0-9])/))
  {
  	intScore += 10
  	strLog += "Combo letters or numbers and special chars: +10\n"
  }

  // SPECIALS

  // Only lower chars get -4 points
  if (passwd.match(/^[a-z]+$/))
  {
  	intScore -= 4
  	strLog += "Only lower chars: -4\n"
  }

  // Only upper chars get -22 points
  if (passwd.match(/^[A-Z]+$/)  )
  {
  	intScore -= 25
  	strLog += "Only upper char: -25\n"
  }

  // Only numbers get -22 points
  if (passwd.match(/^[0-9]+$/) )
  {
  	intScore -= 25
  	strLog += "Only numbers: -25\n"
  }

  // Repitions give negative points
  var rep = (checkRepetition(1, passwd).length - passwd.length);
  if(rep != 0) {
 	 intScore += rep
 	 strLog += "Repition 1 penalty: " + rep + "\n"
  }
  rep = (checkRepetition(2, passwd).length - passwd.length);
  if(rep != 0) {
 	 intScore += rep
 	 strLog += "Repition 2 penalty: " + rep + "\n"
  }
  rep = (checkRepetition(3, passwd).length - passwd.length);
  if(rep != 0) {
 	 intScore += rep
 	 strLog += "Repition 3 penalty: " + rep + "\n"
  }
  rep = (checkRepetition(4, passwd).length - passwd.length);
  if(rep != 0) {
 	 intScore += rep
 	 strLog += "Repition 4 penalty: " + rep + "\n"
  }

  if(intScore > 100) {
  	intScore = 100;
  } else if(intScore < 0) {
  	intScore = 0;
  }

  var level;

  if(intScore < 20) {
    level = 0
  } else if (intScore >= 20 && intScore < 35) {
    level = 1
  } else if (intScore >= 35 && intScore < 60) {
    level = 2
  } else if (intScore >= 60 && intScore < 90) {
    level = 3
  } else {
    level = 4
  }


  var result = {
  	score : intScore,
  	level : level
  }

  return result;
}


function checkRepetition(pLen,str) {
	res = ""
	var repeated = false;
	for ( i=0; i < str.length; i++ ) {
		repeated=true
		for (j=0; j < pLen && (j+i+pLen) < str.length; j++)
		{
			repeated = repeated && (str.charAt(j + i) == str.charAt(j + i + pLen))
		}
		if (j < pLen) {
		 	repeated=false
		}
		if (repeated) {
			i += pLen-1;
			repeated = false;
		} else {
			res += str.charAt(i);
		}
	}
 	return res
}

/**** Form Submit Inpubutton *********************/

function input_submit() {

	$('form input').focus(function()
			{
				$(this).data('safeEnter_InAutocomplete', false);
			});


	$('form input').keypress(function(e){
									  									  
		var key = (e.keyCode ? e.keyCode : e.which);						  
									  
    	  
		switch(key) {
		  
			case 13:
		   
		    	if (!$(this).data('safeEnter_InAutocomplete') || !$(this).is('input[type=text]') || $.browser.opera)
				{
       				var parent_form = $(this).closest('form');
	   				parent_form.submit();
					e.preventDefault();
				}
			
				$(this).data('safeEnter_InAutocomplete', false);
				e.preventDefault();
				break;
				
		  	case 40:
			case 38:
			case 34:
			case 33:
						// down=40,up=38,pgdn=34,pgup=33
				$(this).data('safeEnter_InAutocomplete', true);
				break;

			default:
				$(this).data('safeEnter_InAutocomplete', false);
				break;

			  }			
      	});
}

/**** Videoplayer ********************************/


// function for ajax-request layer
// REQUIRES: INTEGRATED CONTENT ARRAY ON PAGE e.g. 11.1_xxx
function buildVideoPlayer() {
	
	if(videosource.length > 0) {
										
		var flashvars = {
			autostart: "true",
            file: videosource[0].videosrc,
            image: videosource[0].still,
            skin: "/web/swf/jwplayer/skins/docmoskin.zip",
            author: "DocMorris",
            screencolor: "FFFFFF"
			};
		var params = {
			allowScriptAccess: "sameDomain",
			allowFullScreen: "false",
			wmode: "transparent"
			};
		var attributes = {};
		
		swfobject.embedSWF("/web/swf/jwplayer/player.swf", "video_content", "448", "278", "10.0.0.0",false, flashvars, params, attributes);
		$(".video_title").html(videosource[0].title);
		$(".video_subheader").html(videosource[0].subheader);
		$(".video_descr_top").html(videosource[0].descr_top);
		$(".video_descr_bottom").html(videosource[0].descr_bottom);
		if(videosource.length > 1)
		{
		// Thumbnail Links
		$.each(videosource, function(index, map) {
									 
			// Build Content					 
			var thumb_content = "<div id='tno" + index + "' class='thumb'><a href='" + map.videosrc +"'><img src='" + map.thumb + "' alt='' /></a><h3>" + map.title +"</h3><p>" + map.short + "</p><a href='" + map.videosrc +"' class='pfeil_link'>Video ansehen</a></div>";
			$(".thumb_stage").append(thumb_content);
			
			});
			// Add akt to firstchuild
			$(".thumb:first-child").addClass("akt");
			// Navigation Clickfunction
			$(".thumb a").click(function(event) {
										 
				//get the index
				var x = $(this).parent().attr("id").match("[0-9]+");
				$(".thumb").removeClass("akt");
				$(this).parent().addClass("akt");
				flashvars.file = this.href;
				$(".video_title").html(videosource[x].title);
				$(".video_subheader").html(videosource[x].subheader);
				$(".video_descr_top").html(videosource[x].descr_top);
				$(".video_descr_bottom").html(videosource[x].descr_bottom);
				flashvars.image = videosource[x].still;
				swfobject.embedSWF("/web/swf/jwplayer/player.swf", "video_content", "448", "278", "10.0.0.0",false, flashvars, params, attributes);
				event.preventDefault();
				});
		}
		// Wenn keine weiteren Videos vorhanden sind
		else
		{
			$(".thumb_stage").append("<p>keine weiteren Videos</p>");	
		}
	}
	// Handling for no available thumbs	else
	else {
		$(".video_title").html("Keine Videos vorhanden");
		$(".video_stage").html("<p>Es stehen keine Videodateien zur Verfügung</p>");
		$(".thumb_stage").html("");	
	}
	
}


// function for onpage flashlayers
// REQUIRES: INTEGRATED FLASH LAYERS ON PAGE e.g. 11.1.2_xxx
// function for onpage Flashlayer
function loadVideoPlayer(videoimg)
{
	// Do it only if thumbs are available
	if( $(".thumb").length > 0)
	{
	
		// Hide Data Containers
		$(".data").css("display", "none");
		
	
		// Get data for initial video
		var initialVideo = $(".thumb:first-child a:first-child").attr("href");
		var initialTitle = $(".thumb:first-child h3").html();
		var initialDescrTop = $(".thumb:first-child .data .descr_top").html();
		var initialSubheadline = $(".thumb:first-child .data .subheadline").html();
		var initialDescrBottom = $(".thumb:first-child .data .descr_bottom").html();
		
		// Load initial video
		var flashvars = {
				autostart: "false",
				file: initialVideo,
	            image: videoimg,
	            skin: "/web/swf/jwplayer/skins/docmoskin.zip",
	            author: "DocMorris",
	            screencolor: "FFFFFF"
				};
		var params = {
				allowScriptAccess: "sameDomain",
				allowFullScreen: "false",
				wmode: "transparent"
				};
		var attributes = {};
		swfobject.embedSWF("/web/swf/jwplayer/player.swf", "video_content", "448", "278", "10.0.0.0",false, flashvars, params, attributes); 
		
		// Fill initial Content
		$(".video_title").html(initialTitle);
		$(".video_descr_top").html(initialDescrTop);
		$(".video_subheadline").html(initialSubheadline);
		$(".video_descr_bottom").html(initialDescrBottom);
		
		// Add class to first Thumbnail
		$(".thumb:first-child").addClass("akt");
		
		
		// Clickfunction for thumbnails	
		$(".thumb a").click(function(event) { 
			
			// Get data container that belongs to clicked anchor tag
			var dataObject = $(this).parent(".thumb").children(".data");
			
			// Remove class and add it to thumb that belongs to clicked anchor tag
			$(".thumb").removeClass("akt");
			$(this).parent(".thumb").addClass("akt");
			
			// Change content and load new video
			flashvars.file = this.href;
			flashvars.image = dataObject.children(".still").attr("src");
			
			swfobject.embedSWF("/web/swf/jwplayer/player.swf", "video_content", "448", "278", "10.0.0.0",false, flashvars, params, attributes);
			
			$(".video_title").html($(this).parent(".thumb").children("h3").html());
			$(".video_descr_top").html(dataObject.children(".descr_top").html());
			$(".video_subheadline").html(dataObject.children(".subheadline").html());
			$(".video_descr_bottom").html(dataObject.children(".descr_bottom").html());
			
			event.preventDefault();						 
			});
	}
	// Handling for no available thumbs
	else
	{
		$(".video_title").html("keine Videos vorhanden");
		$(".video_stage").html("<p>Es stehen keine Videodateien zur Verfügung</p>");
		$(".thumb_stage").html("");	
	}
	
}

// PAGE-INATOR VERORDNUNGSARTEN

 function paginatorVerordnung() {
   	
	var dots = "<span style='padding: 0; font-size: 9px;'>...</span>" ;
	
	// Check for Pages and Build Navigation
	$.each($("table.verordnungs_inhalt"), function(v, k){
														   
		var pagecount = $(k).find("tbody:not(:last)").size();
													
		if(pagecount > 1)
		{
			$(k).find(".pages").append("<a href='#1' class='pages_back'></a> ");
			$(k).find(".more_pages").html("Weitere Packungsgrößen");
			for(i = 1; i <= pagecount; i++)
			{
				$(k).find(".pages").append("<a href='#" + i + "'>" + i + "</a> ");
			}
			$(k).find(".pages").append("<a href='#"+ pagecount +"' class='pages_forw'></a> ");
			$(k).find("tbody:not(:last):not(:first)").hide();
			$(k).find(".pages a:eq(1)").addClass("akt");
			generateNavi($(k));
		}
		else
		{
			$(k).find("tbody.fixed_row").hide();
		}
		
		
	});
	
	// Clickfunction for fastforward buttons
	// changed by hh 22.09.2010 from: $(".pages a:not(.pages_back, .pages_forw)").click(function(e){
	$(".prod_det_table .pages a:not(.pages_back, .pages_forw)").click(function(e){
		var link = this.hash.substr(1) - 1;
		$(this).closest("table").find("tbody:not(:last)").hide();
		$(this).closest("table").find("tbody:eq("+link+")").show();
		$(this).closest(".pages").find("a").removeClass("akt");
		$(this).addClass("akt");
		changeNavi($(this).closest("table"), link);
		e.preventDefault();					 
	 });
	
	// Clickfunction for normal buttons
	// changed by hh 22.09.2010 from: $(".pages .pages_forw, .prod_det_table .pages .pages_back").click(function(e) {
	$(".prod_det_table .pages .pages_forw, .prod_det_table .pages .pages_back").click(function(e) {
		var link = this.hash.substr(1) - 1;
		$(this).closest("table").find("tbody:not(:last)").hide();
		$(this).closest("table").find("tbody:eq("+link+")").show();
		$(this).closest(".pages").find("a").removeClass("akt");
		$(this).closest(".pages").find("a:not(.pages_back, .pages_forw):eq("+link +")").addClass("akt");
		changeNavi($(this).closest("table"), link);
		e.preventDefault();
	}); 

	// generate Navi and hide Items													
	function generateNavi(obj) {
															
		var navi = $(obj).find(".pages a:not(.pages_back, .pages_forw)");
		var navi_size = navi.size();
																			
		if(navi_size > 5) {
			for(j = 1; j <= navi_size; j++) {
				if( j > 3 && j < navi_size)	{
					$(obj).find(".pages a:eq("+ j +")").hide();
				}
			}
			$(obj).find(".pages a:eq("+ navi_size +")").before(dots);
			
		}
		
	}
	
	
	// Handle navigation on button click
	function changeNavi(obj, id) {
		
		var navi = $(obj).find(".pages a:not(.pages_back, .pages_forw)");
		var navi_size = navi.size();
		
		$(obj).find(".pages span").remove();
		
		if (navi_size > 5)
		{
			for( x=2; x < navi_size; x++)
			{
				if( x == id || x == id+1 || x == id+2)
				{
					$(obj).find(".pages a:eq("+ x +")").show();
					
					if(x == id+2 && id+2 < navi_size-1)
					{
						$(obj).find(".pages a:eq("+ x +")").after(dots);
					}
					
				}
				else
				{
					$(obj).find(".pages a:eq("+ x +")").hide();
				}
			}
			if(id == 0)
			{
				$(".pages span").remove();
				$(obj).find(".pages a:eq("+ id+3 +")").show().after(dots);
			}
			
			if(id > 2)
			{
				$(obj).find(".pages a:eq(1)").after(dots);
			}
			
			if( id == navi_size - 1)
			{
				$(obj).find(".pages a:eq("+ (id-1) +")").show();
			}
		}
		else
		{
			$(obj).find(".pages a").show();
		}
		
	}
};

/* Autocompletion für neu anzulegenden Benutzer abschalten */
jQuery(function($) {
	if (document.getElementById("registryForm")) {
	var AutoCompletion = document.createAttribute("autocomplete");
	AutoCompletion.nodeValue = "off";
	var MyElement = document.getElementById("registryForm");
	MyElement.setAttributeNode(AutoCompletion);
	}
	if (document.getElementById("checkoutValidateCredentialsForm")) {
    var AutoCompletion = document.createAttribute("autocomplete");
    AutoCompletion.nodeValue = "off";
    var MyCheckoutElement = document.getElementById("checkoutValidateCredentialsForm");
    MyCheckoutElement.setAttributeNode(AutoCompletion);
    }
});

/*
 * Fügt hinter die URL einen Parameter "WT.ac" hinzu.
 * Ist für das Teasertracking im Webtrends.
 * Hier kann man sehen von welchem Teaser man "gekommen" ist.
 * Bsp.: .../aspirin-c-beragena-brausetabletten-4405811-produktdetail?WT.ac=DOCMORRIS-ALTERNATIVE
 */
function addParamToHref(url, param_key, param_value){
	if(param_value.length>0){
		var sign = (url.indexOf("?")>0 ? "&" :"?"); 
		window.location.href=url + sign + param_key+"="+escape(param_value) ;
		return false;
	}
}
