function stripeTable(selector) {
	$(selector + " tr:nth-child(odd)").addClass("odd");
}

function get(variable) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i = 0; i < vars.length; i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
			return pair[1];
		}
	}
	return false;
}

function marketTicker(id) {
	this.id = id;
	this.waiting = false;
	this.root = 'http://www.btinternet.com/~maureenselby/grainco/';
//	this.root = 'http://www.agtrader.co.uk/grey/';
	this.removeContent = function(id) {
		$('#' + id + ' table,#' + id + ' div.error').remove();
	};
	this.showLoading = function() {
		var myClass = this;
		$('#' + this.id + ' div.loading').fadeIn(500, function() { myClass.removeContent(myClass.id) });
	};
	this.hideLoading = function(id) {
		$('#' + id + ' div.loading').fadeOut(500);
		this.waiting = false;
	};
	this.getMarketData = function(market) {
		switch ($.trim(market)) {
			case "t": case "ebm": case "ema": case "eco":
				var url = "LatestPrices_" + $.trim(market) + "-enc.htm";
				break;
			case "s": case "sm": case "bo": case "c": case "qbs": case "qsm": case "qbo": case "qbc": case "cl":
				var url = "LatestPrices_" + $.trim(market) + ".htm";
				break;
			case "w": case "qbw": case "qbp":
				var url = "LatestPrices_" + $.trim(market.toUpperCase()) + ".htm";
				break;
		}
		url = this.root + url;
		this.showLoading();
		var myClass = this;
		window.setTimeout(function() {
			$.ajax({
				type: "POST",
				url: '/proxy.asmx/getURL',
				data: 'strURL=' + url,
				cache: false,
				dataType: "xml",
				timeout: 2000,
				success: function(data) {
					var title = $(data).find('table>tbody>tr>td').eq(0).text();
					title = title.match(/[0-9].*/);
					$('#' + myClass.id + ' div.loading').before('<table cellpadding="0" cellspacing="0"><thead><tr><th colspan="3">Last Update: ' + title + '</th></tr></thead><tbody></tbody></table>');
					$(data).find('table tr > tr').each(function() {
						var month = $(this).find('td:eq(0)').text();
						var figure = $(this).find('td:eq(2)').text();
						var change = $(this).find('td:eq(3)').text();
						if ('' == $.trim(change)) {
							change = '&nbsp;';
						} else if ('+' == change.substr(0, 1)) {
							change = '<span class="pos">' + change + '</span>';
						} else if ('-' == change.substr(0, 1)) {
							change = '<span class="neg">' + change + '</span>';
						}
						$('#' + myClass.id + ' table tbody').append('<tr><td class="month">' + month + '</td><td>' + figure + '</td><td>' + change + '</td></tr>');
					});
					stripeTable('#' + myClass.id + ' tbody');
					window.setTimeout(function() { myClass.hideLoading(myClass.id) }, 1000);
				},
				error: function() {
					$('#' + myClass.id + ' div.loading').before('<div class="error"><p>There was an error loading the market data</p></div>');
					window.setTimeout(function() { myClass.hideLoading(myClass.id) }, 1000);
				}
			});
		}, 600);
	};
	this.changeMarket = function(dir) {
		if (dir == '') {
			dir = 'next';
		}
		if (this.waiting) {
			return false;
		}
		this.waiting = true;
		if (dir == 'next' && $('#' + this.id + ' h4 span.active').next('span').length > 0) {
			var market = $('#' + this.id + ' h4 span.active').next().attr('id').replace('market-', '');
			$('#' + this.id + ' h4 span.active').hide('slow').removeClass('active').next().show('slow').addClass('active');
		} else if (dir == 'prev' && $('#' + this.id + ' h4 span.active').prev('span').length > 0) {
			var market = $('#' + this.id + ' h4 span.active').prev().attr('id').replace('market-', '');
			$('#' + this.id + ' h4 span.active').hide('slow').removeClass('active').prev().show('slow').addClass('active');
		} else if (dir == 'prev') {
			var market = $('#' + this.id + ' h4 span:last').attr('id').replace('market-', '');
			$('#' + this.id + ' h4 span.active').hide('slow').removeClass('active');
			$('#' + this.id + ' h4 span:last').show('slow').addClass('active');
		} else {
			var market = $('#' + this.id + ' h4 span:first').attr('id').replace('market-', '');
			$('#' + this.id + ' h4 span.active').hide('slow').removeClass('active');
			$('#' + this.id + ' h4 span:first').show('slow').addClass('active');
		}
		this.getMarketData(market);
	};
	this.nextMarket = function() {
		this.changeMarket('next');
	};
	this.prevMarket = function() {
		this.changeMarket('prev');
	};
	this.interval = null;
	this.setUpLinks = function() {
		var id = this.id;
		$('#' + this.id + ' a.next').attr({ href: 'javascript:' + this.id + '.nextMarket();' });
		$('#' + this.id + ' a.prev').attr({ href: 'javascript:' + this.id + '.prevMarket();' });
		eval("$('#' + this.id).hover(function() {clearInterval(" + id + ".interval);},function() { " + this.id + ".interval = setInterval(function() {" + this.id + ".nextMarket()} , 30000); });");
	}
	this.changeMarket();
	this.setUpLinks();
	eval('this.interval = setInterval(function() {' + this.id + '.nextMarket()} , 30000);');
}

function showDocumentDetail(link) {
	if (!(document.getElementById('docDetailContainer'))) {
		var bh = $(document).height();
		$('body').append('<div id="docDetailWrapper" style="display: none; width: 100%; height: ' + bh + 'px; position: absolute; background: #000; top: 0; left: 0; z-index: 500;">&nbsp;</div><div id="docDetailContainer" style="display: none; position: absolute; z-index: 501;"></div>');
	}
	if (!(animRunning)) {
		animRunning = true;
		$('div#docDetailContainer').empty();
		$('div#docDetailWrapper').css({ opacity: 0, display: "block" }).animate({ opacity: 0.6 }, 500, function() {
			var ww = $(window).width(); var wh = $(window).height(); var scroll = $(document).scrollTop();
			var yOffset = scroll + 100; var xOffset = Math.floor((ww - 550) / 2);
			$('div#docDetailContainer').css({ position: "absolute", top: yOffset + "px", left: xOffset + "px", minHeight: "340px", width: "550px" }).fadeIn("medium", function() {
				animRunning = false;
			}).append('<a href="javascript:hideDocumentDetail();" style="display: block; position: absolute; top: 10px; right: 24px; width: 32px; height: 20px;">&nbsp;</a>');
			$('div#docDetailWrapper').click(function() {
				hideDocumentDetail();
			});
		});
		$('div#docDetailContainer').append("<div></div>");
		if ($(link).parents("div.doc").hasClass('restricted')) {
			var restricted = true;
			$('div#docDetailContainer div').addClass("restricted");
		} else {
			$('div#docDetailContainer div').addClass("details");
		}
		var source = $(link).parents("div.doc").find("div.details");
		var details = '';
		var download = '';
		details = details + '<dl>';
		if ($(source).find('p.ref').text() != '') {
			details += '<dt>Reference:</dt><dd>' + $(source).find('p.ref').text() + '</dd>';
		}
		if ($(source).find('p.version').text() != '') {
			details += '<dt>Version:</dt><dd>' + $(source).find('p.version').text() + '</dd>';
		}
		if ($(source).find('div.abstract').text() != '') {
			details += '<dt>Overview:</dt><dd>' + $(source).find('div.abstract').html() + '</dd>';
		}
		if ($(source).find('p.ext').text() != '') {
			var txt = '';
			switch ($(source).find('p.ext').text().toLowerCase()) {
				case "pdf":
					txt = 'PDF Document';
					break;
				default:
					txt = $(source).find('p.ext').text().toUpperCase();
					break;
			}
			details += '<dt>File Type:</dt><dd>' + txt + '</dd>';
		}
		if ($(source).find('p.size').text() != '') {
			details += '<dt>Size:</dt><dd>' + $(source).find('p.size').text() + '</dd>';
		}
		download = '<a href="javascript:hideDocumentDetail();" class="c">&nbsp;</a>';
		if (restricted) {
			details += '<dt class="restriction">Access:</dt><dd>Authorised Users Only</dd>';
			download += '<a href="javascript:hideDocumentDetail();showLogin(true);" class="dl">&nbsp;</a></p>';
		} else {
			details += '<dt>Access:</dt><dd>You are authorised to download this file</dd>';
			download += '<a href="' + $(link).attr("href") + '" class="dl">&nbsp;</a>';
		}
		details += '</dl>';
		$('div#docDetailContainer div').html('<h3>' + $(source).find("h4").text() + '</h3>'+details).after('<div class="download">'+download+'</div>');
		$('dd p:last').css("margin", "0");
		if (restricted) {
			$('div#docDetailContainer div.download').removeClass('donwload').addClass('noDownload');
		}
	}
}

function hideDocumentDetail() {
	if (!(animRunning)) {
		animRunning = true;
		$('div#docDetailContainer').fadeOut(500, function() {
			$('div#docDetailWrapper').fadeOut(500, function() {
				animRunning = false;
			});
		});
	}
}

function showLogin(force) {
	if (!(animRunning) || force == true) {
		animRunning = true;
		$('#memberLogin div.form *').css("opacity", "0");
		$('#memberLogin div.form').slideDown(500, function() {
			$('#memberLogin p').css("background-image", 'url(/img/close.png)');
			$('#memberLogin div.form *').animate({ opacity: 1 }, 250, function() {
				animRunning = false;
				$('#memberLogin div.form input:first').focus();
			});
		});
	}
}

function hideLogin() {
	if (!(animRunning)) {
		animRunning = true;
		$('#memberLogin div.form *').animate({ opacity: 0 }, 250, function() {
			$('#memberLogin div.form').slideUp(500, function() {
				$('#memberLogin p').css("background-image", 'url(/img/open.png)');
				animRunning = false;
			});
		});
	}
}

$(function(){
	$('.twitter div.tweet:gt(0)').hide();
	setInterval(function(){
		$('.twitter div.tweet:eq(0)').fadeOut(250, function(){
			$('.twitter div.tweet:eq(1)').fadeIn(250);
			$('.twitter div.tweet:eq(0)').appendTo('.twitter');
		});
	}, 10000);
});

$(document).ready(function() {
	$("img.icon").each(function(i) {
		$(this).wrap('<div class="icon"></div>');
		var $tooltip = $(this).attr('title');
		$(this).after('<div class="tooltip"><p><img src="/img/tooltip-right.png" alt="" class="after" />' + $tooltip + '</p></div>');
	});
	$("ul#mainmenu li, div.icon").hover(function() {
		$(this).addClass("over");
	}, function() {
		$(this).removeClass("over");
	});
	stripeTable("tbody");
	$('div.market').slowEach(1000, function() {
		window['' + $(this).attr('id')] = new marketTicker($(this).attr('id'));
	});
	animRunning = false;
	$('#memberLogin a.toggler').click(function() {
		if ($('#memberLogin div.form').css("display") == 'none') {
			showLogin();
		} else {
			hideLogin();
		}
		return false;
	});
	$('#memberLogin > div > span').each(function() {
		if ($(this).css("display") != "none") {
			showLogin();
		}
	});
	$('div.documents h4 a').click(function(e) {
		showDocumentDetail($(this));
		return false;
	});
});