MINMUSLI.articleManagerClass = new Class({
	
	storage: [], // used to emulate element.store and element.retrieve when called directly
	
	initialize: function() {
		// request object used to get the article to edit when clicking an edit link
		this.editBasketRequest = new Request.JSON({
			url: 'index.php', 
			link: 'chain',
			onRequest: function() {
				$('contentInner').addClass('waiting');
			},
		 	onFailure: function() {
				alert('Ett oväntat fel inträffade. Vänligen ladda om sidan och försök igen.');
			},
			onSuccess: function(jsonData) {
				MINMUSLI.basketArticleToEdit = jsonData;
				if (!$chk(MINMUSLI.editBasketSlide)) {
					// for some reason, this is not defined in IE when the class is instanciated
					MINMUSLI.editBasketSlide = new Fx.Slide($('editBasket'), {link: 'chain'}).hide();
					$('editBasket').setStyle('display', 'block');
				}
				// slide out current slide if there is one, then change the data to the current data, then remove the waiting spinner
				MINMUSLI.editBasketSlide.slideOut().chain(
					function() { 
						MINMUSLI.articleManager.updateArticleData(); 
						this.callChain(); 
					},
					function() { 
						this.slideIn(); 
						this.callChain(); 
					},
					function() { 
						$('contentInner').removeClass('waiting'); 
					}
				);
			}
		});
	},
	
	// updates the data in the edit pane
	// called onSuccess in editBasketRequest
	updateArticleData: function() {
		// inject article data into edit basket pane
		$('editBasketImage').empty(); 
		new Element('img', { // article image (info taken from top level array articles)
			src: MINMUSLI.articles[MINMUSLI.basketArticleToEdit.uid].image.src, 
			width: MINMUSLI.articles[MINMUSLI.basketArticleToEdit.uid].image.width,
			height: MINMUSLI.articles[MINMUSLI.basketArticleToEdit.uid].image.height,
			alt: MINMUSLI.basketArticleToEdit.name
		}).inject($('editBasketImage'));
		if (MINMUSLI.articles[MINMUSLI.basketArticleToEdit.uid].header_image.src) {
			$('editBasketName').empty();
			new Element('img', { // header image
				src: MINMUSLI.articles[MINMUSLI.basketArticleToEdit.uid].header_image.src, 
				width: MINMUSLI.articles[MINMUSLI.basketArticleToEdit.uid].header_image.width,
				height: MINMUSLI.articles[MINMUSLI.basketArticleToEdit.uid].header_image.height,
				alt: MINMUSLI.basketArticleToEdit.name
			}).inject($('editBasketName'));
		} else {
			$('editBasketName').set('text', MINMUSLI.basketArticleToEdit.name);
		}
		$('editBasketUnitPrice').set('text', MINMUSLI.basketArticleToEdit.unit_price);
		$('editBasketUnitWeight').set('text', MINMUSLI.basketArticleToEdit.unit_weight);
		$('editBasketShortDescription').set('text', MINMUSLI.basketArticleToEdit.short_description);
		var q = (parseInt(MINMUSLI.basket[MINMUSLI.basketArticleToEdit.uid]) < 10) ? '0' + MINMUSLI.basket[MINMUSLI.basketArticleToEdit.uid] : MINMUSLI.basket[MINMUSLI.basketArticleToEdit.uid];
		$('editBasketQuantity').set('html', q);
		$('editBasketPrice').set('text', MINMUSLI.basketArticleToEdit.unit_price * MINMUSLI.basket[MINMUSLI.basketArticleToEdit.uid]);
		$('editBasketWeight').set('text', MINMUSLI.basketArticleToEdit.unit_weight * MINMUSLI.basket[MINMUSLI.basketArticleToEdit.uid]);
		$('editBasket').store('articleUid', MINMUSLI.basketArticleToEdit.uid);
	},
	
	
	getBasketRow: function(uid) {
		// build the basket table row to use in other functions
		var basketRow = new Element('tr', {'id': 'basketArticle' + uid});
		var viewArticleLink = new Element('a', { 
			'text': MINMUSLI.articles[uid].name_abbr, 
			'href': MINMUSLI.thisUrl + '#article' + uid, 
			'id': 'basketViewArticle' + uid
		}).inject(new Element('td', {'class': 'article'}).inject(basketRow));
		viewArticleLink.addEvent('click', function() { // go the the right category on click
			$$('.categorySheet').removeClass('selected'); // hide others
			$$('#selectToppingsCategories li').removeClass('selected');
			$('categorySheet' + MINMUSLI.articles[uid].subcategory).addClass('selected'); // show new category
			$('category' + MINMUSLI.articles[uid].subcategory).addClass('selected');
		});
		var units = MINMUSLI.basket[uid] == 1 ? 'skopa' : 'skopor';
		new Element('td', {
			'html': MINMUSLI.basket[uid] + '&nbsp;' + units + ' (' + MINMUSLI.articles[uid].unit_weight * MINMUSLI.basket[uid] + '&nbsp;g)', 
			'class': 'quantity'
		}).inject(basketRow);
		var editLink = new Element('a', {
			'href': '#', 
			'id': 'editArticle' + uid,
			'class': 'editArticle',
			'text': MINMUSLI.basketEditLinkText
		}).inject(new Element('td', {'class': 'edit'}).inject(basketRow));
		editLink.store('id', uid);
		editLink.addEvent('click', this.articleEditPane);
		basketRow.addEvent('mouseenter', function() { this.addClass('hover'); }).addEvent('mouseleave', function() { this.removeClass('hover') });
		return basketRow;
	},
	
	addUnit: function(uid) {
		// check that basket isn't full
		if (this.checkMaxWeight(parseInt(MINMUSLI.articles[uid].unit_weight) + MINMUSLI.basketTotalWeight) && parseInt(MINMUSLI.articles[uid].unit_weight) + MINMUSLI.basketTotalWeight != MINMUSLI.basketMaxWeight) {
			return MINMUSLI.basket[uid];
		}
		// add to session data
		var basketRequest = new Request({url: 'index.php', link: 'chain'}).get({
			'eID': 'tx_mycereal_basket',
			'action': 'addToppingUnit',
			'articleUid': uid,
			'timestamp': new Date().getTime()
		});
		// add to basket 
		if (MINMUSLI.basket[uid]) { // add quantity to existing article
			MINMUSLI.basket[uid]++;
			var basketRow = this.getBasketRow(uid);
			basketRow.replaces($('basketArticle' + uid));
			basketRow.highlight();
			// add to basket form
			$('basketContentsFormField' + uid).set('value', parseInt($('basketContentsFormField' + uid).get('value')) + 1);
			
		} else { // add article
			MINMUSLI.basket[uid] = 1;
			var basketRow = this.getBasketRow(uid);
			basketRow.inject($('basketTableBody'));
			basketRow.highlight();
			$('article' + uid).addClass('inBasket');
			new Element('input', { 'type': 'hidden', 'name': 'tx_mycereal_mixer[toppings][' + uid + ']', 'id': 'basketContentsFormField' + uid, 'value': '1' }).inject($('basketContentsForm'));
		}
		MINMUSLI.basketTotalWeight += parseInt(MINMUSLI.articles[uid].unit_weight);
		MINMUSLI.basketTotalPrice += parseInt(MINMUSLI.articles[uid].unit_price);
		$('basketTotalWeight').set('text', MINMUSLI.basketTotalWeight).highlight();
		$('basketTotalPrice').set('text', MINMUSLI.basketTotalPrice).highlight();
		//var comparisonPrice = Math.round((basketTotalPrice / (basketTotalWeight / 1000)) * 100) / 100;
		//$('basketComparisonPrice').set('text', comparisonPrice).highlight(); 
		if (MINMUSLI.basketTotalWeight) {
			$('meterFilled').setStyle('width', Math.round((MINMUSLI.basketTotalWeight / MINMUSLI.basketMaxWeight) * 100) + '%');
		}
		MINMUSLI.step3Access();
		
		// calculate nutritions
		var currentAmount;
		var addedAmount;
		var newAmount;
		for (var key in MINMUSLI.articles[uid].nutrition) {
			if (!MINMUSLI.basketNutrition[key]) {
				MINMUSLI.basketNutrition[key] = 0;
			}
			currentAmount = MINMUSLI.basketNutrition[key] / MINMUSLI.articles[uid].nutrition[key].dividend * (MINMUSLI.basketTotalWeight - MINMUSLI.articles[uid].unit_weight);
			addedAmount = MINMUSLI.articles[uid].unit_weight * MINMUSLI.articles[uid].nutrition[key].value / MINMUSLI.articles[uid].nutrition[key].dividend; 
			newAmount = currentAmount + addedAmount; 
			MINMUSLI.basketNutrition[key] = (newAmount / MINMUSLI.basketTotalWeight) * MINMUSLI.articles[uid].nutrition[key].dividend;
			$$('#basket dd.' + key, '#basket dt.' + key).setStyle('display', 'block');
			$$('#basket span.' + key).set('text', Math.round(MINMUSLI.basketNutrition[key] * MINMUSLI.articles[uid].nutrition[key].roundPrecision) / MINMUSLI.articles[uid].nutrition[key].roundPrecision).highlight();
		}
		
		return MINMUSLI.basket[uid];
	},
	
	removeUnit: function(uid) {
		// update session data
		var basketRequest = new Request({url: 'index.php', link: 'chain'}).get({
			'eID': 'tx_mycereal_basket',
			'action': 'removeToppingUnit',
			'articleUid': uid,
			'timestamp': new Date().getTime()
		});
		if (MINMUSLI.basket[uid] > 1) {
			MINMUSLI.basket[uid]--;
			var basketRow = this.getBasketRow(uid);
			basketRow.replaces($('basketArticle' + uid));
			basketRow.highlight();
			$('basketContentsFormField' + uid).set('value', parseInt($('basketContentsFormField' + uid).get('value')) - 1);
		} else {
			MINMUSLI.basket[uid] = 0;
			$('basketArticle' + uid).destroy();
			$('article' + uid).removeClass('inBasket');
			$('basketContentsFormField' + uid).destroy();
		}
		MINMUSLI.basketTotalWeight -= parseInt(MINMUSLI.articles[uid].unit_weight);
		MINMUSLI.basketTotalPrice -= parseInt(MINMUSLI.articles[uid].unit_price);
		$('basketTotalWeight').set('text', MINMUSLI.basketTotalWeight).highlight();
		$('basketTotalPrice').set('text', MINMUSLI.basketTotalPrice).highlight();
		//var comparisonPrice = Math.round((basketTotalPrice / (basketTotalWeight / 1000)) * 100) / 100;
		//$('basketComparisonPrice').set('text', comparisonPrice).highlight();
		if (MINMUSLI.basketTotalWeight) {
			$('meterFilled').setStyle('width', Math.round((MINMUSLI.basketTotalWeight / MINMUSLI.basketMaxWeight) * 100) + '%');
		}
		// close alert boxes if open
		if (MINMUSLI.maxWeightAlertSlide.open) {
			MINMUSLI.maxWeightAlertSlide.addEvent('complete', function() {
				$('selectToppingsAlertContainer').setStyle('padding-bottom', 0);
				MINMUSLI.maxWeightAlertSlide.removeEvents('complete');
			}).slideOut();
		}
		if (MINMUSLI.weightAlertSlide.open && MINMUSLI.basketTotalWeight < MINMUSLI.basketAlertWeight) {
			MINMUSLI.weightAlertSlide.addEvent('complete', function() {
				$('selectToppingsAlertContainer').setStyle('padding-bottom', 0);
				MINMUSLI.weightAlertSlide.removeEvents('complete');
			}).slideOut();
		}
		if (MINMUSLI.basketTotalWeight < MINMUSLI.basketAlertWeight) {
			this.deactivateBasketOrderButton();
		}
		MINMUSLI.step3Access();
		
		// calculate nutritions
		var currentAmount;
		var removedAmount;
		var newAmount;
		for (var key in MINMUSLI.articles[uid].nutrition) {
			if (!MINMUSLI.basketNutrition[key]) {
				MINMUSLI.basketNutrition[key] = 0;
			}
			currentAmount = MINMUSLI.basketNutrition[key] / MINMUSLI.articles[uid].nutrition[key].dividend * (MINMUSLI.basketTotalWeight + MINMUSLI.articles[uid].unit_weight);
			removedAmount = MINMUSLI.articles[uid].unit_weight * MINMUSLI.articles[uid].nutrition[key].value / MINMUSLI.articles[uid].nutrition[key].dividend; 
			newAmount = currentAmount - removedAmount; 
			MINMUSLI.basketNutrition[key] = (newAmount / MINMUSLI.basketTotalWeight) * MINMUSLI.articles[uid].nutrition[key].dividend;
			$$('#basket dd.' + key, '#basket dt.' + key).setStyle('display', 'block');
			$$('#basket span.' + key).set('text', Math.round(MINMUSLI.basketNutrition[key] * MINMUSLI.articles[uid].nutrition[key].roundPrecision) / MINMUSLI.articles[uid].nutrition[key].roundPrecision).highlight();
		}
		
		return MINMUSLI.basket[uid];
	},
	
	updateArticle: function(uid, quantity) {
		// check that basket isn't full
		if (MINMUSLI.basket[uid] < parseInt(quantity) && this.checkMaxWeight((parseInt(MINMUSLI.articles[uid].unit_weight) * quantity) + MINMUSLI.basketTotalWeight)) {
			return MINMUSLI.basket[uid];
		}
		// update session data
		var basketRequest = new Request({url: 'index.php', link: 'chain'}).get({
			'eID': 'tx_mycereal_basket',
			'action': 'updateTopping',
			'articleUid': uid,
			'quantity': quantity,
			'timestamp': new Date().getTime()
		});
		// calculate total weight and price
		if (MINMUSLI.basket[uid] > parseInt(quantity)) { // new quantity is less than old
			MINMUSLI.basketTotalWeight -= (MINMUSLI.basket[uid] - parseInt(quantity)) * parseInt(MINMUSLI.articles[uid].unit_weight);
			MINMUSLI.basketTotalPrice -= (MINMUSLI.basket[uid] - parseInt(quantity)) * parseInt(MINMUSLI.articles[uid].unit_price)
			// close alert boxes if open
			if (MINMUSLI.maxWeightAlertSlide.open) {
				MINMUSLI.maxWeightAlertSlide.addEvent('complete', function() {
					$('selectToppingsAlertContainer').setStyle('padding-bottom', 0);
					MINMUSLI.maxWeightAlertSlide.removeEvents('complete');
				}).slideOut();
			}
			if (MINMUSLI.weightAlertSlide.open && MINMUSLI.basketTotalWeight < MINMUSLI.basketAlertWeight) {
				MINMUSLI.weightAlertSlide.addEvent('complete', function() {
					$('selectToppingsAlertContainer').setStyle('padding-bottom', 0);
					MINMUSLI.weightAlertSlide.removeEvents('complete');
				}).slideOut();
			}
			if (MINMUSLI.basketTotalWeight < MINMUSLI.basketAlertWeight) {
				this.deactivateBasketOrderButton();
			}
			
			// calculate nutritions
			var currentAmount;
			var removedAmount;
			var newAmount;
			for (var key in MINMUSLI.articles[uid].nutrition) {
				if (!MINMUSLI.basketNutrition[key]) {
					MINMUSLI.basketNutrition[key] = 0;
				}
				currentAmount = MINMUSLI.basketNutrition[key] / MINMUSLI.articles[uid].nutrition[key].dividend * (MINMUSLI.basketTotalWeight + ((MINMUSLI.basket[uid] - quantity) * MINMUSLI.articles[uid].unit_weight));
				removedAmount = (MINMUSLI.basket[uid] - quantity) * MINMUSLI.articles[uid].unit_weight * MINMUSLI.articles[uid].nutrition[key].value / MINMUSLI.articles[uid].nutrition[key].dividend; 
				newAmount = currentAmount - removedAmount; 
				MINMUSLI.basketNutrition[key] = (newAmount / MINMUSLI.basketTotalWeight) * MINMUSLI.articles[uid].nutrition[key].dividend;
				$$('#basket dd.' + key, '#basket dt.' + key).setStyle('display', 'block');
				$$('#basket span.' + key).set('text', Math.round(MINMUSLI.basketNutrition[key] * MINMUSLI.articles[uid].nutrition[key].roundPrecision) / MINMUSLI.articles[uid].nutrition[key].roundPrecision).highlight();
			}
		} else if (MINMUSLI.basket[uid] < parseInt(quantity)) { // new quantity is greater than old
			MINMUSLI.basketTotalWeight += (parseInt(quantity) - MINMUSLI.basket[uid]) * parseInt(MINMUSLI.articles[uid].unit_weight);
			MINMUSLI.basketTotalPrice += (parseInt(quantity) - MINMUSLI.basket[uid]) * parseInt(MINMUSLI.articles[uid].unit_price);
			
			// calculate nutritions
			var currentAmount;
			var addedAmount;
			var newAmount;
			for (var key in MINMUSLI.articles[uid].nutrition) {
				if (!MINMUSLI.basketNutrition[key]) {
					MINMUSLI.basketNutrition[key] = 0;
				}
				currentAmount = MINMUSLI.basketNutrition[key] / MINMUSLI.articles[uid].nutrition[key].dividend * (MINMUSLI.basketTotalWeight - ((MINMUSLI.basket[uid] + quantity) * MINMUSLI.articles[uid].unit_weight));
				addedAmount = (MINMUSLI.basket[uid] + quantity) * MINMUSLI.articles[uid].unit_weight * MINMUSLI.articles[uid].nutrition[key].value / MINMUSLI.articles[uid].nutrition[key].dividend; 
				newAmount = currentAmount + addedAmount; 
				MINMUSLI.basketNutrition[key] = (newAmount / MINMUSLI.basketTotalWeight) * MINMUSLI.articles[uid].nutrition[key].dividend;
				$$('#basket dd.' + key, '#basket dt.' + key).setStyle('display', 'block');
				$$('#basket span.' + key).set('text', Math.round(MINMUSLI.basketNutrition[key] * MINMUSLI.articles[uid].nutrition[key].roundPrecision) / MINMUSLI.articles[uid].nutrition[key].roundPrecision).highlight();
			}
			return MINMUSLI.basket[uid];
		}
		if (quantity > 0) { // update article
			MINMUSLI.basket[uid] = parseInt(quantity);
			var basketRow = this.getBasketRow(uid);
			basketRow.replaces($('basketArticle' + uid));
			basketRow.highlight();
			new Element('input', { 'type': 'hidden', 'name': 'tx_mycereal_mixer[toppings][' + uid + ']', 'id': 'basketContentsFormField' + uid, 'value': quantity }).replaces($('basketContentsFormField' + uid));
		} else { // remove article
			MINMUSLI.basket[uid] = 0;
			$('basketArticle' + uid).destroy();
			$('article' + uid).removeClass('inBasket');
			$('basketContentsFormField' + uid).destroy();
		}
		$('basketTotalWeight').set('text', MINMUSLI.basketTotalWeight).highlight();
		$('basketTotalPrice').set('text', MINMUSLI.basketTotalPrice).highlight();
		//var comparisonPrice = Math.round((basketTotalPrice / (basketTotalWeight / 1000)) * 100) / 100;
		//$('basketComparisonPrice').set('text', comparisonPrice).highlight();
		if (MINMUSLI.basketTotalWeight) {
			$('meterFilled').setStyle('width', Math.round((MINMUSLI.basketTotalWeight / MINMUSLI.basketMaxWeight) * 100) + '%');
		}
		MINMUSLI.step3Access();
		return MINMUSLI.basket[uid];
	},
	
	// returns true if newTotalWeight is larger than or equal to the max weight, otherwise false
	checkMaxWeight: function(newTotalWeight) {
		if (newTotalWeight >= MINMUSLI.basketAlertWeight && newTotalWeight < MINMUSLI.basketMaxWeight) {
			if (MINMUSLI.maxWeightAlertSlide.open) { 
				MINMUSLI.maxWeightAlertSlide.addEvent('complete', function() {
					MINMUSLI.weightAlertSlide.slideIn();
					MINMUSLI.maxWeightAlertSlide.removeEvents('complete');
				}).slideOut();
			} else {
				MINMUSLI.weightAlertSlide.slideIn();
			}
			$('selectToppingsAlertContainer').setStyle('padding-bottom', '9px');
			this.activateBasketOrderButton();
		}
		if (newTotalWeight >= MINMUSLI.basketMaxWeight) {
			MINMUSLI.weightAlertSlide.addEvent('complete', function() {
				if (newTotalWeight == MINMUSLI.basketMaxWeight) {
					$$('#maxWeightAlert p').set('html', MINMUSLI.maxWeightAlertBasketFullText); // change message text if weight == maxWeight
				} else {
					$$('#maxWeightAlert p').set('html', MINMUSLI.maxWeightAlertText);
				}
				MINMUSLI.maxWeightAlertSlide.slideIn();
				MINMUSLI.weightAlertSlide.removeEvents('complete');
			}).slideOut();
			$('selectToppingsAlertContainer').setStyle('padding-bottom', '9px');
			this.activateBasketOrderButton();
			return true;
		}
		return false;
	},
	
	articleEditPane: function(e) { 
		e.stop();
		var articleUid = this.retrieve('id'); 
		if (articleUid == $('editBasket').retrieve('articleUid')) { // same link clicked again. close pane.
			$('editBasket').store('articleUid', 0); // reset articleUid so the same article can be edited again without page reload
			MINMUSLI.editBasketSlide.addEvent('complete', function() {
				$('editBasketContainer').setStyle('margin-bottom', 0);
				MINMUSLI.editBasketSlide.removeEvents('complete');
			}).slideOut();
			return;
		}
		MINMUSLI.articleManager.editBasketRequest.get({
			'eID': 'tx_mycereal_basket',
			'action': 'getArticle',
			'articleUid': articleUid
		});
	},
	
	activateBasketOrderButton: function() {
		$$('#basketButtonOrderDiv', '#basketButtonOrderDiv a').fade(1);
		$('basketButtonOrder').setStyle('cursor', 'pointer');
		$('basketButtonOrder').removeEvents('click');
		$('basketButtonOrder').addEvent('click', function(e) { e.stop(); $('basketContentsForm').submit(); });
		MINMUSLI.basketButtonOrderTips.detach($('basketButtonOrderDiv'));
		$('basketButtonOrderDiv').set('title', '');
	},
	
	deactivateBasketOrderButton: function() {
		$$('#basketButtonOrderDiv', '#basketButtonOrderDiv a').fade(0.5);
		$('basketButtonOrderDiv').set('title', 'Din blandning måste väga minst 380 g innan du kan beställa.');
		$('basketButtonOrder').setStyle('cursor', 'default');
		$('basketButtonOrder').removeEvents('click');
		$('basketButtonOrder').addEvent('click', function(e) { e.stop(); });
		MINMUSLI.basketButtonOrderTips.attach($('basketButtonOrderDiv'));
	},
	
	store: function(key, value) {
		this.storage[key] = value;
	},
	
	retrieve: function(key) {
		return this.storage[key];
	}
});

window.addEvent('domready', function() {
	MINMUSLI.articleManager = new MINMUSLI.articleManagerClass();
})

