/**
* Mandantenspezifische Scripte
* @requires prototype1.6, core.js
* @author	Florian Weber (florian.weber@pixelpark.com)
*/
Element.addMethods(['TEXTAREA'],{maxLength: function(element, max){
	var limit = max;
	element = $(element);
	function counter(){
		if (element.value.length > limit) {
		    element.value = element.value.substring(0, limit);
		    element.scrollTop = element.scrollHeight;
		}
	};
	element.observe('change', function(){
		counter();
	});
	element.observe('keyup', function(){
		counter();
	});
	element.observe('keypress', function(){
		counter();
	});
	 element.observe('blur', function(){
		 counter();
	});
	counter();
	return element;
}});

/**
* Ruft die initial Events und Pruefungen fuer die Seite auf
* @author	Florian Weber (florian.weber@pixelpark.com)
*/
function initMandantEvents(){
	ppInit.topnavi().startStyle();
	ppInit.roundedCorners().startStyle();
	ppInit.subnavi();
//	ppInit.accordion('accordionBlockLeftCol');
	ppInit.moreLink();
	if($('userNoteText') != null)
	$('userNoteText').maxLength(2000);
}

/**
* Namespace fuer die Initialisierungen
* @author	Florian Weber (florian.weber@pixelpark.com)
*/
ppInit = {


	/**
	* Manipuliere die Hauptnavigation. Sobald die Eintraege zu breit werden stelle die letzten
	* Elemente in einer neuen Zeile dar.
	* @author	Florian Weber (florian.weber@pixelpark.com)
	*/
	topnavi: function() {
		if($('topnavi')) {
			/**
			* Konfiguration der TopNavi
			*/
			this.config = function() {
				this.totalAvailWidth = $('topnavi').getStyle('width');
				return this;
			}
			this.getEntryCount = function(){
				var entryCount = $$('#topnavi li').length;
				return entryCount;
			}

			this.getEntriesWidth = function() {
				widthComplete = 0;
				var list2 = new Array();
				totalAvailWidth = ppInit.topnavi().config().totalAvailWidth;

				allListElements = $$('#topnavi li');
				allListElements.each(function(ele) {
					widthComplete += parseInt(ele.getStyle('width')) + 3;
					if(widthComplete > parseInt(ppInit.topnavi().config().totalAvailWidth)) {
						list2[list2.length] = ele;
					}
					
				})
				this.widthComplete = widthComplete;
				this.list2 = list2;
				return this;
			}
			/**
			* Wenn die breite der LIs breiter als der zur verfuegungstehende Platz ist, zaehle die extra-Elemente und
			* parse Sie in das Element #extraRow
			*/
			this.startStyle = function() {
				if(!$("extraRow")){
					$$("#topnavi ul")[0].insert({before: new Element('ul', { 'id': 'extraRow' })});
				}
				if($$('#topnavi ul li')[0]) {
					//cd(ppInit.topnavi().getEntriesWidth().widthComplete +" - "+ parseInt(ppInit.topnavi().config().totalAvailWidth))
					if(ppInit.topnavi().getEntriesWidth().widthComplete > parseInt(ppInit.topnavi().config().totalAvailWidth)) {
						extraListLength = ppInit.topnavi().getEntriesWidth().list2.length; //entrylength of extra listelements that are to long to fin in normal row
						//cd(extraListLength)
						allListElements = $$('#topnavi li');
						standardRow = $A(allListElements).length - extraListLength; //normal navigation row without special styles
						allListElements.each(function(ele, index) {
							if(index >= standardRow) { //all elements that are longer than totalAvailWidth
								try {$('extraRow').insert({bottom: ele});}
								catch(e){
									alert(e);
								};
							}
						})
					}
				}
			}
			return this;
		}

	},

	roundedCorners: function() {
		//Hier bodyIds hinzufuegen, die roundedCorners haben sollen.
		bodyIdWrap = "";
		if($('bsNeuesProdukt')) {
			$('content').addClassName('corners');
		}
		if($('detailseite') && $('pageContent')) {
			$('pageContent').addClassName('corners');
		}
		if($('detailseite') && $('recommendation')) {
			$('recommendation').addClassName('corners');
		}
		if($('warenkorb')) {
			if($('intro')) $('intro').addClassName('corners');
		}
		if($('bsPruefen')) {
			if($('intro')) $('intro').addClassName('corners');
		}
//		if($('bsLogin')) {
//			$('content').addClassName('corners');
//		}
//		if($('kundendaten')) {
//			$('content').addClassName('corners');
//		}

		if(ele = $$('.corners')) {
			/**
			* Konfiguration der abgerundeten Ecken
			*/
			this.config = function() {
				//this.totalAvailWidth = $('topnavi').getStyle('width');
				return this;
			}

			/**
			* Wenn die breite der LIs breiter als der zur verfuegungstehende Platz ist, zaehle die extra-Elemente und
			* parse Sie in das Element #extraRow
			*/
			this.startStyle = function() {
				ele.each(function(elem) {
					if($('bsNeuesProdukt') && elem == $('content')) {
						bodyIdWrap = "bsNeuesProduktRounded";
					}
					if($('bsNeuesProdukt') && elem == $('recommendation')) {
						bodyIdWrap = "recommendationRounded";
					}
					if(elem == $('pageContent')) {
						bodyIdWrap = "pageContentRounded";
					}
					if($('detailseite') && elem == $('recommendation')) {
						bodyIdWrap = "recommendationRounded";
					}
					if(($('warenkorb') || $('bsPruefen')) && elem == $('intro')) {
						bodyIdWrap = "introRounded";
					}
					if(($('kontakt')) && elem == $('kunde')) {
						bodyIdWrap = "introRounded";
					}
//					if($('bsLogin') && elem == $('content')) {
//						bodyIdWrap = "bsLoginRounded";
//					}
//					if($('kundendaten') && elem == $('content')) {
//						bodyIdWrap = "bsKundendatenRounded";
//					}

					elem.wrap('div', {'class' : bodyIdWrap + ' roundedCorners'})
					elem.wrap('div', {'class' : 'topLeft'})
					elem.up('.topLeft').insert({top: '<div class="topRight"></div>'});
					elem.wrap('div', {'class' : 'bottomLeft'})
					elem.up('.bottomLeft').insert({top: '<div class="bottomRight"></div>'});
					elem.wrap('div', {'class' : 'borderLeft'});
					elem.wrap('div', {'class' : 'borderRight'});
					elem.up('.borderRight').insert({bottom: '<div class="clearMe"></div>'});
					//elem.up('.bottomLeft').insert({top: '<div class="bottomRight"></div>'});
					elem.removeClassName('corners');
				})

			}

			return this;
		}
	},

	/**
	* Auf der Detailseite steht ein mehr-Link - Bei klick vergrößert sich das div mit der Artikelbeschreibung
	 * @author	Florian Weber (florian.weber@pixelpark.com)
	 */
	moreLink: function() {
		if(ele = $$('.moreLink')[0]) {
			Event.observe(ele, 'click', function(){
				if($$('.artikeltext')) $$('.artikeltext span')[0].setStyle('height: auto;');
				ele.addClassName('inv');
			})
			XPLAIN.core.disableHref(ele, true);
		}
	},

	subnavi: function(){
		try {
		if(ele = $('subnavi')) {
			if(ele.select('li').length > 0) {
				var allLis = $$("#subnavi>ul>li");
				allLis[allLis.length-1].addClassName("last");
				return this;
			}
		}
		} catch(ex){
		}
	},

	accordion: function(accordionID){
		var options = {
			// The speed of the accordion
			resizeSpeed : 8,
			// The classnames to look for
			classNames : {
				// The standard class for the title bar
				toggle : 'accordionToggle',
				// The class used for the active state of the title bar
				toggleActive : 'accordionToggleActive',
				// The class used to find the content
				content : 'accordionContent'
			},
			// If you don't want the accordion to stretch to fit
			// its content, set a value here, handy for horixontal examples.
			defaultSize : {
				height : 'auto',
				width : 'width'
			},
			// The direction of the accordion
			direction : 'vertical',
			// Should the accordion activate on click or say on mouseover? (apple.com)
			onEvent : 'click'
		}
		//console.debug(options);
		try{
			new Accordion(accordionID, options);
		} catch(e){
			//throw 'Accordion: No Element found!';
		}

	}

}

function checkIKnow(thisObj){
	if(thisObj.checked){
		document.getElementById("submitForward").removeAttribute("disabled");
		document.getElementById("submitForward").style.display = "block";
	} else {
		document.getElementById("submitForward").setAttribute("disabled", "disabled");
		document.getElementById("submitForward").style.display = "none";

	}
}


var Treadmill = Class.create();
Treadmill.prototype = {
	container : null,
	viewPortItems : 6,
	itemWidth : 110,
	items: null,
	effMove : null,
	counter: 0,
	isStopped: false,
	direction: 1,
	initialize: function(container, content) {
		if (!$(container)) {
			throw(container + " doesn't exist!");
		} else {
			this.container = $(container);
		}
		this.items = content;
		this.contentBox = this.container.select(".treadmillContent")[0];
		this.container.observe('mouseover', this._stop.bindAsEventListener());
		this._fill(content);
		//this._start(1);
	},
	_fill: function(content) {
		var contentString = "";
		var $this = this;
		content.each(function(item){
			contentString+= '<li><a href="'+item.ahref+'"><img src="'+item.image+'" alt="" /><span class="details">'+item.name+'<br /><span class="price">'+item.price+'</span></span></a></li>';
		})
		this.contentBox.update(contentString);
//		this.contentBox.select('li').each(function(item){
//			item.observe('mouseover', $this._stop.bind(null, $this))
//			item.observe('mouseout', $this._mouseOut.bind(null, $this))
//		})
	},
	_start: function(direction) {
		this.isStopped = false;
		var $this = this;
		var dur = 1;
		var moveLength = -1*direction*this.itemWidth;
		this.effMove = new Effect.Move(this.contentBox,{x : moveLength,y : 0 , duration:dur, afterFinish:$this._next.bind(null,$this, direction)});
	},
	_stop: function() {
		var $this = arguments[0];
		$this._start($this.direction);
	},
	_mouseOut: function() {
		var $this = arguments[0];
		console.debug($this);
		$this._start();
	},
	_getMaxCount: function() {
		return this.items.length-this.viewPortItems;
	},
	_next: function() {
		var $this = arguments[0];
		$this.counter++;
		var direction = arguments[1];
		if($this.counter>=$this._getMaxCount()) {
			$this.counter = 0;
			direction = direction*-1;
		}
		$this._sleep(2000);
		if(!$this.isStopped) {
			$this.direction = direction;
			$this._start(direction);
		}
		//options.$this._start(options.direction);
	},
	_sleep: function(ms){
		var now=(new Date()).getTime();
		var end=now+ms;
		while((new Date()).getTime()<end){};
	}
}

hasCheckWarenkorbWAError = false;
function checkWarenkorbWA(thisObj, minAmount, url){
	var inp = $(thisObj).ancestors()[2].select('.anzahlCol input')[0];
	if(inp.value < minAmount) {
		var p = new Element("p", {"style": "font-weight:bold;color:red;padding-top: 10px;"}).update(locations.errorWAMinAmount.replace(/###value###/, minAmount));
		if(!hasCheckWarenkorbWAError) {
			$('warenkorbform').insert({before: p});
			hasCheckWarenkorbWAError = !hasCheckWarenkorbWAError;
		}
	}else {
		document.location = url;
	}
}

/**
 * Prototype onload-Event
 */
Event.observe(window, 'load', function(){
    initMandantEvents();
});