var Tx_Mevshop_Product = new Class({

	Implements: [Options,Events],

	options: {
		sku: '',
		uid: '',
		guiElements: {
			amount: Element,	// <input>
			toCart: Element,		// <img>
			itemPriceCell: Element		// <td>
		},
		tgr: '',	// String, Teilegruppe
		ownerList: Class	// Tx_Mevshop_ProductList
	},

	validator: null,
	configInterfaceShown: false,
	fetchingProductData: false,	// ...wenn gerade Produktdaten geholt werden...
	amountTypingTimeoutId: null,	// für den Delay bei Eingabe von Produktdaten
	
	/**
	 * Constructor
	 */
	initialize: function(element, options) {
		this.setOptions(options);
		this.element = document.id(element);

		this.attachEvents();
		this.options.guiElements.amount.set('value', '');

		this.refreshProductPrice();
	},


	/**
	 * Events initialisieren
	 */
	attachEvents: function() {
			// beim Ändern des Textfeldes entsprechendes Event triggern
		this.options.guiElements.amount.addEvent('keyup', this.amountKeyAction.bind(this));

			// ebenso beim Klicken auf die "ItemPriceCell", die mehrere Funktionen (konfigurieren oder Preis anfragen) haben kann.
		this.options.guiElements.itemPriceCell.addEvent('click', this.itemPriceCellClick.bind(this));

			// beim Klicken auf den Warenkorb-Button...
		this.options.guiElements.toCart.addEvents({
			'click': this.addToCart.bind(this),

			/**
			 * nur, wenn ein verwertbarer Wert vorhanden ist, den Mouseover-Effekt und Tooltip anzeigen.
			 */
			'mouseenter': function() {
				if (this.getAmount()) {
					var elem = this.options.guiElements.toCart;
					addHover(elem);
					elem.getParent().setStyle('background-color', '#0a1e81');
					Tip(MooTools.lang.get('Tx_Mevshop_Product', 'addToCartToolTip'));
				}
			}.bind(this),

			'mouseleave': function() {
				var elem = this.options.guiElements.toCart;
				remHover(elem);
				elem.getParent().setStyle('background-color', '');
				UnTip();
			}.bind(this)
		});
	},


	/**
	 * Die Zelle für Preis anfragen, konfigurieren etc. wurde geklickt.
	 * @return void
	 */
	itemPriceCellClick: function() {
		if (this.getAmount()) {
			this.refreshProductPrice();
		}
	},


	getAddedToCartNotification: function() {
		return new Overlay(document.body, {
				id: 'Tx_Mevshop_ProductList_addedToCartOverlay',
				color: '#ffffff',
				//duration: 500,
				opacity: 0.7,
				onClick: function() {  this.close() },
				onOpen: function() {	// Function to execute immediately after the open directive has been given (before the opacity fade has completed)
					document.id('tx_mevshop_cart_basketNotification')
						.store('Overlay', this)
						.inject(document.body)
						.position()
						.fade('hide')
						.show()	// um den display:none aufzuheben
						.setStyles({
							'z-index': this.options.zIndex + 10
						})
						.fade('in');
				},
				onShow: function() {	// Function to execute when the overlay has completed it's fade in (after the "open" event)

				},
				onClose: function() {	//Function to execute immediately after the close directive has been given (before the opacity fade has completed).
					$('tx_mevshop_cart_basketNotification').fade('out')
				}
			});
	},


	/**
	 * Wird beim Ändern der Amount-Box getriggert.
	 * @param Event evt
	 */
	amountKeyAction: function(evt) {
		if ('left' === evt.key || 'right' === evt.key) return;

			// Inhalt verschönern, falls "krumme" Zahlen genannt werden
		if(amount = this.getAmount()) {
			this.options.guiElements.amount.set('value', amount);
		}

		if ('10' === this.options.sku.substr(0, 2) || '15' === this.options.sku.substr(0, 2)) {
			clearTimeout(this.amountTypingTimeoutId);
			this.amountTypingTimeoutId = this.refreshProductPrice.delay(500, this);
		} else {
			this.setInteractionItemsState();
		}
	},


	/**
	 * Setzt die Zellen für Menge, Preis Pro Stück, Warenkorb usw. je nach Situation
	 * @return void
	 */
	setInteractionItemsState: function() {
		if (this.getAmount()) {
			this.options.guiElements.toCart.setStyle('visibility', 'visible');

			this.options.guiElements.itemPriceCell
				.setStyle('cursor', 'pointer')
				.set('html', MooTools.lang.get('Tx_Mevshop_Product', 'requestPriceLabel'));

		} else {
			this.options.guiElements.toCart.setStyle('visibility', 'hidden');

			this.options.guiElements.itemPriceCell
				.setStyle('cursor', 'default')
				.set('html', MooTools.lang.get('Tx_Mevshop_Product', 'fillInQuantitiyLabel'));
		}
	},


	/**
	 * wird ausgeführt, wenn das Hinzufügen in den Warenkorb gewählt wurde
	 */
	addToCart: function() {
			// wenn kein Wert in der Textbox angegeben ist, nichts tun und Mengenhinweis hervorheben
		if(!this.getAmount()) {
			var elem = this.element.getElement('.itemprice');
			elem.highlight().get('tween').chain(function(){elem.setStyle('background-color', '');});
			return;
		}

			// lade-Icon anzeigen
		if (this.element) this.element.getElement('td.submit').setStyle('background-color', '');
		this.options.guiElements.toCart.src = this.options.guiElements.toCart.src.replace(new RegExp('([^/]+?)$'), 'loadingicon.gif');

			// Warenkorb-Add-Funktion per AJAX aufrufen
		new Request.JSON({
			url: 'index.php',

			onSuccess: function(responseJSON, responseText) {
				if ($H(responseJSON).getFromPath('shopdata.status.canOrder.msg')) {
					msgString = $H(responseJSON).getFromPath('shopdata.status.canOrder.msg')["#"];
						// allg. Fehler anzeigen
					this.showGeneralErrorMessage(msgString);

				}
				if (resultPosCount = responseJSON.shopdata.status.positioncount['#']) {

						// wenn eine positive Anzahl zurückgegeben wurde...
					$$('#topnav a.cartlink .amount').set('text', '(' + resultPosCount + ')');
					this.getAddedToCartNotification().open();
				}
			}.bind(this),

			onComplete: function() {
				this.options.guiElements.toCart.src = this.options.guiElements.toCart.src.replace(new RegExp('([^/]+?)$'), 'btn_basket.gif');
			}.bind(this)
		}).get(this.getCartAddOptions());
	},


	/**
	 * Gibt die Cart-Optionen zurück
	 * @return Object
	 */
	getCartAddOptions: function() {
		var amount = this.getAmount();
		if (!amount) amount = 1;
		var listType = this.element ? this.element.getElement('td input.list_type').get('value') : '';

		return {
				eID: 'tx_mevshop_eid_cart',
				action: 'add',
				options: $H({
					amount: amount,
					itemId: this.options.uid,
					itemNo: this.options.sku,
					list_type: listType
				}).toQueryString()
			};
	},




	
	/**
	 * Holt die Daten wie SML-Infos usw. aus dem Shop
	 * @return Object
	 */
	fetchProductData: function() {
		this.fetchingProductData = true;

		new Request.JSON({
			url: 'index.php',

			onRequest: function()	{

			}.bind(this),

			onSuccess: this.dispatchProductData.bind(this),

			onComplete: function(){this.fetchingProductData = false;this.setInteractionItemsState();}.bind(this)

		}).get({
			eID: 'tx_mevshop_dynItemData',
			'itemId': this.options.uid
		}); //END new ajax.request
	},


	/**
	 * Gibt die Werte für den Produktpreis zurück
	 * @return Object
	 */
	getProductPriceOptions: function(amount) {
		var amount = this.getAmount();
		
		return {
			eID: 'tx_mevshop_dynItemPrice',
			'itemId': this.options.uid,
			'itemNo': this.options.sku,
			'amount': amount
		};
	},


	/**
	 * Zeigt den Fehlerdialog wg. der Maximalmengengrenze an
	 */
	showMaxAmoutErrorMessage: function(maxAmount) {
		new Message({
			iconPath: tx_mevshop_div.options.extPath + 'res/img/jslib/Message/',
			icon: 'cautionMedium.png',
			title: MooTools.lang.get('Tx_Mevshop_Product', 'maxArticleAmountErrorTitle'),
			message: MooTools.lang.get(
					'Tx_Mevshop_Product',
					'maxArticleAmountError',
					maxAmount
			)
		}).tell();
	},


	/**
	 * Zeigt eine generelle Fehlermeldung an
	 */
	showGeneralErrorMessage: function(message) {
		new Message({
			iconPath: tx_mevshop_div.options.extPath + 'res/img/jslib/Message/',
			icon: 'cautionMedium.png',
			title: 'Error',
			message: message
		}).tell();
	},




	/**
	 * Aktualisiert den Produktpreis
	 */
	refreshProductPrice: function() {
		this.setInteractionItemsState();

		
		if(!this.getAmount()) {
				// amount ist keine gültige Zahl, also abbrechen.
			return;
		}



		var itemPriceCell = (this.configurationInterface ? this.configurationInterface.getElement('.priceDisplay') : this.options.guiElements.itemPriceCell);
			// Preis holen:
		new Request.JSON({
			url: 'index.php',

			onRequest: function()	{
				itemPriceCell.set('html', '<img src="typo3conf/ext/mevshop/res/img/loadingicon.gif" width="16" height="16" alt="Ladeicon" title="Ihr persönlicher Preis wird geladen..." />');
			}.bind(this),

			onSuccess: function(responseJSON, responseText) {
				if ($H(responseJSON).getFromPath('shopdata.xhrItemPrice.errormsg')) {
						// wenn eine Fehlermeldung zurückgegeben wurde...
					itemPriceCell.set('text', '..');

					if(maxAmount = $H(responseJSON).getFromPath('shopdata.xhrItemPrice.errormsg')["@"].maxAmount) {
							// wenn das Feld maxAmount gesetzt ist, gehen wir von einer Mengenbestellüberschreitung aus.
						this.showMaxAmoutErrorMessage(maxAmount);
						this.options.guiElements.amount.set('value', maxAmount);
						this.refreshProductPrice();
					}

				} else if (this.options.uid == parseInt($H(responseJSON).getFromPath('shopdata.xhrItemPrice.itemid.#')))	{
						// sicherheitshalber die Ist-Item-Id mit der Soll-Item-Id vergleichen;
						// dann den ermittelten Preis anzeigen:
					itemPriceCell.set('html',
						$H(responseJSON).getFromPath('shopdata.xhrItemPrice.baseprice.#')
							+ ' '
							+ $H(responseJSON).getFromPath('shopdata.xhrItemPrice.t3curr.#')
					);
				} else {
						// irgendetwas anderes hat nicht gestimmt; XX als Fallback anzeigen
					itemPriceCell.set('text', 'XX');
					this.showGeneralErrorMessage('DEBUG: ' + responseText);
				}
			}.bind(this),

			onFailure: function(xhr) {
				itemPriceCell.set('text', 'XX');
			}.bind(this)

		}).get(this.getProductPriceOptions()); //END new ajax.request
	},


	/**
	 * Gibt einen gültigen Zahlenwert der angegebenen Menge zurück, ggf. gerundet, oder NaN
	 */
	getAmount: function() {
		return Math.ceil(Math.abs(this.options.guiElements.amount.get('value').toInt()));
	},


	lang: {
		get: function(key, args) {
			return MooTools.lang.get('Tx_Mevshop_Product', key, args);
		}
	}
});
