var formcheck, formcheck_login, myTabs;


window.addEvent('domready',function(){
	// check old ie
	oldie = (Browser.Engine.trident == true && Browser.Engine.version < 5);
		
	// slidingTabs not working with ie lt 6
	if (!oldie)
	{

		// customize formcheck
		FormCheck.implement({
		    directAjaxSubmit: function(name){
		        this.reinitialize();
				
				this.validations.each(function(el) {
					var validation = this.manageError(el,'submit');
					if(!validation) this.form.isValid = false;
				}, this);
			    
				if (this.form.isValid) {
					if (this.options.submitByAjax) {
						this.submitByAjax();
					}
				} else {
					if (this.elementToRemove && this.elementToRemove != this.firstError && this.options.display.indicateErrors == 1) {
						this.removeError(this.elementToRemove);
					}
					this.focusOnError(this.firstError)
				}
		    },
		    AjaxErrorHandler: function(data)
	    	{
	    		if (data == 'true')
	    		{
	    			myTabs.next();
	    			try {
	    				if(myTabs.panes[myTabs.current].get('id')!=null) {
							pageTracker._trackPageview('/DE/register/'+myTabs.panes[myTabs.current].get('id')+'.html');
	    				}
					} catch(e) {};
	    		}
	    		else
	    		{
	    			this.reinitialize();
	    			this.form.isValid = false
	    			if(data=='') { alert('Ein Fehler ist aufgreten, bitte versuchen Sie es erneut!'); return; }
	    			var err = JSON.decode(data);
	    			for (el in err['err'])
	    			{	
	    				if ($(el) && $(el).errors) { 
								$(el).errors.push((typeof register_errors[el] != 'undefined' && typeof register_errors[el][err['err'][el]] != 'undefined') ? register_errors[el][err['err'][el]] : err['err'][el]);
	    				}
	    				else
	    					alert('Ein Fehler ist aufgreten, bitte versuchen Sie es erneut!');
	    				if(!this.firstError) this.firstError = $(el);
	    				this.addError($(el));
	    			}
	    			if (this.elementToRemove && this.elementToRemove != this.firstError && this.options.display.indicateErrors == 1) {
	    				this.removeError(this.elementToRemove);
	    			}
	    			this.focusOnError(this.firstError);
	    		}
	    	}
		});
		
		// show JS based buttons
		$$('.button').each(function(el) { el.setStyle('display', 'block'); });

		// remove one-form ...
		$('signup').getChildren().each(function(el) { el.inject(this, 'before'); }.bind($('signup')));
		$('signup').destroy();
		$('submit_button').destroy();

		// prepare tabs for js view
		$$('#stepsContainer .steps').each(function(el)
		{
			el.setStyles({'display': 'block', 'height': '300px'});
		});
		
		// ... replace with few form's for scriptbased requests
		if ($('fieldset_login'))
		{
			new Element('form', {'id': 'form_login', 'method': 'post', 'action': '/DE/register', 'name': 'reg'}).wraps($('fieldset_login'), 'top');
			new Element('input', {'type': 'hidden', 'name': 'jscall', 'value': 'Register::checkLogin'}).inject($('fieldset_login'), 'top');
		}
		if ($('fieldset_address'))
		{
			new Element('form', {'id': 'form_address', 'method': 'post', 'action': '/DE/register'}).wraps($('fieldset_address'), 'top');
			new Element('input', {'type': 'hidden', 'name': 'jscall', 'value': 'Register::checkAddress'}).inject($('fieldset_address'), 'top');
		}
		if ($('fieldset_payment'))
		{
			new Element('form', {'id': 'form_payment', 'method': 'post', 'action': '/DE/register'}).wraps($('fieldset_payment'), 'top');
			new Element('input', {'type': 'hidden', 'name': 'jscall', 'value': 'Register::checkPayment'}).inject($('fieldset_payment'), 'top');
			new Element('input', {'type': 'hidden', 'name': 'membership', 'value': 'Deluxe', 'id': 'membership'}).inject($('fieldset_payment'), 'top');
		}
		
		// form checks
		// step 1 login-data
	    formcheck_login = new FormCheck('form_login', {
	    	'display': {'showErrors': 1, 'indicateErrors': 2, 'errorsLocation': 1 },
	    	'submitByAjax': true,
	    	'onAjaxSuccess': function(data) { this.AjaxErrorHandler(data) },
	    	'onAjaxFailure': function() { alert('failed'); }
	    });
	    // step 2 adress-data
	    formcheck_address = new FormCheck('form_address', {
	    	'display': {'showErrors': 1, 'indicateErrors': 2, 'errorsLocation': 1 },
	    	'submitByAjax': true,
	    	'onAjaxSuccess': function(data) { this.AjaxErrorHandler(data) },
	    	'onAjaxFailure': function() { alert('failed'); }
	    });
	    // step 3 payment-data
	    formcheck_payment = new FormCheck('form_payment', {
	    	'display': {'showErrors': 1, 'indicateErrors': 2, 'errorsLocation': 1 },
	    	'submitByAjax': true,
	    	'onAjaxRequest': function()
	    	{
	    		if ($('memberDeluxe') && $('memberDeluxe').checked)
	    			$('membership').set('value', 'Deluxe');
	    		else if ($('memberPower') && $('memberPower').checked)
	    			$('membership').set('value', 'Power');
	    		else if ($('memberBasis') && $('memberBasis').checked)
	    			$('membership').set('value', 'Basic');
	    	}, 
	    	'onAjaxSuccess': function(data) { this.AjaxErrorHandler(data) },
	    	'onAjaxFailure': function() { alert('failed'); }
	    });
		$$('.selectAbo').addEvent('click', function(e) {
			var id = $(e.target).getParent().get('id');
			if(id==null) id = e.target.getParent().getParent().get('id');
			activateClass(id);
			$(id).getElement('td input').checked = 'checked';
		});
	
		var slideOptions = {};
		if (typeof startingSlide != 'undefined') slideOptions.startingSlide = startingSlide;
		myTabs = new SlidingTabs('selectorContainer', 'stepsContainer', slideOptions);
	}

	// tooltips
	$('tip-basic').store('tip:text', LANG.register.tip_basic);
	if($('tip-power')) $('tip-power').store('tip:text', LANG.register.tip_power);
	if($('tip-deluxe')) $('tip-deluxe').store('tip:text', LANG.register.tip_deluxe);
	if ($('tip-username'))
		$('tip-username').store('tip:text', "Denke dir einen Benutzernamen aus und schau nach, ob er noch frei ist. Mit deinem Benutzernamen kannst du "+LANG.app.sitename+" <strong>anonym</strong> nutzen.");
	if ($('tip-birthday'))
		$('tip-birthday').store('tip:text', "Gib hier dein richtiges Geburtsdatum ein. Du musst mindestens 18 Jahre alt sein.");
	if ($('tip-cvv'))
		$('tip-cvv').store('tip:text', "Die Pr&uuml;fnummer besteht aus 3 oder 4 Ziffern ohne Leerzeichen. Du findest sie auf der R&uuml;ckseite deiner Kreditkarte.<br /><br /><img src=\"/images/register/tip_cvv.png\" width=\"205\" height=\"137\" alt=\"CVV\" /><br />");
	/*
	var SimpleTip = new Tips($$('.help'),
	{
		  className: 'register-tip', 
		  showDelay: 0,
		  hideDelay: 0,
		  offsets: {x: 15, y: 15},
		  fixed: true
	});*/
	
	var OwnTip = new OwnTips($$('.help'), $('reg-tooltip'));
	
    // switch pay type's
    $('pay_type').addEvent('change', function()
	{
    	pay_type = this.options[this.selectedIndex].value;
    	// creditcard
    	if (pay_type == 'cc')
    	{
    		changeClass('debit_note','hide');
    		changeClass('credit_card','show');
    		changeClass('div_debit','standard');
    		changeClass('div_credit','payment_active');
    		changeClass('div_tpay','standard');
    		if (!oldie)
    		{
	    		formcheck_payment.reinitialize();    		
	    		formcheck_payment.dispose($('bank_holder'));
	    		formcheck_payment.dispose($('bank_number'));
	    		formcheck_payment.dispose($('bank_code'));
	    		formcheck_payment.register($('creditcard_validcode'));
	    		formcheck_payment.register($('creditcard_holder'));
	    		formcheck_payment.register($('creditcard_number'));
    		}
    	}
    	// elv
    	else
    	{
    		changeClass('debit_note','show');
    		changeClass('credit_card','hide');
    		changeClass('div_debit','payment_active');
    		changeClass('div_credit','standard');
    		changeClass('div_tpay','standard');
    		if (!oldie)
    		{
    			formcheck_payment.reinitialize();
	    		formcheck_payment.register($('bank_holder'));
	    		formcheck_payment.register($('bank_number'));
	    		formcheck_payment.register($('bank_code'));
	    		formcheck_payment.dispose($('creditcard_validcode'));
	    		formcheck_payment.dispose($('creditcard_holder'));
	    		formcheck_payment.dispose($('creditcard_number'));
    		}
    	}
	});
	
});

function activateClass(labelID) {
	var ids = new Array("mDeluxe","mPower","mBasis");				
	for (var i=0;i<ids.length;++i) {			
		changeClass(ids[i],ids[i] + ((ids[i]===labelID)?'_on':'_off'));			
	}
}
var checkRunning=false;
function checknick (el){
	if(!checkRunning) {
		checkRunning = true;
		jslink('/DE/register/', {nick:$("nick").value}, 'Register::checkNick', function(result) {
			checkRunning=false;
			if (result == 'false')
				el.errors.push("Dieser Benutzername ist leider bereits vergeben oder unzulässig!");
			return !!result;
		});
	}
}
function changeClass(theElem, myClass) {
	if ($(theElem))
	{
		$(theElem).className = myClass;
		$(theElem).getParent().className = myClass;
	}
}

// @todo: function entfernen wenn formcheck komplett implementiert
function checkpflicht(elementId)	{
	var theElement = $(elementId);
	if (theElement.value == "")
		theElement.className = "pflicht";
	else
		theElement.className = "";
}

Element.extend({
   ajaxLoad: function(url){
       new Ajax(url, {method: 'get', update:this}).request();
   }
});
/*changeClass('memberGold','lowerIndex');
changeClass('memberSilver','lowerIndex');
changeClass('memberBronze','lowerIndex');
changeClass('mBronze','mBronze_on');*/

// Documentation: http://creativepony.com/journal/scripts/sliding-tabs/
// version: 1.8
var SlidingTabs = new Class({
  options: {
    startingSlide: false, // sets the slide to start on, either an element or an id 
    activeButtonClass: 'active', // class to add to selected button
    activationEvent: 'click', // you can set this to ‘mouseover’ or whatever you like
    wrap: true, // calls to previous() and next() should wrap around?
    slideEffect: { // options for effect used to animate the sliding, see Fx.Base in mootools docs
      duration: 400 // 0.4 of a second
    },
    animateHeight: true, // animate height of container
    rightOversized: 0 // how much of the next pane to show to the right of the current pane
  },
  current: null, // zero based current pane number, read only
  buttons: false,
  buttonsClickable: false,
  outerSlidesBox: null,
  innerSlidesBox: null,
  panes: null,
  fx: null, // this one animates the scrolling inside
  heightFx: null, // this one animates the height
  
  
  initialize: function(buttonContainer, slideContainer, options) {
    if (buttonContainer) { this.buttons = $(buttonContainer).getChildren(); }
    this.outerSlidesBox = $(slideContainer);
    this.innerSlidesBox = this.outerSlidesBox.getFirst();
    this.panes = this.innerSlidesBox.getChildren();
    
    this.setOptions(options);
    
    this.fx = new Fx.Scroll(this.outerSlidesBox, this.options.slideEffect);
    this.heightFx = this.outerSlidesBox.effect('height', this.options.slideEffect);
    
    // set up button highlight
    this.current = this.options.startingSlide ? this.panes.indexOf($(this.options.startingSlide)) : 0;
    if (this.buttons) { this.buttons[this.current].addClass(this.options.activeButtonClass); }
    this.disableInputs();
    
    // add needed stylings
    this.outerSlidesBox.setStyle('overflow', 'hidden');
    this.panes.each(function(pane, index) {
      pane.setStyles({
       'float': 'left',
       'overflow': 'hidden',
       'display': 'block'
      });
    }.bind(this));
    
    // stupidness to make IE work - it boggles the mind why this has any effect
    // maybe it's something to do with giving it layout?
    this.innerSlidesBox.setStyle('float', 'left');
    
    if (this.options.startingSlide) this.fx.toElement(this.options.startingSlide);
    
    // add events to the buttons
    if (this.buttons && this.buttonsClickable) this.buttons.each( function(button) {
      button.addEvent(this.options.activationEvent, this.buttonEventHandler.bindWithEvent(this, button));
    }.bind(this));
    
    if (this.options.animateHeight)
      this.heightFx.set(this.panes[this.current].offsetHeight);
    
    
    // set up all the right widths inside the panes
    this.recalcWidths();
  },
  
  // to change to a specific tab, call this, argument is the pane element you want to switch to.
  changeTo: function(element, animate) {
    if ($type(element) == 'number') element = this.panes[element - 1];
    if (!$defined(animate)) animate = true;
    var event = { cancel: false, target: $(element), animateChange: animate };
    try{this.fireEvent('change', event);}catch(e){};
    if (event.cancel == true) { return; };
    
    if (this.buttons) { this.buttons[this.current].removeClass(this.options.activeButtonClass); };
    this.current = this.panes.indexOf($(event.target));
    this.disableInputs();
    if (this.buttons) { this.buttons[this.current].addClass(this.options.activeButtonClass); };
    
    this.fx.cancel();
    if (event.animateChange) {
      this.fx.toElement(event.target);
    } else {
      this.outerSlidesBox.scrollTo(this.current * this.outerSlidesBox.offsetWidth.toInt(), 0);
    }
    
    if (this.options.animateHeight)
      this.heightFx.start(this.panes[this.current].offsetHeight);
  },
  
  // Handles a click
  buttonEventHandler: function(event, button) {
    if (event.target == this.buttons[this.current]) return;
    this.changeTo(this.panes[this.buttons.indexOf($(button))]);
  },
  
  // call this to go to the next tab
  next: function() {
    var next = this.current + 1;
    if (next == this.panes.length) {
      if (this.options.wrap == true) { next = 0 } else { return }
    }
    this.changeTo(this.panes[next]);
  },

  // to go to the previous tab
  previous: function() {
    var prev = this.current - 1
    if (prev < 0) {
      if (this.options.wrap == true) { prev = this.panes.length - 1 } else { return }
    }
    
    this.changeTo(this.panes[prev]);
  },
  
  // call this if the width of the sliding tabs container changes to get everything in line again
  recalcWidths: function() {
    this.panes.each(function(pane, index) {
      pane.setStyle('width', this.outerSlidesBox.offsetWidth.toInt() - this.options.rightOversized + 'px');
    }.bind(this));
    
    this.innerSlidesBox.setStyle(
      'width', (this.outerSlidesBox.offsetWidth.toInt() * this.panes.length) + 'px'
    );
    
    // fix positioning
    if (this.current > 0) {
      this.fx.cancel();
      this.outerSlidesBox.scrollTo(this.current * this.outerSlidesBox.offsetWidth.toInt(), 0);
    }
  },
  
  
  /**
   * added 09-05-14 cg
   * 
   * Verhindert fehlerhafte Anzeige von Panes, welche durch die Nutzung der Tab-Taste ausgelöst werden können.
   * Deaktiviert alle Inputs, Selects und Anchors.
   * 
   */
  disableInputs: function() {
	  this.panes.each(function(pane, index) {
		  pane.getElements('input, select').each(function(el) { el.disabled = (index != this.current); }.bind(this));
		  pane.getElements('a').each(function(el) { el.setStyle('display', (index != this.current) ? 'none' : 'block'); }.bind(this));
	    }.bind(this));
  }
});

SlidingTabs.implement(new Options, new Events);

var OwnTips = new Class(
{
	layer: null,
	initialize: function(elements, layer)
	{
		this.layer = layer;
		this.layer.setStyle('display', 'block').fade('hide');
		elements.each(function(el)
		{
			el.addEvent('mouseenter', this.show);
			el.addEvent('mouseleave', this.hide);
		}.bind(this));	
	},
	show: function(event)
	{
		var layer = $('reg-tooltip');
		var coords = $(this).getCoordinates();
		layer.getElement('.content').set('html', $(this).retrieve('tip:text'));
//		layer.setStyles({'position': 'absolute', 'left': (coords.left+15) + 'px', 'top': (coords.top+15) + 'px'}).fade('in');
		// cause f***** ie png fade bug
		layer.setStyles({'position': 'absolute', 'left': (coords.left+15) + 'px', 'top': (coords.top+15) + 'px'}).fade('show');
	},
	hide: function(event)
	{
		var layer = $('reg-tooltip');
//		layer.fade('out');
		layer.fade('hide');
	}
});