var stocks = {
	//object to keep the details of a proposed transaction
	pendingTrade: {stock: '', tradeAmount: 0, action: '', timeout: 10},

	//make the rows show and hide on click
	activateRows: function () {
		rows = $('stocks').getElementsByTagName('tr');
		for (var i=0; i<rows.length; i++) {
			if (/collapsed/i.test(rows[i].className) || /expanded/i.test(rows[i].className)) {
				rows[i].onclick = stocks.toggleRow;
			} else if (/tradestocks/i.test(rows[i].className)) {
				Element.hide(rows[i]);
			}
		}

		//add behaviour to the buy/sell buttons
		btns = $('stocks').getElementsByTagName('button');
		for (var i=0; i<btns.length; i++) {
			btns[i].onclick = stocks.initiateTrade;
		}

		//make the buybasket button active
		if ($('bundle')) {
			bundleBtn = $('bundle').getElementsByTagName('button')[0];
			bundleBtn.onclick = stocks.initiateTrade;
		}

		//hide the stocktrading message boxes
		if ($('confirmbox'))  Element.hide($('confirmbox'));
		if ($('feedbackbox')) Element.hide($('feedbackbox'));

		//set events for the buttons confirm transaction button
		if ($('okdeal')) $('okdeal').onclick = function() {
			Element.hide($('confirmbox'));
			stocks.doPendingTrade();
			if (tradeInterval) window.clearInterval(tradeInterval);
		}

		//set events for the buttons cancel transaction button
		if ($('canceldeal')) $('canceldeal').onclick = function () {
			Element.hide($('confirmbox'));
			if (tradeInterval) window.clearInterval(tradeInterval);
		}
	},

	//make a row show of hide
	toggleRow: function () {
		if (this.nextSibling.nodeName == '#text') {
			Element.toggle(this.nextSibling.nextSibling);
		} else {
			Element.toggle(this.nextSibling);
		}

		if (/collapsed/i.test(this.className)) {
			Element.removeClassName(this, 'collapsed');
			Element.addClassName(this, 'expanded');
		} else {
			Element.addClassName(this, 'collapsed');
			Element.removeClassName(this, 'expanded');	
		}
	},

	//initiate trade
	initiateTrade: function () {
		Element.hide($('feedbackbox'));
		Element.hide($('confirmbox'));

		function Round(number, decimals) {
			power = Math.pow(10, parseInt(decimals));
			return Math.round(number * power) / power;
		}

		if (typeof(transactions) == 'undefined') {
			alert('transactions object not initialized');
			return false;
		}

		//get the desired action, id of the stock and the amount
		if (this.parentNode.id == 'bundle') {
			action = 'buybundle';
			stock  = 0;
			tradeAmount = 1;
		} else {
			action = this.id.split('_')[0];
			stock  = this.id.split('_')[1];
			tradeAmount = parseInt($(action + '_amount_' + stock).value);
		}

		if (tradeAmount < 1 || isNaN(tradeAmount)) {
			feedback = 'Je moet een geldig aantal aandelen invullen.';

			$('feedbackbox').innerHTML = feedback + '<br /><button>Ok</button>';
			$('feedbackbox').getElementsByTagName('button')[0].onclick = function () {
				Element.hide('feedbackbox');
			}
			$('hovermsg').style.top = stocks.boxPosition() + 'px';
			Element.show($('feedbackbox'));

			window.setTimeout(function (){Element.hide($('feedbackbox'));}, 10000);
			//window.scrollTo(0,0);
			return;
		}

		//get the price details for the proposed transaction
		money = transactions.getPriceQuote(stock, tradeAmount, action);

		if (typeof money.priceQuote.error != 'undefined') {
			switch (money.priceQuote.error) {
				case 'invalid amount':
					feedback = 'Je moet een geldig aantal aandelen invullen.';
					break;
				case 'invalid transaction type':
					feedback = 'Verkeerd transactie type';
					break;
				default:
					feedback = money.priceQuote.error;
			}

			$('feedbackbox').innerHTML = feedback + '<br /><button>Ok</button>';
			$('feedbackbox').getElementsByTagName('button')[0].onclick = function () {
				Element.hide('feedbackbox');
			}
			$('hovermsg').style.top = stocks.boxPosition() + 'px';
			Element.show($('feedbackbox'));

			window.setTimeout(function (){Element.hide($('feedbackbox'));}, 10000);
			//window.scrollTo(0,0);

			return;
		}

		//place the details in the object
		stocks.pendingTrade.stock = stock;
		stocks.pendingTrade.tradeAmount = tradeAmount;
		stocks.pendingTrade.action = action;

		//set the confirmation message
		if (action == 'buybundle') {
			confirmMsg = 'Een mandje met van elk aandeel één exemplaar kost '	+ money.priceQuote + '\n. Wil je doorgaan?';
		} else {
			confirmMsg = 'Deze deal zou je ' + money.dealPrice;
			confirmMsg += ' credits ' + (action == 'sell' ? 'opleveren' : 'kosten') + '. Tegen ' + money.priceQuote + ' per aandeel. \n';
			confirmMsg += 'Je vermogen gaat dan van ' + money.oldCredits + ' credits naar ' + money.newCredits + ' credits.\n';
			confirmMsg += 'Wil je doorgaan?';
		}

		//fill the confirm box and show it
		stocks.pendingTrade.timeout = 10;
		$('message').innerHTML = confirmMsg;
		$('okdeal').innerHTML = 'Doorgaan (' + stocks.pendingTrade.timeout + ')';
		
		//console.log($('confirmbox').style.top);
		Element.show($('confirmbox'));
		$('hovermsg').style.top = stocks.boxPosition() + 'px';
		//window.scrollTo(0,0);

		//make the timer update the confirmbutton every second
		tradeInterval = window.setInterval(function() {
			if (stocks.pendingTrade.timeout == 0) {
				window.clearInterval(tradeInterval);
				Element.hide($('confirmbox'));
			} else {
				$('okdeal').innerHTML = 'Doorgaan (' + stocks.pendingTrade.timeout + ')';
				stocks.pendingTrade.timeout--;
			}
		}, 1000);
	},

	//execute the trade when the user presses the confirm ("Doorgaan") button
	doPendingTrade: function () {
		$('message').innerHTML = '';

		//do the actual transaction
		trans = transactions.tradeStocks(stocks.pendingTrade.stock, stocks.pendingTrade.tradeAmount, stocks.pendingTrade.action);

		//handle the response from the ajax object
		if (typeof(trans) == 'undefined') {
			feedback = 'Er is iets fout gegaan';

		} else if (typeof(trans.error) == 'string') {
			switch (trans.error) {
				case 'BUYING_TOO_MANY':
					feedback = 'De bank heeft er niet zoveel. Koop een lager aantal.';
					break;

				case 'SELLING_TOO_MANY':
					feedback = 'Je wilt meer verkopen dan je hebt, bied een lager aantal aan.';
					break;

				case 'TOO_FEW_CREDITS':
					feedback = 'Je hebt niet genoeg geld voor deze transactie';
					break;

				default:
					feedback = trans.error;
			}

		} else {
			feedback  = 'Je hebt ' + trans.amount;
			feedback += ' ' + (action == 'buybundle' ? 'mandje' : 'exemplaren') + ' ' + (action == 'sell' ? 'ver' : 'ge') + 'kocht tegen ';
			feedback += trans.price + ' credits per exemplaar.\n';
			feedback += 'Dit heeft je ' + trans.totalPrice;
			feedback += ' credits ';
			feedback += action == 'sell' ? 'opgeleverd' : 'gekost'; 

			$('usercredits').innerHTML = trans.userCredits;
		}

		$('feedbackbox').innerHTML = feedback + '<br /><button>Ok</button>';
		$('feedbackbox').getElementsByTagName('button')[0].onclick = function () {
			Element.hide('feedbackbox');
		}
		$('hovermsg').style.top = stocks.boxPosition() + 'px';

		pageUpdater.fetchData();

		Element.show($('feedbackbox'));

		window.setTimeout(function (){
			Element.hide($('feedbackbox'));
		}, 10000);
		//window.scrollTo(0,0);
	},

	boxPosition: function () {
		var screenTop;

		if (window.innerHeight) {
			screenTop = window.pageYOffset + (window.innerHeight / 2);
		} else if (document.documentElement && document.documentElement.scrollTop) {
			screenTop = document.documentElement.scrollTop + (document.documentElement.clientHeight / 2);
		} else if (document.body) {
			screenTop = document.body.scrollTop + (document.body.clientHeight / 2);
		}

		return parseInt(screenTop - 250);
	}
}