/**
 * basic javascript functions
 * author: m. heuermann, werk01.de
 */
Prototype.Browser.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5))==6;
Prototype.Browser.IE7 = Prototype.Browser.IE && !Prototype.Browser.IE6;

/**
 * start on load handler
 */
Event.observe(window, 'load', function(event) {
	event.stop();
	dm.init();
	dm.scaleImg(false);
	dm.activateNav();
	
	if (!Prototype.Browser.IE6 && !Prototype.Browser.IE7) {
		dm.smoothLink();
	}
	
	dm.fadeBox();
	dmSound.openWinOnStartup();
	dmSound.soundWindow();
});

var dmSound = {
	autoPlay: false,
	popup: false,
	playList: ['/sounds/Canta_Bossa_Mix_02_PB.mp3'],
	init: function() {
		if (debug) { alert('sound init'); }
		if (dmSound.autoPlay) {
			dmSound.stop();
			Sound.play(dmSound.playList[0],{replace:true});
		} else {
			dmSound.play();
		}
	},

	// currently unused
	openWinOnStartup: function () {
		var sound = getCookie('sound' + dm.lang);
		if 	(sound != 1 && $('soundWindow') && 
			(window.location.pathname == '/com/' || window.location.pathname == '/com' || 
			 window.location.pathname == '/de/' || window.location.pathname == '/de' ||
			 window.location.pathname == '/cn/' || window.location.pathname == '/cn' ||
 			 window.location.pathname == '/at/' || window.location.pathname == '/at' ||
 			 window.location.pathname == '/ch/de/' || window.location.pathname == '/ch/de' || 
 			 window.location.pathname == '/ch/it/' || window.location.pathname == '/ch/it' || 
 			 window.location.pathname == '/ch/fr/' || window.location.pathname == '/ch/fr')
		) {
			Popup.open({
				url:$('soundWindow').href,
				width: 450,
				height:351,
				popunder: true,
				name:"dmSound"
			});
			setCookie('sound' + dm.lang ,1,1);
			dmSound.popup = true;
			var md = new Date();
			var oneDay = md.getTime() + (1 * 24 * 60 * 60 * 1000);
			md.setTime(oneDay);
		} 
	},
	
	play: function() {
		if ($('soundPlay')) {
		  	$('soundPlay').observe('click', function(event) {
    	   		event.stop();
				Sound.enable();       		
				Sound.play(dmSound.playList[0],{replace:true});
				window.setTimeout(function(){
					dmSound.stop();
				}, 500);
			});
		}
	},
	stop: function() {
		if ($('soundPlay')) {
			$('soundPlay').observe('click', function(event) {
				event.stop();
				Sound.enable();
				Sound.play('/sounds/null.mp3',{replace:true});
				Sound.disable();
				window.setTimeout(function(){
					dmSound.play();
				}, 500);
			});
		}
	},
	soundWindow: function() {
		if ($('soundWindow')) {
			$('soundWindow').observe('click', function(event) {
				event.stop();
				if (!Popup.focus()) {
					var url = $('soundWindow').href;
					var pos = url.lastIndexOf('.');
					url = url.substring(0, pos)+'_no_autostart'+url.substr(pos);
					Popup.open({
						url: url,
						width: 450,
						height:351,
						popunder: false,
						name:"dmSound"
					});
				}
			});
		}
	}
};
var Popup = {
  myWindow: null,
  open: function(options)
  {
    this.options = {
      url: '#',
      width: 300,
      height: 200,
      name:"_blank",
      location:"no",
      menubar:"no",
      toolbar:"no",
      status:"no",
      scrollbars:"no",
      resizable:"no",
      left:"100",
      top:"100",
      normal:false,
      popunder:false
    }
    Object.extend(this.options, options || {});

    if (this.options.normal){
        this.options.menubar = "yes";
        this.options.status = "yes";
        this.options.toolbar = "yes";
        this.options.location = "yes";
    }

    this.options.width = this.options.width < screen.availWidth ? this.options.width : screen.availWidth;
    this.options.height = this.options.height < screen.availHeight ? this.options.height : screen.availHeight;
    var openoptions = 'width='+this.options.width+',height='+this.options.height+',location='+this.options.location+',menubar='+this.options.menubar+',toolbar='+this.options.toolbar+',scrollbars='+this.options.scrollbars+',resizable='+this.options.resizable+',status='+this.options.status
    if (this.options.top!="")openoptions+=",top="+this.options.top;
    if (this.options.left!="")openoptions+=",left="+this.options.left;
    Popup.myWindow = window.open(this.options.url, this.options.name, openoptions);
    if (Popup.myWindow && this.options.popunder) {
			Popup.myWindow.blur();
			window.focus();
    }
    return false;
  },
  focus: function() {
  	if (Popup.myWindow && Popup.myWindow.closed)
  		Popup.myWindow = null;
    if (Popup.myWindow) {
			Popup.myWindow.focus();
			return true;
    }
    return false;
  },
  close: function() {
  	if (Popup.myWindow && Popup.myWindow.closed)
  		Popup.myWindow = null;
  	if (Popup.myWindow)
  		Popup.myWindow.close();
  }
}
/**
 * class dm
 * provides the eye candy stuff*/
var dm = {	
	
	shCounter:[],
	
	lang: '',

	/**
	 * start functions onload
	 */
	init: function(){
		Event.observe(window, 'resize', function(event) {
			dm.scaleImg(true);
			dm.checkAccSize();
			dm.resizeAccDelayed(-1);
			dm.contactNavResize();
		});
	},
	
	showBranding: function (id) {
		Effect.toggle('shopBrandingBox'+id, 'blind', { 
			beforeStart: function() {
				dm.getContent('/ch/de/shop/branding/o2pid/'+id+'/', '', 'shopBrandingBox'+id, 'null');
			},
			afterFinish: function() {
				CSBfleXcroll('flexcontent4');
			}
		});
	},

	career: function() {
		var links = $$('#joblist_1 .careerLink');
		links.each(function(anchor, index){
			Event.observe($(anchor), 'click', function(event) {
				$('joblist_1').hide();			
				new Effect.Appear('jobdescr_'+(index+1)+'_'+(index+1));
				var anc = 'flexcontent_'+(index+1);
				if ($('accListFlex')) {
					var ph = $('accListFlex').getDimensions().height;
				} else {
					var ph = $('flexcroll').getDimensions().height;
				}
				var uri = window.location.pathname;
				if (uri.search('/your-career-with-us+/') != -1) {
					ph=ph+50;
				}				
				$(anc).setStyle({'height': ph  + 'px'});
				window.setTimeout(function(){CSBfleXcroll(anc);}, 600);
			});
		});
		
		var backLinks = $$('#content .backBtn');
		backLinks.each(function(anchor, index){
			Event.observe($(anchor), 'click', function(event) {
				var links = $$('.careerLink');		
				links.each(function(anchor, index){
					$('jobdescr_'+(index+1)+'_'+(index+1)).hide();
				});
				new Effect.Appear('joblist_1');
			});
		});
	},
	
	activateNav: function() {
		var links 		= $$('#mainNav a');
		var myUrl 		= "\"" + window.location + "\"";
		var subIsDown 	= false;
		links.each(function(anchor){
			var myLink = anchor.readAttribute('href');
		  	if(myUrl.indexOf(myLink) !=-1) {
		  		if (subIsDown == false) {
	  				anchor.className = "active";
		  			var myAnc = anchor.next();	  				
		  			if (myAnc) {
						myAnc.setStyle({left:0});
						if (Prototype.Browser.IE6) {
							window.setTimeout(function(){myAnc.show();}, 600);						
						} else {
							window.setTimeout(function(){new Effect.BlindDown(myAnc, {duration: 0.8});}, 600);
						}
	 					subIsDown = true;
					}
	  			} else {
					anchor.className = "active";
	  			}
	  		} 
		});
	},
	contactNavResize: function() {
		var theAnc = $$('[class*=arrowLeft]:not(a)');
		var uri = window.location.pathname;	
		theAnc.each(function(anc, index) {
			if (!anc.down().match('h2') && !anc.down().match('h3')) {
				var ph = $('accordion').getDimensions().height - (parseInt(anc.getStyle('padding-top')) + parseInt(anc.getStyle('padding-bottom')));	
				anc.down().setStyle({'height': ph  + 'px'});
			} else  if (uri.search('/apprentices-and-internships-with-us+/') != -1) {
				var ph = $('flexcontent').getDimensions().height;
				anc.down().next().setStyle({'height': ph  + 'px'});
			}
		});	
	},
	flexCalcDone: false,
	contactNav: function(anchorClass, activeClass, nonActiveClass){
		var anchors = $$(anchorClass);
		var uri = window.location.pathname;
		if (anchors.length > 0) {
			anchors.each(function(anchor, index){

				// precalc all heights for right divs, OM
				var theAnc = $$(anchorClass+index);
				if (theAnc && theAnc.length) {
					if (!theAnc[0].down().match('h2') && !theAnc[0].down().match('h3') && anchorClass == '.arrowLeft') {
						var ph = $('accordion').getDimensions().height - (parseInt(theAnc[0].getStyle('padding-top')) + parseInt(theAnc[0].getStyle('padding-bottom')));
						theAnc[0].down().setStyle({'height': ph  + 'px'});
					} else if (dm.flexCalcDone) {
						var ph = $('content').getDimensions().height - 300;
						theAnc[0].down().next().setStyle({'height': ph  + 'px'});
					}
				}

				Event.observe($(anchor), 'click', function(event) {
					if (anchorClass == '.arrowLeft') {
						if (uri.search('/location-contacts') == -1) {
							 if (index > 3) {
								 dm.contactNavSub();
							 }
						} else {
							dm.contactNavSub();	
						}
					}
					dm.closeContactNav(anchorClass);
					if (anchorClass == '.arrowLeft') {
						dm.closeContactNav('.subArrowLeft');
					}
					anchor.addClassName('active');
					var theAnc = $$(anchorClass+index);
					if (theAnc && theAnc.length) {
						if (Prototype.Browser.IE6) {
							theAnc[0].show();
						} else {
							new Effect.Appear(theAnc[0], {duration:0.4});
						}
						if (anchorClass == '.subArrowLeft') {
							window.setTimeout(function(){CSBfleXcroll('subflexcontent'+index);}, 200);
						} else {
							if (uri.search('/location-contacts') == -1) {
								window.setTimeout(function(){CSBfleXcroll('flexcontent'+index);}, 600);
							} else {
							 	if (index > 3)
									window.setTimeout(function(){CSBfleXcroll('flexcontent'+index);}, 600);
							}
						}
					}
				});
			});
		}
	},

	contentNavSubStat: false,
	contactNavSub: function() {
		if (!dm.contentNavSubStat) {
			dm.contactNav('.subArrowLeft', 'subArrowLeft active', 'subArrowLeft');			
			dm.contentNavSubStat = true;
		}
		return;
	},
	closeContactNav: function(anchorClass){	
		var anchors = $$(anchorClass);
		anchors.each(function(anchor, index) {
				anchor.removeClassName('active');
				var theAnc = $$(anchorClass+index);
				if (theAnc && theAnc.length) {
					theAnc[0].hide();
				}
		});
	},

	contactNavCloseButton: function(anchorClass, activeClass){
		var anchors = $$('.closeLayer');
		if (anchors.length > 0) {
			anchors.each(function(anchor, index){
				Event.observe($(anchor), 'click', function(event) {
					dm.closeContactNav(anchorClass);
				});
			});
		}
	},

	accToggleHeight: 0,
	accToggleIndex: -1,
	teaserStatus: [],
	teaserElem: [],
	headElem: [],
	innerHeight: [],

	checkAccSize: function() {
		if ($('accordion')) {
			// init
			dm.fleXenvGlobalInit();
			var myH = $('content').getHeight() - $('footer').getHeight() - parseInt($('inset').getStyle('padding-top'));
			$('accordion').setStyle({height:myH+'px'});
			var myTogg = $$('.accordionToggle');
			// search toggle height
			myTogg.each(function(toggle){
				var h = $(toggle).getHeight();
				if (h > 0)
					dm.accToggleHeight = h;
			});
			// apply height to all content divs, for later animation
			var myContent = $$('.accordionContent');
			var myContentHeight = parseInt($('accordion').getStyle('height')) - (myTogg.length-1)*dm.accToggleHeight;
			myContent.each(function(content){
				var height = myContentHeight;
				var h = parseInt ($(content).getStyle('padding-top'));
				if (h > 0)
					height -= h;
				var h = parseInt ($(content).getStyle('padding-bottom'));
				if (h > 0)
					height -= h;
				$(content).setStyle({height:height+'px'});
			});
		}
	},

	makeAcc: function () {
		if ($('accordion')) {
			this.checkAccSize();
			this.blogRollMagic();
		}
	},

	// calls resizeAcc delayed due to browser bugs
	resizeAccDelayed : function (index) {
		if (index >= 0)
			dm.accToggleIndex = index;
		window.setTimeout("dm.resizeAcc(-1)", 1500);
	},

	// initializes flexrolls in accordeons
	resizeAcc: function (index) {
	
		if (index < 0)
			index = dm.accToggleIndex;

		var flexObj = $('flexcontent_'+index);
		if (flexObj) {
			var accObj = $(flexObj).up();
			if (accObj) {
				var size = parseInt($(accObj).getStyle('height'));	// initial height
				var childs = new Array (accObj.down('h2'), accObj.down('h3'));
				childs.each(function(child){
					if (child) {
						var h = $(child).getHeight();
						if (h > 0)
							size -= h;
					}
				});
				$(flexObj).setStyle({height:size+'px'});
				CSBfleXcroll('flexcontent_'+index);
			}
			dm.accToggleIndex = index;
		}
	},

	blogRollMagic:  function () {
		var myTogg = $$('.accordionToggle');
		myTogg.each(function(tog) {
			var myHead = tog.down('.accordionToggleHref');
			var myContent = tog.next('.accordionContent');
			// head element and next element must exist on dom tree
			if (myHead && myContent.className.indexOf('accordionContent')>=0) {
				dm.headElem.push(myHead);
				dm.teaserElem.push(myContent);
			}
		});
		dm.headElem.each(function(element, index) {
			dm.teaserStatus[index] = 0;
			if (index == 0) {	// open index-0
				dm.teaserStatus[index] = 1;
				$(dm.headElem[index]).up().setStyle({'display':'none'});
				if (Prototype.Browser.IE6) {
	        		$(dm.teaserElem[index]).show();
	        		dm.resizeAccDelayed(index);
	        	} else {
					new Effect.BlindDown($(dm.teaserElem[index]), {duration: 0.8, afterFinish: dm.resizeAccDelayed(index)});	        	
	        	}
			}
			Event.observe($(element), 'click', function(event) {
					if (dm.teaserStatus[index] == 0) {
						$(dm.headElem[index]).up().setStyle({'display':'none'});
						dm.teaserStatus[index] = 1;
						if (Prototype.Browser.IE6) {
		        			$(dm.teaserElem[index]).show();
		    	    		dm.resizeAccDelayed(index);
		        		} else {
							new Effect.BlindDown($(dm.teaserElem[index]), {duration: 0.3, afterFinish: dm.resizeAccDelayed(index)});	        	
	        			}
						dm.closeBlogRollItems(dm.teaserElem[index]);
					}
				});
		});
	},
	
	closeBlogRollItems: function (elemNotClose) {
		dm.teaserElem.each(function(element, index) {
			if (elemNotClose != element) {
				if (dm.teaserStatus[index] == 1) {
					$(dm.headElem[index]).up().setStyle({'display':''});
					if (Prototype.Browser.IE6) {
						element.hide();
						dm.teaserStatus[index] = 0;
					} else {
						new Effect.BlindUp(element, {duration: 0.3, afterFinish: function(){
							dm.teaserStatus[index] = 0;
						}});
					}
				}
			}
		});
	},
	
	readMore: function () {
	
		var fxc = $$('div.flexcroll');
		var myH = $('content').getDimensions().height - 322;
		if (fxc.first()) {
			try {
				h2Height = fxc.first().previous('h2').getStyle('lineHeight');
				if (h2Height.replace("px","") >= 80) {
					myH = myH-30;			
				}
			}catch(e){
			};
		}
		if (fxc.first()) {
			try {
				pHeight = fxc.first().previous('p').getStyle('height');
				if (pHeight.replace("px","") >= 40) {
					myH = myH-30;			
				}
			}catch(e){
			};			
		}
		if (fxc.first()) {
			try {
			if (fxc.first().previous('h3')) {
				h3Height = fxc.first().previous('h3').getStyle('height');
				if (h3Height.replace("px","") >= 40) {
					myH = myH-20;			
				} else {
					myH = myH-10;			
				}
			}
			}catch(e){
			};			
		}
		if ($('content') && fxc.first() != 'undefined') {
			fxc.each(function(anchor) {
				$(anchor).setStyle({height: myH + 'px'});
			});
		}
		
		dm.actualContentHeight = myH;
		
		var rmb = $$('a.readMoreBtn');
		if (rmb.first() != 'undefined') {
			rmb.each(function(anchor, index) {
				Event.observe($(anchor), 'click', function(event) {
					event.stop();
					$(anchor).hide();
					$(anchor).previous(1).hide();
					new Effect.Appear($(anchor).previous(), {duration:0.2, afterFinish: function(){
						fleXenv.globalInit();
						if ($('flexcroll')) {
							CSBfleXcroll('flexcroll');
						} else if ($('flexscroll'+index)) {
							CSBfleXcroll('flexcroll'+index);
						} else if ($('flexcontent'+index)) {
							CSBfleXcroll('flexcontent'+index);
						} else if ($('flexcontent_'+index)) {
							CSBfleXcroll('flexcontent_'+index);
						} else {
							CSBfleXcroll('flexcroll');
						}
					}});
				});
			});
		}
	},
	
	actualContentHeight: 0,
	
	showFullText: function(anc, flex) {
		if (anc) {
			$(anc).hide();
			$(anc).next('a').show();			
			$(anc).previous().down('span').show();				
			if (flex) {
				CSBfleXcroll(flex);
			}
		}
		return false;
	},

	hideFullText: function(anc, flex) {
		if (anc) {
			$(anc).hide();		
			$(anc).previous('p').down('span').hide();	
			$(anc).previous('a').show();				
			if (flex) {
				CSBfleXcroll(flex);
			}
		}
		return false;
	},
	
	nav: function () {
		if ($('subNav')) {
			new Effect.BlindDown('subNav');
		}
	},
	
	fadeBox: function () {
		if ($('fadeBox')) {
			new Effect.Fade('fadeBox', {duration:0.6});
		}
	},
	
	fadingFonts: function() {
		if ($('fadingFont')) {
			new Effect.Appear('fadingFont', {duration:2.5});
			var boxes = $$('#fadingFont h2');
			boxes.each(function(anchor, index) {
				var type = $(anchor).readAttribute('rel').split("|");
				new Effect.Move($(anchor), {
					x: type[0],
					y: type[1],
					duration: type[2]
				});
			});
		}
	},
	
	fixMarginTop: false,
	varMarginTop: 0,
	scaleImg: function (resize) {
	
		if($('mainWrapper')){	
			var myMarginTop;
		    var winSize = document.viewport.getDimensions();
		    var w 		= winSize.width;
		    var h 		= winSize.height;
		    
	    	if (w > 1440) w = 1440;
	    	if (w < 980) w = 1000;

		    var myW 	= $('bgImage').getDimensions().width;
		    var myH 	= $('bgImage').getDimensions().height;
			
    		if (this.varMarginTop > 0) {
			    myMarginTop = (myH/this.varMarginTop);
			} else if (this.fixMarginTop == true) {
				if (Prototype.Browser.IE6) {
				    myMarginTop = ((h/2) - $('header').getDimensions().height + 10);				
				} else {
				    myMarginTop = ((h/2) - $('header').getDimensions().height + 40);
				}
			} else {
				myMarginTop = (myH/2);
			}

			var newMarginTop  = Math.round(myMarginTop);
			var newMarginLeft = Math.round((w/2));
			$('bgImage').setStyle({
	    	    width: Math.round(w) + 'px',
		        marginTop: '-' + newMarginTop + 'px',
	    	    marginLeft: '-' + newMarginLeft + 'px'
		    });
		    if (Prototype.Browser.IE6) {
				$('bgImage').setStyle({
					left: '50%', 
					top: '50%'
				});
		    } 
		    this.positionFadingFont(winSize.width,winSize.height);
		    this.readMore();
		}
	},
	
	posFadingFont: 0,
	positionFadingFont: function (width, height) {
		if ($('fadingFont')) {
			$('fadingFont').setStyle({
				right : '0'
			});
			if(height <= 480){
				$('fadingFont').setStyle({
					top : (50 + dm.posFadingFont) + '%'
			});
			} else {
				$('fadingFont').setStyle({
					top : (60 + dm.posFadingFont) + '%'
				});
			}
		}
	},
	
	lensFlare: function () {
		if ($('lenseFlare') && !Prototype.Browser.IE) {
			new Effect.Appear ('lenseFlare', {duration: 2.8});
		} else if ($('lenseFlare') && Prototype.Browser.IE) {
			$('lenseFlare').show();
			/*window.setTimeout(function(){
				new Effect.Scale('lenseImage', 100, {duration:1.5,scaleFromCenter:true,scaleFrom:95, scaleMode: { originalHeight: 659, originalWidth: 518 }});
			}, 800);*/
		}
	},
	
	smoothLink: function () {
		var links = $$('a[rel="smoothLink"]');
		links.each(function(anchor, index) {
			var uri = $(anchor).readAttribute('href');
			Event.observe($(anchor), 'click', function(event) {
				event.stop();
				new Effect.Appear('fadeBox', {duration:0.4});				
				setTimeout('window.location = "' + uri + '"', 500);
			});
		});
	},
	
	lostPwd: function() {
		$('lostPwdForm').request({
  			onSuccess: function(transport){ 
  				var result = transport.responseText;
  				$('lostPwdAnswer').innerHTML = result;
  				$('lostPwdAnswer').show();
				if (result.search('error') == -1) {
	  				$('lostPwdForm').hide();					
				}
				window.setTimeout(function(){
					CSBfleXcroll('flexcontent2');
					fleXcrollTo('flexcontent2', false, "-1000px", true);
				}, 300);
  			}
		});
		return false;
	},

	extraSize:0,
	scaleLists: function(domIds, size) {
		var ph = $('content').getDimensions().height;
		dm.extraSize = size;
		if (Object.isArray(size)) {
			domIds.each(function(id, i) {
				$(id).setStyle({height: (ph - size[i])  + 'px'});
			});
		} else {
			domIds.each(function(id) {
				$(id).setStyle({height: (ph - size)  + 'px'});
			});
		}
	},

	getContent: function(url, params, domId, flexcroll) {
		$(domId).innerHTML = '<div style="width:100%;text-align:center;"><img src="/images/indicator.gif" width="16" height="16" /></div>';
		if (Prototype.Browser.IE) {
			window.setTimeout(function(){
				new Ajax.Updater(domId, url , {
					method: 'post',
					parameters: params,
					evalScripts: true,
					onComplete: function() {
						if (flexcroll != 'null') {	
							window.setTimeout(function(){
								CSBfleXcroll(flexcroll);
								fleXcrollTo(flexcroll,false,"-1000px",true);
							}, 300);
							Event.observe(window, 'resize', function() {
								var size = dm.actualContentHeight;
								if (dm.extraSize > 0) { 
									ph = $('content').getDimensions().height;
									size = ph-dm.extraSize;
								}
								$(flexcroll).setStyle({height: size + 'px'});
								CSBfleXcroll(flexcroll);
							});					
						}
					}
				});			
			},1000);
		} else {
			new Ajax.Updater(domId, url , {
				method: 'post',
				parameters: params,
				evalScripts: true,
				onComplete: function() {
					if (flexcroll != 'null') {	
						window.setTimeout(function() {
							CSBfleXcroll(flexcroll);
							fleXcrollTo(flexcroll, false, "-1000px", true);
						}, 300);
						Event.observe(window, 'resize', function() {
							var size = dm.actualContentHeight;
							if (dm.extraSize > 0) { 
								ph = $('content').getDimensions().height;
								size = ph-dm.extraSize;
							}
							$(flexcroll).setStyle({height: size + 'px'});
							CSBfleXcroll(flexcroll);
						});
					}
				}
			});		
		}
	}, 

	switchContent: function(anchorName, activeAnchorId, activeContentId) {
		dm.closeContactNav (anchorName);
		if (activeAnchorId != '')
			$(activeAnchorId).addClassName('active');
		$(activeContentId).show();
	}, 

	slideShow: function(anc) {
		if (!anc) return;
		if (!$('zoomImage')) return;

		$('zoomImage').src = anc.src;
		$('zoomImageText').innerHTML = anc.alt;
	},

	mySB: function(anc){
		Shadowbox.open({
	    	content:anc.href,
		    player: "img"
	    });
	    return false;
	},
	sendMyForm: function(formID, RadioName){
		var myVal = $RF(formID, RadioName);
		if (myVal == null) {
			return false;
		} else {
			var lang = dm.lang;
			if (dm.lang == 'de-ch') {
				lang = 'ch/de';
			}
			dm.getContent('/' + lang + '/private-lounge/postcard-service-send/','motive=' + myVal , 'postCardService', 'flexcontent0');
		}
		return false;
	}, 
	clubContactItems: function(notClose) {
		var ancs = $$('td[class="contactClubForm"]');
		ancs.each(function(anc, index) {
			if (anc.id != notClose) {
				new Effect.BlindUp(anc);
				$(anc).setStyle({'height':'0px'});
			}
		});					
		$(notClose).setStyle({'height':'200px'});
		new Effect.BlindDown(notClose);	
	},
	fleXenvGlobalInit: function(){
		window.setTimeout(function(){fleXenv.globalInit()}, 250);
	},
	uploadImage: function(formid) {
		
		var n = 'f' + Math.floor(Math.random() * 99999);
		var d = document.createElement('DIV');
		d.innerHTML = '<iframe style="display:none" src="about:blank" id="'+n+'" name="'+n+'"></iframe>';
		document.body.appendChild(d);
		$(formid).setAttribute('target', n);
		$('throbberLayer').show();
		$('imageLayer').hide();
		$(formid).submit();
				
	}
};
/* accordion lists all variants*/
var module = {
	init: function(flex) {
		if (flex == true) {
			module.doFlex = true;
		}
		if ($('accordionList')) {
			module.akkordion();
		}
	},
	doFlex: false,
	doFlexId: 'flexcontent1',
	status: [],
	item: [],
	akkordion: function() {
		var anchors = $$('a[rel="moduleAkkordion"]')
		if (anchors) {
			anchors.each(function(anchor, index) {
				module.status[index] 		= 0;
				module.item[index] 			= $(anchor);
				module.item[index].onclick 	= function() {
					module.action(index);
					if (module.doFlex) {
						dm.readMore();
						if (Prototype.Browser.IE6) {
							CSBfleXcroll('accListFlex');
						}
					} else {
						CSBfleXcroll(module.doFlexId);
					}
					return false;
				};
			});	
		}
	},
	action: function(myIndex) {
		module.item.each(function(anchor, index) {
			var myAnchor = $(anchor.up(0).next(0));
			if(module.status[index] == '1') {
				module.status[index] = 0;
				if (myAnchor) {
					if (Prototype.Browser.IE6) {
						myAnchor.hide();
					} else {
						new Effect.BlindUp(myAnchor,{duration:0.3, afterFinish: function () {
							if (module.doFlex) {
								CSBfleXcroll('accListFlex');
							}else {
								CSBfleXcroll(module.doFlexId);
							}
						}});
					}
					anchor.className = '';
				}
			} else if(module.status[index] == '0' && index == myIndex) {
				module.status[index] = 1;
				if (myAnchor) {
					if (Prototype.Browser.IE6) {
						myAnchor.show();
					} else {
						new Effect.BlindDown(myAnchor,{duration:0.3, afterFinish: function () {
							if (module.doFlex) {
								CSBfleXcroll('accListFlex');
							} else {
								CSBfleXcroll(module.doFlexId);
							}
						}});
					}
					anchor.className = "active";
				}
			}
		});
	}
};

var dmAjax = {
	url: '',
	init: function() {
		if ($('ajaxContent')) {
			dmAjax.getContent(dmAjax.url);
		}
		if ($('contactForm')) {
			dmAjax.contactFormSubmit();
		}
	},
	getContent: function(url) {
		new Ajax.Request(url, {
			method: 'get',
			onSuccess: function(transport) {
			    	$('ajaxContent').style.display = 'none';
				    $('ajaxContent').innerHTML = transport.responseText;
			    	new Effect.Appear('ajaxContent', {duration:0.8});
					var anchors = $$('.reconAjax');
					if (anchors.length > 0) {
						anchors.each(function(anchor, index){
							Event.observe($(anchor), 'click', function(event) {
								$('ajaxContent').innerHTML = '<p style="margin-left:150px;margin-top:75px;"><img align="middle" src="/images/indicator.gif" /></p>';
								dmAjax.getContent($(anchor).getAttribute('href'));
								event.stop();
							});
						});
					}
					window.setTimeout(function() {
						CSBfleXcroll("flexcontent0");
						fleXcrollTo("flexcontent0",false,"-100s",true);
						fleXcrollTo("flexcontent2",false,"-100s",true);
					}, 300);
					
					if ($('toggleCommentForm')) {
						Event.observe($('toggleCommentForm'), 'click', function(event) {
							$('toggleCommentForm').hide();
							$('commentList').hide();
							$('commentForm').show();
							window.setTimeout(function(){
								CSBfleXcroll("flexcontent2");
								fleXcrollTo("flexcontent2",false,"-100s",true);
							}, 100);
							if ($('submitCommentForm')) {
								dmAjax.commentFormSubmit();
							}

						});
					}
			}
		});
	},
	
	commentFormSubmit: function () {
		Event.observe($('submitCommentForm'), 'click', function(event) {
			event.stop();
			var error = false;
			if (!$F('myDescription')) {
				$('myDescription').previous().setAttribute('class', 'error');
				error = true;
			} else {
				$('myDescription').previous().setAttribute('class', '');
			}
			if (!$F('firstname')) {
	    		$('firstname').previous().setAttribute('class', 'error');
	    		error = true;
	    	} else {
				$('firstname').previous().setAttribute('class', '');
			}
	    	if (!$F('surname')) {
	    		$('surname').previous().setAttribute('class', 'error');
	    		error = true;
	    	} else {
				$('surname').previous().setAttribute('class', '');
			}
	    	if (!error) {
	    		$('commentForm').request({
	    			onComplete: function(transport){ 
	    				dmAjax.getContent(dmAjax.url);
	    				dm.resizeAccDelayed();
	    			}
	    		});
	    	} 
	    });
	},

	contactFormSubmit: function() {

		Event.observe($('contactFormSubmit'), 'click', function(event) {
							
			event.stop();
			var field = '';
			var error = false;
			
			$$('#contactForm label').each(function(node, i){
				field = node.readAttribute('for');
				if ($F(field) == '') {
		    		$(node).className = 'error';
    				error = true;
				} else if($F(field) != null) {
					$(node).className = '';
				}
			});

    	if (!error) {
    		var message;
    		$('contactForm').request({
    			onComplete: function(transport){ 
						message = transport.responseText.evalJSON();
						if (message.success) {
							$('contactInitiationH2').hide();							
							$('contactInitiationH3').hide();
    					$('flexcontent2').hide();
    					$('contactConfirm').show();
						}
    				if (message.error.email) {
							$('email').previous().className = 'error';
						}
    			}
    		});
    	} else {
				window.setTimeout(function(){
					CSBfleXcroll("flexcontent2");
					fleXcrollTo("flexcontent2",false,"-400px",true);
				}, 300);
    	}
    });
	}
};

function checkBCShop (myAnchor) {

	var bc = ['bcWarenkorb', 'bcAdresse', 'bcLieferung', 'bcZahlungsart', 'bcBestaetigung'];
	bc.each(function(anc){
		if (anc == myAnchor) {
			$(anc).addClassName('active');		
		} else {
			$(anc).removeClassName('active');
		}
	});	
}

function fleXcrollTo(id,x,y,relative) {
	var scrollDiv = $(id);
	if (!scrollDiv) return;
	if(scrollDiv.contentScroll) {
		scrollDiv.contentScroll(x,y,relative);
	}
}
function $RF(el, radioGroup) {
    if($(el).type && $(el).type.toLowerCase() == 'radio') {
        var radioGroup = $(el).name;
        var el = $(el).form;
    } else if ($(el).tagName.toLowerCase() != 'form') {
        return false;
    }
 
    var checked = $(el).getInputs('radio', radioGroup).find(
        function(re) {return re.checked;}
    );
	    return (checked) ? $F(checked) : null;
}
function check (obj) {
	switch (obj.name) {
		case 'text':		if (obj.value != 'Hier bitte den Text eingeben ...') return; addUpdate(obj); break;
		case 'name':		if (obj.value != 'Name') return; break;
		case 'firstname':	if (obj.value != 'Vorname') return; break;
		case 'street':		if (obj.value != 'Straße Hausnummer') return; break;
		case 'zip':			if (obj.value != 'PLZ') return; break;
		case 'city':		if (obj.value != 'Ort') return; break;
	}
	obj.value = '';
}
function addUpdate(obj) {
	obj.observe('keydown', function(event) {
		Update(obj);
	});
	obj.observe('keyup', function(event) {
		Update(obj);	
	});
}
function Update(obj) {
	var max = 400;
	if (obj.value) {
		var len = obj.value.length;
		if (len > max)
			obj.value = obj.value.substring (0,max);
	}
}
function cigarillo_sw (pos) {
	var swobj = new Array (
		"cigarillo_moods",
		"cigarillo_moods_filter",
		"cigarillo_mlt",
		"cigarillo_minimoods",
		"cigarillo_sweets_filter",
		"cigarillo_speciale",
		"cigarillo_mcf",
		"cigarillo_dm_rest",
		"cigarillo_cm_aro_filter",
		"cigarillo_cm_aro_nonfilter",
		"cigarillo_cm_nonaro_filter",
		"cigarillo_cm_nonaro_nonfilter",
		"cigarillo_alcapone_filter",
		"cigarillo_alcapone_nonfilter",
		"cigarillo_nobel",
		"cigarillo_biddies",
		"cigarillo_panther_aro_filter",
		"cigarillo_panther_aro_nonfilter",
		"cigarillo_panther_nonaro_filter",
		"cigarillo_panther_nonaro_nonfilter",
		"cigarillo_handelsgold_aro",
		"cigarillo_handelsgold_nonaro",
		"cigarillo_meharis_aro_filter",
		"cigarillo_meharis_aro_nonfilter",
		"cigarillo_meharis_nonaro_nonfilter",
		"cigarillo_aro_filter",
		"cigarillo_aro_nonfilter",
		"cigarillo_nonaro_filter",
		"cigarillo_nonaro_nonfilter");

	if (pos) {
		for (var i=0; i<swobj.length; i++)
			eval ("document.FormName."+swobj[i]+".checked = false");
	}
	else
		document.FormName.cigarillo_none.checked = false;
}

function cigarre_sw (pos) {
	var swobj = new Array (
		"cigarre_moods",
		"cigarre_panalito",
		"cigarre_tubes",
		"cigarre_collofino",
		"cigarre_alcapone",
		"cigarre_tropen",
		"cigarre_handelsgold",
		"cigarre_independence",
		"cigarre_vasco");

	if (pos) {
		for (var i=0; i<swobj.length; i++)
			eval ("$('register')."+swobj[i]+".checked = false;");
	}
	else
		$('register').cigarre_none.checked = false;
}

function longfiller_sw (pos) {
	var swobj = new Array (
		"longfiller_hbpr",
		"longfiller_nicaragua",
		"longfiller_reserva",
		"longfiller_brasil",
		"longfiller_cuba",
		"longfiller_honduras",
		"longfiller_domrep",
		"longfiller_kanarisch",
		"longfiller_mexico",
		"longfiller_ecuador",
		"longfiller_indo");

	if (pos) {
		for (var i=0; i<swobj.length; i++)
			eval ("$('register')."+swobj[i]+".checked = false;");
	}
	else
		$('register').longfiller_none.checked = false;
}

function zusatz_sw (pos) {
	var swobj = new Array ("cigarillo", "cigarre","cigarette","lights","pipe","longfiller");

	if (pos) {
		for (var i=0; i<swobj.length; i++)
			eval ("$('register')."+swobj[i]+".checked = false");
	}
	else
		$('register').non_smoker.checked = false;
}

function status_sw () {
	var swobj = new Array ("all_topics","brasil","products","events");

	var sel = false;
	for (var i=0; i<swobj.length; i++)
		eval ("sel |= document.FormName."+swobj[i]+".checked;");
	if (!sel)
		eval ("document.FormName."+swobj[0]+".checked = true;");
}

function setCookie(c_name,value,expiredays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}
function getCookie(c_name) {
	if (document.cookie.length>0) {
	  c_start=document.cookie.indexOf(c_name + "=");
  	if (c_start!=-1) {
	    c_start=c_start + c_name.length+1;
  	  c_end=document.cookie.indexOf(";",c_start);
    	if (c_end==-1) c_end=document.cookie.length;
 	   return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return "";
}
function add(anz) {
	document.step1.anzahl.value = parseInt(document.step1.anzahl.value) + anz;
	if (parseInt(document.step1.anzahl.value)<5) {
		document.step1.anzahl.value=5;
	}
}
var flexEnvNum = {
	id: null,
	setId: function(id) {
		this.id = $(id).up('.flexscroll').identify().toString();
	},
	getId: function() {
		return this.id;
	}
};

