var portalMessagesTimeout = 0;

function addToHistory(url)
{
	if (history && history.pushState)
	{
		try
		{
			var portalMenuItem = $('.portal-menu ul li');
			history.pushState(null, null, url);
			portalMenuItem.removeClass('active');
			portalMenuItem.each(function() {
				var linkHref = $(this).children('a').prop('href');
				if (!$(this).hasClass('expandable') && linkHref == url.replace('/ajax', '').substring(0, linkHref.length))
				{
					$(this).addClass('active');
				}
			});
		}
		catch (ex)
		{

		}
	}
}

$(document).ready(function() {
	if ($('.portal-messages .message-list').children('.message').length > 1) changePortalMessage(0);
	
	$('.portal-menu ul li.expandable > a').click(function(e) {
		$('.portal-menu ul li.expandable').removeClass('expanded');
		$(this).parent().addClass('expanded');
		
		$('.portal-menu ul li.expandable > ul').each(function(index, element) {
			if ($(this).parent().hasClass('expanded'))
			{
				var oldHeight = $(this).height();
				$(this).css({ height: 'auto' });
				var newHeight = $(this).height();
				if (oldHeight != newHeight)
				{
					$(this).css({ height: oldHeight }).animate({ height: newHeight, opacity: 1 }, 300, function() {
						$(this).css({ height: 'auto' });
						scaleToColumns(true);
					});
				}
			}
			else
			{
				var oldHeight = $(this).height();
				var newHeight = 0;
				if (oldHeight != newHeight)
				{
					$(this).css({ height: oldHeight }).animate({ height: newHeight, opacity: 0 }, 300, function() {
						scaleToColumns(true);
					});
				}
			}
		});
		
		return false;
	});
	$('.portal-menu ul li.expandable > ul').css({ height: 0, opacity: 0 });
	$('.portal-menu ul li.expandable.expanded > ul').css({ height: 'auto', opacity: 1 });
	scaleToColumns();
	
	if (history && history.pushState)
	{
		$('.portal-menu ul li a').click(function(e) {
			if (!$(this).parent().hasClass('expandable'))
			{
				var url = $(this).prop('href').replace('/portal/', '/ajax/portal/');
				if (url.indexOf("/portal/help") >= 0) return true;
				var newHistoryUrl = $(this).prop('href');
				addToHistory(newHistoryUrl);
				loadPortalContent(false, url, new Object(), $(this));
				return false;
			}
		});
	}
	
	$('#portal-help-button').click(function(e) {
		if ($('.portal-menu ul li.expandable > ul li.active a').length <= 0) return true;
		var url = $('.portal-menu ul li.expandable > ul li.active a').prop('href');
		if (url.indexOf('/portal/help') >= 0) return true;
		url = url.replace('/portal', '/portal/help');
		$(this).prop('href', url);
		return true;
	});
	
	$('body').click(function(e) {
		commodityPopupAlignElement = false;
		positionCommodityPopup();
	});
	
	initFieldFilters();
	initNotifyCheckboxes();
	initRowExpand();
	initCommodityCodesPopup();
});

function changePortalMessage(messageNum)
{
	clearTimeout(portalMessagesTimeout);
	var delayTime = 10000;
	
	if (messageNum > $('.portal-messages .message-list').children('.message').length - 1) messageNum = 0;
	
	var scrollText = false;
	var childNum = 0;
	$('.portal-messages .message-list').children('.message').each(function(index, element) {
		$(this).stop();
		if (childNum == messageNum)
		{
			$(this).css({ top: $('.portal-messages .message-list').height(), left: 0 }).animate({ top: 0 }, 200);
			if ($(this).width() > $('.portal-messages .message-list').width())
			{
				scrollText = true;
				var animTime = ($(this).width() - $('.portal-messages .message-list').width()) * 15;
				if (animTime < 0) animTime = 0;
				var gapTime = (delayTime / 2) - animTime;
				if (gapTime < 2000) gapTime = 2000;
				$(this).delay(gapTime).animate({ left: -($(this).width() - $('.portal-messages .message-list').width()) }, animTime, 'linear', function() {
					portalMessagesTimeout = setTimeout("changePortalMessage(" + (messageNum + 1) + ")", gapTime);
				});
			}
		}
		else
		{
			$(this).animate({ top: -$('.portal-messages .message-list').height() }, 200, function() {
				$(this).css({ top: '-100%', left: 0 });
			});
		}
		childNum++;
	});
	
	if (!scrollText)
	{
		portalMessagesTimeout = setTimeout("changePortalMessage(" + (messageNum + 1) + ")", delayTime);
	}
}

var originalFieldFilters = new Object();
var enterMessageAlignElement = false;
var popped = ('state' in window.history && window.history.state !== null), initialURL = location.href;
$(window).bind('popstate', function(e) {
	var initialPop = !popped && location.href == initialURL;
	popped = true;
	if (!initialPop)
	{
		var url = window.location.href.replace('/portal/', '/ajax/portal/');
		$('.portal-menu ul li').removeClass('active');
		$('.portal-menu ul li').each(function(index, element) {
			if (!$(this).hasClass('expandable') && $(this).children('a').prop('href') == url.replace('/ajax', '').substring(0, $(this).children('a').prop('href').length))
			{
				$(this).addClass('active');
			}
		});
		loadPortalContent(false, url, false, false, true);
	}
});
function initFieldFilters(contentArea)
{
	if (!contentArea) contentArea = $('#portal-content');
	//originalFieldFilters = new Object();
	enterMessageAlignElement = false;
	
	var contentAreaPortalTableWrapper = contentArea.children('.expanded-form, form').find('.portal-table-wrapper');
	if (contentAreaPortalTableWrapper.length == 0) contentAreaPortalTableWrapper = contentArea.children('.portal-table-wrapper');
	var contentAreaPortalTable = contentAreaPortalTableWrapper.children('.portal-table');
	var contentAreaTable = contentAreaPortalTable.children('table');
	var contentAreaFieldFilterCells = contentAreaTable.children('thead').children('tr:not(.header-row)').children('td, th').children('.cell-wrapper').children('.field-filter');
	
	contentAreaFieldFilterCells.children('input.text, select, input.date').each(function(index, element) {
		originalFieldFilters[$(this).prop('id')] = $(this).val();
	});
	
	contentArea.find('a.portal-ajax-link').unbind('click');
	contentArea.find('.portal-table > table > thead > tr:not(.header-row) > td, .portal-table > table > thead > tr:not(.header-row) > th').unbind('mouseover mouseout');
	contentAreaFieldFilterCells.children('input.text, select, input.date').unbind('keypress keyup focus blur');
	contentAreaFieldFilterCells.children('.clear-field').unbind('click');
	
	contentAreaFieldFilterCells.children('input.date').datepicker();
	contentAreaFieldFilterCells.children('input.date').datepicker('option', { dateFormat: "d M yy" });
	contentAreaFieldFilterCells.children('input.date').each(function(index, element) {
		$(this).datepicker('setDate', originalFieldFilters[$(this).prop('id')]);
	});
	
	if (history && history.pushState)
	{
		contentArea.find('a.portal-ajax-link').click(function(e) {
			var url = $(this).prop('href').replace('/portal/', '/ajax/portal/');
			var newHistoryUrl = $(this).prop('href');
			addToHistory(newHistoryUrl);
			loadPortalContent(contentArea, url);
			return false;
		});
	}
	contentArea.find('.portal-table > table > thead > tr:not(.header-row) > td, .portal-table > table > thead > tr:not(.header-row) > th').bind('mouseover', function(e) {
		if (!$(this).hasClass('expand-icon') && !$(this).hasClass('spacer'))
		{
			var hoverCell = $(this);
			var hoverColumn = 1;
			hoverCell.parent().parent().parent().children('thead').children('tr:not(.header-row)').children('td, th').each(function(index, element) {
				if ($(this).html() == hoverCell.html()) return false;
				if ($(this).attr('colspan'))
				{
					hoverColumn += parseInt($(this).attr('colspan'));
				}
				else
				{
					hoverColumn++;
				}
			});
			hoverCell.parent().parent().parent().children('tbody').children('tr').each(function(index, element) {
				var currentRow = $(this);
				var currentColumn = 1;
				currentRow.children('td, th').each(function(index, element) {
					if (currentColumn == hoverColumn)
					{
						$(this).addClass('col-hover');
						return false;
					}
					
					if ($(this).attr('colspan'))
					{
						currentColumn += parseInt($(this).attr('colspan'));
					}
					else
					{
						currentColumn++;
					}
				});
			});
		}
	});
	contentArea.find('.portal-table > table > thead > tr:not(.header-row) > td, .portal-table > table > thead > tr:not(.header-row) > th').bind('mouseout', function(e) {
		if (!$(this).hasClass('expand-icon'))
		{
			var hoverCell = $(this);
			var hoverColumn = 1;
			hoverCell.parent().parent().parent().children('thead').children('tr:not(.header-row)').children('td, th').each(function(index, element) {
				if ($(this).html() == hoverCell.html()) return false;
				if ($(this).attr('colspan'))
				{
					hoverColumn += parseInt($(this).attr('colspan'));
				}
				else
				{
					hoverColumn++;
				}
			});
			hoverCell.parent().parent().parent().children('tbody').children('tr').each(function(index, element) {
				var currentRow = $(this);
				var currentColumn = 1;
				currentRow.children('td, th').each(function(index, element) {
					if (currentColumn == hoverColumn)
					{
						$(this).removeClass('col-hover');
						return false;
					}
					
					if ($(this).attr('colspan'))
					{
						currentColumn += parseInt($(this).attr('colspan'));
					}
					else
					{
						currentColumn++;
					}
				});
			});
		}
	});
	
	contentAreaFieldFilterCells.children('input.text').bind('keypress', function(e) {
		if (e.keyCode && e.keyCode == 13)
		{
			return false;
		}
	});
	contentAreaFieldFilterCells.children('input.text').bind('keyup focus blur', function(e) {
		//if ($(this).closest('.risk-page') <= 0) {
			if (e.keyCode && e.keyCode == 13) {
				$('.portal-table').css('overflow', '');
				$('#enter-message-background').stop().fadeOut(500);
				enterMessageAlignElement = false;

				var url = $(this).closest('form').prop('action');
				var filters = new Object();
				if (contentArea.attr('id') == 'portal-content') {
					$(this).closest('form').children('input').each(function (index, element) {
						if ($(this).attr('type') == 'hidden') {
							filters[$(this).prop('name')] = $(this).val();
						}
					});
					$(this).closest('form').find('table tr .field-filter input.text, table tr .field-filter select').each(function (index, element) {
						if ($(this).closest('.expanded-area').length == 0) filters[$(this).prop('name')] = $(this).val();
					});
					$(this).closest('form').find('.main-filters select, .main-filters input.date').each(function (index, element) {
						filters[$(this).prop('name')] = $(this).val();
					});
					$(this).closest('form').find('.main-filters input.checkbox').each(function (index, element) {
						if ($(this).is(':checked')) {
							filters[$(this).prop('name')] = $(this).val();
						}
					});
				} else {
					url = $(this).closest('.expanded-form').children('a.expanded-form-action').prop('href');
					$(this).closest('.expanded-form').children('input').each(function (index, element) {
						if ($(this).attr('type') == 'hidden') {
							filters[$(this).prop('name')] = $(this).val();
						}
					});
					$(this).closest('.expanded-form').children('.portal-table-wrapper').children('.portal-table').children('table').children('thead').children('tr:not(.header-row)').children('td, th').children('.cell-wrapper').children('.field-filter').children('input.text, select').each(function (index, element) {
						filters[$(this).prop('name')] = $(this).val();
					});
				}
				if (url) {
					url = url.replace('/portal/', '/ajax/portal/');
					var newHistoryUrl = $(this).closest('form').prop('action');
					if (contentArea.attr('id') != 'portal-content') newHistoryUrl = $(this).closest('.expanded-form').children('a.expanded-form-action').prop('href');
					var firstFilter = true;
					for (var filterName in filters) {
						if (firstFilter) {
							newHistoryUrl += '?';
							firstFilter = false;
						} else {
							newHistoryUrl += '&';
						}
						newHistoryUrl += filterName + '=' + filters[filterName];
					}
					if (contentArea.attr('id') == 'portal-content') addToHistory(newHistoryUrl);
					loadPortalContent(contentArea, url, filters);
				}
			} else {
				checkFieldFilterValues(contentArea, e);
			}
		//}
	});
	contentAreaFieldFilterCells.children('select, input.date').bind('change', function(e) {
		//if ($(this).closest('.risk-page') <= 0) {
			$('.portal-table').css('overflow', '');
			$('#enter-message-background').stop().fadeOut(500);
			enterMessageAlignElement = false;

			var url = $(this).closest('form').prop('action');
			var filters = new Object();
			if (contentArea.attr('id') == 'portal-content') {
				$(this).closest('form').children('input').each(function (index, element) {
					if ($(this).attr('type') == 'hidden') {
						filters[$(this).prop('name')] = $(this).val();
					}
				});
				$(this).closest('form').find('table tr .field-filter input.text, table tr .field-filter select').each(function (index, element) {
					if ($(this).closest('.expanded-area').length == 0) filters[$(this).prop('name')] = $(this).val();
				});
				$(this).closest('form').find('.main-filters select, .main-filters input.date').each(function (index, element) {
					filters[$(this).prop('name')] = $(this).val();
				});
				$(this).closest('form').find('.main-filters input.checkbox').each(function (index, element) {
					if ($(this).is(':checked')) {
						filters[$(this).prop('name')] = $(this).val();
					}
				});
			} else {
				url = $(this).closest('.expanded-form').children('a.expanded-form-action').prop('href');
				$(this).closest('.expanded-form').children('input').each(function (index, element) {
					if ($(this).attr('type') == 'hidden') {
						filters[$(this).prop('name')] = $(this).val();
					}
				});
				$(this).closest('.expanded-form').children('.portal-table-wrapper').children('.portal-table').children('table').children('thead').children('tr:not(.header-row)').children('td, th').children('.cell-wrapper').children('.field-filter').children('input.text, select').each(function (index, element) {
					filters[$(this).prop('name')] = $(this).val();
				});
			}
			if (url) {
				url = url.replace('/portal/', '/ajax/portal/');
				var newHistoryUrl = $(this).closest('form').prop('action');
				if (contentArea.attr('id') != 'portal-content') newHistoryUrl = $(this).closest('.expanded-form').children('a.expanded-form-action').prop('href');
				var firstFilter = true;
				for (var filterName in filters) {
					if (firstFilter) {
						newHistoryUrl += '?';
						firstFilter = false;
					} else {
						newHistoryUrl += '&';
					}
					newHistoryUrl += filterName + '=' + filters[filterName];
				}
				if (contentArea.attr('id') == 'portal-content') addToHistory(newHistoryUrl);
				loadPortalContent(contentArea, url, filters);
			}
		//}
	});
	contentAreaFieldFilterCells.children('.clear-field').bind('click', function(e) {
		//if ($(this).closest('.risk-page') <= 0) {
			var id = $(this).attr('id').substr(6);
			$(this).parent().children('#' + id).val('');

			$('.portal-table').css('overflow', '');
			$('#enter-message-background').stop().fadeOut(500);
			enterMessageAlignElement = false;

			var url = $(this).closest('form').prop('action');
			var filters = new Object();
			if (contentArea.attr('id') == 'portal-content') {
				$(this).closest('form').children('input').each(function (index, element) {
					if ($(this).attr('type') == 'hidden') {
						filters[$(this).prop('name')] = $(this).val();
					}
				});
				$(this).closest('form').find('table tr .field-filter input.text, table tr .field-filter select').each(function (index, element) {
					if ($(this).closest('.expanded-area').length == 0) filters[$(this).prop('name')] = $(this).val();
				});
				$(this).closest('form').find('.main-filters select, .main-filters input.date').each(function (index, element) {
					filters[$(this).prop('name')] = $(this).val();
				});
				$(this).closest('form').find('.main-filters input.checkbox').each(function (index, element) {
					if ($(this).is(':checked')) {
						filters[$(this).prop('name')] = $(this).val();
					}
				});
			} else {
				url = $(this).closest('.expanded-form').children('a.expanded-form-action').prop('href');
				$(this).closest('.expanded-form').children('input').each(function (index, element) {
					if ($(this).attr('type') == 'hidden') {
						filters[$(this).prop('name')] = $(this).val();
					}
				});
				$(this).closest('.expanded-form').children('.portal-table-wrapper').children('.portal-table').children('table').children('thead').children('tr:not(.header-row)').children('td, th').children('.cell-wrapper').children('.field-filter').children('input.text, select').each(function (index, element) {
					filters[$(this).prop('name')] = $(this).val();
				});
			}
			if (url) {
				url = url.replace('/portal/', '/ajax/portal/');
				var newHistoryUrl = $(this).closest('form').prop('action');
				if (contentArea.attr('id') != 'portal-content') newHistoryUrl = $(this).closest('.expanded-form').children('a.expanded-form-action').prop('href');
				var firstFilter = true;
				for (var filterName in filters) {
					if (firstFilter) {
						newHistoryUrl += '?';
						firstFilter = false;
					} else {
						newHistoryUrl += '&';
					}
					newHistoryUrl += filterName + '=' + filters[filterName];
				}
				if (contentArea.attr('id') == 'portal-content') addToHistory(newHistoryUrl);
				loadPortalContent(contentArea, url, filters);
			}
		//}
	});
	
	if (contentArea.attr('id') == 'portal-content')
	{
		if (history && history.pushState && !isRiskPage())
		{
			$('#portal-content .pager-bar ul.pager li a, #portal-content .back-button a').unbind('click');
			$('#portal-content .pager-bar ul.pager li a, #portal-content .back-button a').click(function(e) {
				var newHistoryUrl = $(this).prop('href');
				var url = newHistoryUrl.replace('/portal/', '/ajax/portal/');
				addToHistory(newHistoryUrl);
				loadPortalContent(contentArea, url);
				return false;
			});
			/*$('#portal-content .back-button a').click(function(e) {
				history.back();
				return false;
			});*/
		}

		$('#portal-content .main-filters select, #portal-content .main-filters input.date').unbind('change');
		$('#portal-content .main-filters select, #portal-content .main-filters input.date').bind('change', function(e) {
			$('.portal-table').css('overflow', '');
			$('#enter-message-background').stop().fadeOut(500);
			enterMessageAlignElement = false;
			
			if ($(this).prop('id') == 'select-type' && $('#portal-content .main-filters input.date#prompt-date').length > 0)
			{
				if ($(this).val() == 'tomorrow')
				{
					$('#portal-content .main-filters input.date#prompt-date').val(promptDateTomorrow);
				}
				else if ($(this).val() == 'cash')
				{
					$('#portal-content .main-filters input.date#prompt-date').val(promptDateCash);
				}
			}
			
			var url = $(this).closest('form').prop('action').replace('/portal/', '/ajax/portal/');
			var filters = new Object();
			$(this).closest('form').children('input').each(function(index, element) {
				if ($(this).attr('type') == 'hidden')
				{
					filters[$(this).prop('name')] = $(this).val();
				}
			});
			$(this).closest('form').find('table tr .field-filter input.text, table tr .field-filter select').each(function(index, element) {
				if ($(this).closest('.expanded-area').length == 0) filters[$(this).prop('name')] = $(this).val();
			});
			$(this).closest('form').find('.main-filters select, .main-filters input.date').each(function(index, element) {
				filters[$(this).prop('name')] = $(this).val();
			});
			$(this).closest('form').find('.main-filters input.checkbox').each(function(index, element) {
				if ($(this).is(':checked'))
				{
					filters[$(this).prop('name')] = $(this).val();
				}
			});
			var newHistoryUrl = $(this).closest('form').prop('action');
			var firstFilter = true;
			for (var filterName in filters)
			{
				if (firstFilter)
				{
					newHistoryUrl += '?';
					firstFilter = false;
				}
				else
				{
					newHistoryUrl += '&';
				}
				newHistoryUrl += filterName + '=' + filters[filterName];
			}
			if (history && history.pushState)
			{
				addToHistory(newHistoryUrl);
				loadPortalContent(contentArea, url, filters);
			}
			else
			{
				$(this).closest('form').submit();
			}
		});
		$('#portal-content .main-filters input.checkbox').unbind('click');
		$('#portal-content .main-filters input.checkbox').bind('click', function(e) {
			$('.portal-table').css('overflow', '');
			$('#enter-message-background').stop().fadeOut(500);
			enterMessageAlignElement = false;
			
			var url = $(this).closest('form').prop('action').replace('/portal/', '/ajax/portal/');
			var filters = new Object();
			$(this).closest('form').children('input').each(function(index, element) {
				if ($(this).attr('type') == 'hidden')
				{
					filters[$(this).prop('name')] = $(this).val();
				}
			});
			$(this).closest('form').find('table tr .field-filter input.text, table tr .field-filter select').each(function(index, element) {
				if ($(this).closest('.expanded-area').length == 0) filters[$(this).prop('name')] = $(this).val();
			});
			$(this).closest('form').find('.main-filters select, .main-filters input.date').each(function(index, element) {
				filters[$(this).prop('name')] = $(this).val();
			});
			$(this).closest('form').find('.main-filters input.checkbox').each(function(index, element) {
				if ($(this).is(':checked'))
				{
					filters[$(this).prop('name')] = $(this).val();
				}
			});
			var newHistoryUrl = $(this).closest('form').prop('action');
			var firstFilter = true;
			for (var filterName in filters)
			{
				if (firstFilter)
				{
					newHistoryUrl += '?';
					firstFilter = false;
				}
				else
				{
					newHistoryUrl += '&';
				}
				newHistoryUrl += filterName + '=' + filters[filterName];
			}
			if (history && history.pushState)
			{
				addToHistory(newHistoryUrl);
				loadPortalContent(contentArea, url, filters);
			}
			else
			{
				$(this).closest('form').submit();
			}
		});
	}
	
	contentAreaPortalTableWrapper.children('.portal-table-scroll-left, .portal-table-scroll-right').unbind('click mousemove');
	
	contentAreaPortalTableWrapper.children('.portal-table-scroll-left').click(function(e) {
		contentAreaPortalTable.animate({ scrollLeft: contentAreaPortalTable.scrollLeft() - (contentAreaPortalTable.width() / 2) }, 500);
		
		if (contentAreaPortalTable.scrollLeft() <= 5)
		{
			contentAreaPortalTableWrapper.children('.portal-table-scroll-left').fadeOut(200);
		}
		else
		{
			contentAreaPortalTableWrapper.children('.portal-table-scroll-left').fadeIn(200);
		}
		
		if (contentAreaPortalTable.scrollLeft() >= contentAreaTable.width() - contentAreaPortalTable.width() - 5)
		{
			contentAreaPortalTableWrapper.children('.portal-table-scroll-right').fadeOut(200);
		}
		else
		{
			contentAreaPortalTableWrapper.children('.portal-table-scroll-right').fadeIn(200);
		}
	});
	contentAreaPortalTableWrapper.children('.portal-table-scroll-right').click(function(e) {
		contentAreaPortalTable.animate({ scrollLeft: contentAreaPortalTable.scrollLeft() + (contentAreaPortalTable.width() / 2) }, 500);
		
		if (contentAreaPortalTable.scrollLeft() <= 5)
		{
			contentAreaPortalTableWrapper.children('.portal-table-scroll-left').fadeOut(200);
		}
		else
		{
			contentAreaPortalTableWrapper.children('.portal-table-scroll-left').fadeIn(200);
		}
		
		if (contentAreaPortalTable.scrollLeft() >= contentAreaTable.width() - contentAreaPortalTable.width() - 5)
		{
			contentAreaPortalTableWrapper.children('.portal-table-scroll-right').fadeOut(200);
		}
		else
		{
			contentAreaPortalTableWrapper.children('.portal-table-scroll-right').fadeIn(200);
		}
	});
	contentAreaPortalTableWrapper.children('.portal-table-scroll-left, .portal-table-scroll-right').mousemove(function(e) {
		var newTop = e.pageY - $(this).offset().top - ($(this).children('.scroll-arrow').height() / 2);
		if (newTop > $(this).height() - $(this).children('.scroll-arrow').height()) newTop = $(this).height() - $(this).children('.scroll-arrow').height();
		if (newTop < 0) newTop = 0;
		$(this).children('.scroll-arrow').css('top', newTop);
	});
	
	setTimeout(function() {
		if (contentAreaPortalTable.scrollLeft() <= 5)
		{
			contentAreaPortalTableWrapper.children('.portal-table-scroll-left').hide();
		}
		else
		{
			contentAreaPortalTableWrapper.children('.portal-table-scroll-left').show();
		}
		
		if (contentAreaPortalTable.scrollLeft() >= contentAreaTable.width() - contentAreaPortalTable.width() - 5)
		{
			contentAreaPortalTableWrapper.children('.portal-table-scroll-right').hide();
		}
		else
		{
			contentAreaPortalTableWrapper.children('.portal-table-scroll-right').show();
		}
	}, 1);
	
	contentAreaPortalTable.unbind('scroll');
	contentAreaPortalTable.scroll(function() {
		if (contentAreaPortalTable.scrollLeft() <= 5)
		{
			contentAreaPortalTableWrapper.children('.portal-table-scroll-left').fadeOut(200);
		}
		else
		{
			contentAreaPortalTableWrapper.children('.portal-table-scroll-left').fadeIn(200);
		}
		
		if (contentAreaPortalTable.scrollLeft() >= contentAreaTable.width() - contentAreaPortalTable.width() - 5)
		{
			contentAreaPortalTableWrapper.children('.portal-table-scroll-right').fadeOut(200);
		}
		else
		{
			contentAreaPortalTableWrapper.children('.portal-table-scroll-right').fadeIn(200);
		}
	});
}
function checkFieldFilterValues(contentArea, e)
{
	if (!contentArea) contentArea = $('#portal-content');
	var matched = true;
	contentArea.children('.expanded-form, form').children('.portal-table-wrapper').children('.portal-table').children('table').children('thead').children('tr:not(.header-row)').children('td, th').children('.cell-wrapper').children('.field-filter').children('input.text, select').each(function(index, element) {
		if (originalFieldFilters[$(this).prop('id')] !== $(this).val())
		{
			matched = false;
			enterMessageAlignElement = $(this).closest('table').children('tbody');
			return false;
		}
	});
	
	if (matched)
	{
		$('.portal-table').css('overflow', '');
		$('#enter-message-background').stop().fadeOut(500);
		enterMessageAlignElement = false;
	}
	else
	{
		$('#enter-message-background').css({ top: '', left: '', width: '', height: '' });
		alignEnterMessage(contentArea);
		$('#enter-message-background').fadeIn(500);
	}
}
function alignEnterMessage(contentArea)
{
	if (!contentArea) contentArea = $('#portal-content');
	if (enterMessageAlignElement)
	{
		var pos = enterMessageAlignElement.offset();
		if (contentArea.attr('id') == 'portal-content')
		{
			$('#enter-message-background').css({ top: pos.top, left: pos.left, width: enterMessageAlignElement.width(), height: enterMessageAlignElement.height() });
		}
		else
		{
			$('.portal-table').css('overflow', '');
			enterMessageAlignElement.closest('.portal-table').css('overflow', 'hidden');
			enterMessageAlignElement.closest('.portal-table').scrollTop(0);
			pos = enterMessageAlignElement.offset();
			if (enterMessageAlignElement.closest('.expanded-area-content').length > 0) {
				$('#enter-message-background').css({
					top: pos.top,
					left: enterMessageAlignElement.closest('.expanded-area-content').offset().left,
					width: enterMessageAlignElement.closest('.expanded-area-content').width(),
					height: enterMessageAlignElement.closest('.expanded-area-content').height() - enterMessageAlignElement.closest('table').children('thead').height()
				});
			} else {
				$('#enter-message-background').css({
					top: pos.top,
					left: enterMessageAlignElement.closest('.portal-table-wrapper').offset().left,
					width: enterMessageAlignElement.closest('.portal-table-wrapper').width(),
					height: enterMessageAlignElement.closest('.portal-table-wrapper').height() - enterMessageAlignElement.closest('table').children('thead').height()
				});
			}
		}
	}
}
$(window).resize(function(e) {
	$('.expanded-area').children('td').children('div').children('.expanded-area-content').each(function(index, element) {
		scaleAllExpandedAreas(true);
	});
	alignEnterMessage();
	
	$('.portal-table-wrapper').each(function(index, element) {
		var contentAreaPortalTable = $(this).children('.portal-table');
		var contentAreaTable = contentAreaPortalTable.children('table');
		if (contentAreaPortalTable.scrollLeft() <= 5)
		{
			$(this).children('.portal-table-scroll-left').fadeOut(200);
		}
		else
		{
			$(this).children('.portal-table-scroll-left').fadeIn(200);
		}
		
		if (contentAreaPortalTable.scrollLeft() >= contentAreaTable.width() - contentAreaPortalTable.width() - 5)
		{
			$(this).children('.portal-table-scroll-right').fadeOut(200);
		}
		else
		{
			$(this).children('.portal-table-scroll-right').fadeIn(200);
		}
	});
});

var portalContentCache = {};
var portalContentAjaxLoading = false;
function loadPortalContent(contentArea, url, filters, linkToRestore, noScroll, complete)
{
	var body = $('body');
	if (body.hasClass('show-left-column')) {
		body.removeClass('show-left-column');
	}
	if (!contentArea) contentArea = $('#portal-content');
	contentArea.find('.loading-message-background').fadeIn(500);
	if (!filters) filters = new Object();
	if (contentArea.parent().parent().attr('id') == 'commodity-popup')
	{
		if (commodityAjaxLoading) commodityAjaxLoading.abort();
	}
	else
	{
		commodityPopupAlignElement = false;
		positionCommodityPopup();
		if (portalContentAjaxLoading) portalContentAjaxLoading.abort();
	}
	var ajaxLoading = loadPortalContentInt(contentArea, url, filters, linkToRestore, noScroll, function(content) {
		contentArea.fadeOut(200, function() {
			if (linkToRestore) linkToRestore.attr('href', url.replace('/ajax', ''));
			contentArea.html(content);
			if (typeof setupEditTextAreas == 'function') setupEditTextAreas();
			if (contentArea.parent().parent().attr('id') == 'commodity-popup')
			{
				contentArea.show();
				positionCommodityPopup();
				contentArea.hide();
				contentArea.fadeIn(200);
			}
			else
			{
				contentArea.fadeIn(200);
				contentArea.height('');
				initFieldFilters(contentArea);
				initNotifyCheckboxes(contentArea);
				initRowExpand(contentArea);
				scaleAllExpandedAreas();
				initCommodityCodesPopup(contentArea);
				contentArea.find('.main-error').delay(7000).fadeOut(500, function() {
					scaleAllExpandedAreas();
				});
				setTimeout(scaleAllExpandedAreas, 200);
				if (!noScroll)
				{
					if (contentArea.attr('id') == 'portal-content')
					{
						$("html, body").animate({ scrollTop: $('#nav').offset().top }, 500);
					}
					else
					{
						//scrollToClickedRow(tableRow);
						setTimeout(function() {
							scrollToClickedRow(tableRow);
						}, 500);
					}
				}
			}

			if (complete) {
				complete(content);
			}
		});
	});
	if (contentArea.parent().parent().attr('id') == 'commodity-popup')
	{
		commodityAjaxLoading = ajaxLoading;
	}
	else
	{
		portalContentAjaxLoading = ajaxLoading;
		if (!noScroll)
		{
			if (contentArea.attr('id') == 'portal-content')
			{
				$("html, body").animate({ scrollTop: $('#nav').offset().top }, 500);
			}
			else
			{
                var tableRow = contentArea.parent().parent().parent().prev('tr');
                scrollToClickedRow(tableRow);
			}
		}
	}
}

function loadPortalContentInt(contentArea, url, filters, linkToRestore, noScroll, complete)
{
	var cacheId = url + JSON.stringify(filters);
	var loadedFromCache = false;
	if (portalContentCache.hasOwnProperty(cacheId) && portalContentCache[cacheId]) {
		loadedFromCache = true;
		if (complete) {
			complete(portalContentCache[cacheId]);
		}
		return null;
	}
	return $.ajax({
		type: "GET",
		url: url,
		data: filters
	}).always(function(content) {
		if (typeof(content) == 'string') {
			portalContentCache[cacheId] = content;
		}
		if (!loadedFromCache) {
			if (complete) {
				complete(content);
			}
		}
	});
}

function scrollToClickedRow(tableRow) {
	if (!isRiskRootPage()) {
		var outerTableRow = tableRow;
		var scrollArea = tableRow.closest('tr.expanded-area .expanded-area-content > .portal-table-wrapper > .portal-table');
		while (outerTableRow.closest('tr.expanded-area .expanded-area-content').length > 0) {
			scrollArea = outerTableRow.closest('tr.expanded-area .expanded-area-content > .portal-table-wrapper > .portal-table');
			outerTableRow = outerTableRow.closest('tr.expanded-area .expanded-area-content').parent().parent().parent().prev('tr');
		}
		if (scrollArea.length > 0) {
			var oldScrollPos = scrollArea.scrollTop();
			scrollArea.scrollTop(0);
			var scrollTopPos = tableRow.offset().top - scrollArea.offset().top;
			scrollArea.scrollTop(oldScrollPos);
			scrollArea.stop().animate({scrollTop: scrollTopPos}, 500);
		}
		var topPos = outerTableRow.offset().top - outerTableRow.height();
		$("html, body").stop().animate({scrollTop: topPos}, 500);
	}
}

function initRowExpand(contentArea)
{
	if (!contentArea) contentArea = $('#portal-content');
	contentArea.find('table tr .expand-icon').each(function(index, element) {
		var expandIconParent = $(this).parent();
		if (expandIconParent.find('.expand-link').length > 0)
		{
			var tableDataId = getPortalTableId(expandIconParent.closest('table'));
			portalExpandedRows[tableDataId] = [];
			$(this).removeClass('hidden');
			expandIconParent.find('td, th').css('cursor', 'pointer');
			expandIconParent.find('.expand-link').unbind('click');
			expandIconParent.find('.expand-link').click(function(e) {
				clickExpandable($(this).closest('tr'));
				return false;
			});
			expandIconParent.find('td, th').unbind('click');
			expandIconParent.find('td, th').click(function(e) {
				clickExpandable($(this).parent());
				return false;
			});
		}
	});
	contentArea.find('table tr .full-row-link').each(function(index, element) {
		var newHistoryUrl = $(this).prop('href');
		var linkTarget = $(this).prop('target');
		var url = newHistoryUrl.replace('/portal/', '/ajax/portal/');
		var closestTrCells = $(this).closest('tr').find('td, th');
		closestTrCells.css('cursor', 'pointer');
		closestTrCells.unbind('click');
		closestTrCells.click(function(e) {
			if (linkTarget == "_blank")
			{
				window.open(newHistoryUrl, '_blank');
			}
			else
			{
				addToHistory(newHistoryUrl);
				loadPortalContent(false, url);
			}
			
			return false;
		});
	});
	
	if (history && history.pushState)
	{
		if (isRiskPage()) {
			//contentArea.children('.full-size-link').prop('target', '_blank');
		} else {
			contentArea.children('.full-size-link').click(function (e) {
				var newHistoryUrl = $(this).prop('href');
				var url = newHistoryUrl.replace('/portal/', '/ajax/portal/');
				addToHistory(newHistoryUrl);
				loadPortalContent(false, url);
				return false;
			});
		}
	}
}

function isRiskPage() {
	var matchUrl = siteDirectory + '/portal/risk';
	return window.location.pathname.substr(0, matchUrl.length) === matchUrl;
}

function isRiskRootPage() {
	var matchUrl = siteDirectory + '/portal/risk';
	return window.location.pathname === matchUrl ||
		window.location.pathname === matchUrl + '/';
}

function clickExpandable(tableRow)
{
	var expandUrl = tableRow.find('.expand-link').prop('href');
	var url = expandUrl.replace('/portal/', '/ajax/portal/tables/');
	var tableDataId = getPortalTableId(tableRow.closest('table'));

	if (tableRow.hasClass('expanded'))
	{
		tableRow.removeClass('expanded');
		var portalExpandedRowsIndex = portalExpandedRows[tableDataId].indexOf(url);
		if (portalExpandedRowsIndex >= 0) {
			portalExpandedRows[tableDataId].splice(portalExpandedRowsIndex, 1);
		}
		tableRow.next('.expanded-area').children('td').children('div').stop().animate({ height: 0 }, 300, function() {
			tableRow.next('.expanded-area').remove();
			scaleAllExpandedAreas();
			checkFieldFilterValues();
		});
		tableRow.trigger('collapsed');
	}
	else
	{
        var expandedRow = tableRow.closest('table').children('tbody').children('tr.expanded');
        if (expandedRow.length > 0) {
            var doneAfterProcess = false;
            expandedRow.next('.expanded-area').children('td').children('div').stop().animate({height: 0}, 300, function () {
                if (!doneAfterProcess) {
                    doneAfterProcess = true;
					var expandedUrl = expandedRow.find('.expand-link').prop('href').replace('/portal/', '/ajax/portal/tables/');
                    expandedRow.next('.expanded-area').remove();
                    expandedRow.removeClass('expanded');
					expandedRow.trigger('collapsed');
					var portalExpandedRowsIndex = portalExpandedRows[tableDataId].indexOf(expandedUrl);
					if (portalExpandedRowsIndex >= 0) {
						portalExpandedRows[tableDataId].splice(portalExpandedRowsIndex, 1);
					}
                    scaleAllExpandedAreas();
                    checkFieldFilterValues();
                    expandRow(tableRow, url);
                }
            });
        } else {
            expandRow(tableRow, url);
        }
	}
}

var portalExpandedRows = [];
var portalTablesDataId = 0;

function getPortalTableId(table) {
	var tableDataId = table.attr('data-portal_table_id');
	if (!tableDataId) {
		portalTablesDataId++;
		tableDataId = 'portal_table_' + portalTablesDataId;
		table.attr('data-portal_table_id', tableDataId);
	}

	return tableDataId;
}

function expandRow(tableRow, url, complete) {
    tableRow.closest('table').children('tbody').children('tr').each(function (index, element) {
        $(this).next('.expanded-area').remove();
        checkFieldFilterValues();
    });
    tableRow.addClass('expanded');
	tableRow.trigger('expanded');
    var tableDataId = getPortalTableId(tableRow.closest('table'));
    if (!portalExpandedRows[tableDataId]) {
		portalExpandedRows[tableDataId] = [];
	}
	if (portalExpandedRows[tableDataId].indexOf(url) < 0) {
		portalExpandedRows[tableDataId].push(url);
	}
    var numColumns = 0;
    tableRow.children('td, th').each(function (index, element) {
        if ($(this).attr('colspan')) {
            numColumns += parseInt($(this).attr('colspan'));
        }
        else {
            numColumns++;
        }
    });

    tableRow.after('<tr class="expanded-area"><td colspan="' + numColumns + '"><div><div class="expanded-area-content" style="height: 5em;"><div class="loading-message-background"><div class="loading-message"><div class="box loading-message-box">Loading...</div></div></div></div></div></td></tr>');
    tableRow.next('.expanded-area').children('td').children('div').children('.expanded-area-content').show();
    scaleAllExpandedAreas();
    loadPortalContent(tableRow.next('.expanded-area').children('td').children('div').children('.expanded-area-content'), url, false, false, false, complete);
}

function scaleAllExpandedAreas(noAnimation)
{
	var expandedArea = getDeepestExpandedArea($('#portal-content'), noAnimation);

	scaleExpandedArea(expandedArea, noAnimation);
	
	$('.portal-table-wrapper').each(function(index, element) {
		var contentAreaPortalTable = $(this).children('.portal-table');
		var contentAreaTable = contentAreaPortalTable.children('table');
		if (contentAreaPortalTable.scrollLeft() <= 5)
		{
			$(this).children('.portal-table-scroll-left').fadeOut(200);
		}
		else
		{
			$(this).children('.portal-table-scroll-left').fadeIn(200);
		}
		
		if (contentAreaPortalTable.scrollLeft() >= contentAreaTable.width() - contentAreaPortalTable.width() - 5)
		{
			$(this).children('.portal-table-scroll-right').fadeOut(200);
		}
		else
		{
			$(this).children('.portal-table-scroll-right').fadeIn(200);
		}
	});
}

function getDeepestExpandedArea(expandedArea, noAnimation)
{
	var returnArea = expandedArea;
	if (expandedArea.find('.expanded-area-content').length > 0)
	{
		returnArea = getDeepestExpandedArea(expandedArea.find('.expanded-area-content').first(), noAnimation);
	}
	
	return returnArea;
}

function scaleExpandedArea(expandedArea, noAnimation, maximumHeight)
{
	if (expandedArea.attr('id') != 'portal-content')
	{
		if (!maximumHeight) maximumHeight = 'dont-set';
		
		var portalExpandedTable = expandedArea.children('form, .expanded-form').children('.portal-table-wrapper').children('.portal-table');
		if (portalExpandedTable.length == 0) portalExpandedTable = expandedArea.children('.portal-table-wrapper').children('form, .expanded-form');
		
		if (maximumHeight != 'dont-set') portalExpandedTable.css({ maxHeight: maximumHeight });
		
		var oldHeight = expandedArea.parent().height();
		var newHeight = expandedArea.height();
		
		expandedArea.parent().css({ height: newHeight, overflow: '' });
		if (expandedArea.parents('.expanded-area-content').length > 0)
		{
			expandedArea.parents('.expanded-area-content').each(function(index, element) {
				//scaleExpandedArea($(this), noAnimation, 'none');
				$(this).children('form, .expanded-form').children('.portal-table-wrapper').children('.portal-table').css({ maxHeight: 'none' });
				$(this).parent().css({ height: 'auto', overflow: '' });
			});
		}
		expandedArea.parent().css({ height: oldHeight, overflow: '' });

		var animSpeed = noAnimation ? 0 : 500;

		expandedArea.parent().stop(true).animate({ height: newHeight }, animSpeed, function() {
			$(this).css('overflow', '');
		});
		expandedArea.parent().css({ overflow: '' });
	}
}

function initNotifyCheckboxes(contentArea)
{
	if (!contentArea) contentArea = $('#portal-content');
	
	checkAllNotifyCheckboxes(contentArea, true);
	
	var contentAreaTable = contentArea.children('.expanded-form, form').children('.portal-table-wrapper').children('.portal-table').children('table');
	
	contentAreaTable.children('thead').children('tr:not(.header-row)').children('.notify-checkbox').children('.cell-wrapper').children('.field-filter').children('input.checkbox').unbind('click');
	contentAreaTable.children('thead').children('tr:not(.header-row)').children('.notify-checkbox').children('.cell-wrapper').children('.field-filter').children('input.checkbox').click(function(e) {
		$(this).closest('table').children('tbody').children('tr').children('.notify-checkbox').children('.cell-wrapper').children('input.checkbox:enabled').prop('checked', false);
		var mainCheckboxId = $(this).prop('id');
		var mainCheckboxIdShort = mainCheckboxId.replace('check-all', 'check');
		var otherCheckbox = false;
		if ($(this).closest('tr').children('.notify-checkbox').children('.cell-wrapper').children('input.checkbox[name="' + $(this).prop('name') + '"]').length > 0)
		{
			$(this).closest('tr').children('.notify-checkbox').children('.cell-wrapper').children('input.checkbox[name="' + $(this).prop('name') + '"]').each(function(index, element) {
				if (mainCheckboxId != $(this).prop('id')) otherCheckbox = $(this);
			});
		}
		if (otherCheckbox != false && otherCheckbox.is(':checked') && $(this).is(':checked'))
		{
			otherCheckbox.prop('checked', false);
		}
		
		if ($(this).is(':checked'))
		{
			$(this).closest('table').children('tbody').children('tr').children('.notify-checkbox').children('.cell-wrapper').children('input.checkbox').each(function(index, element) {
				if (!$(this).is(':disabled') && $(this).prop('id').substring(0, mainCheckboxIdShort.length) == mainCheckboxIdShort) $(this).prop('checked', true);
			});
		}
		else
		{
			$(this).closest('table').children('tbody').children('tr').children('.notify-checkbox').children('.cell-wrapper').children('input.checkbox').each(function(index, element) {
				if (!$(this).is(':disabled') && $(this).prop('id').substring(0, mainCheckboxIdShort.length) == mainCheckboxIdShort) $(this).prop('checked', false);
			});
		}
		checkAllNotifyCheckboxes(contentArea);
	});
	contentAreaTable.children('tbody').children('tr').children('td, th').children('.cell-wrapper').children('input.text').unbind('click');
	contentAreaTable.children('tbody').children('tr').children('td, th').children('.cell-wrapper').children('input.text').click(function(e) {
		stopPropagation(e);
	});
	contentAreaTable.children('tbody').children('tr').children('.notify-checkbox').children('.cell-wrapper').children('input.checkbox').unbind('click');
	contentAreaTable.children('tbody').children('tr').children('.notify-checkbox').children('.cell-wrapper').children('input.checkbox').click(function(e) {
		stopPropagation(e);
		var currentCheckboxId = $(this).prop('id');
		var otherCheckbox = false;
		if (contentAreaTable.children('tbody').children('tr').children('.notify-checkbox').children('.cell-wrapper').children('input.checkbox[name="' + $(this).prop('name') + '"]').length > 0)
		{
			contentAreaTable.children('tbody').children('tr').children('.notify-checkbox').children('.cell-wrapper').children('input.checkbox[name="' + $(this).prop('name') + '"]').each(function(index, element) {
				if (currentCheckboxId != $(this).prop('id')) otherCheckbox = $(this);
			});
		}
		if (otherCheckbox != false && otherCheckbox.is(':checked') && $(this).is(':checked'))
		{
			otherCheckbox.prop('checked', false);
		}
		
		if ($(this).hasClass('reason'))
		{
			if ($(this).is(':checked'))
			{
				$(this).closest('tr').find('.reason-text').fadeIn(200);
			}
			else
			{
				$(this).closest('tr').find('.reason-text').fadeOut(200);
			}
		}
		
		checkAllNotifyCheckboxes(contentArea);
	});
	contentAreaTable.children('tbody').children('tr').children('.notify-checkbox').children('.cell-wrapper').children('a.reset-checkbox').unbind('click');
	contentAreaTable.children('tbody').children('tr').children('.notify-checkbox').children('.cell-wrapper').children('a.reset-checkbox').click(function(e) {
		stopPropagation(e);
		if (confirm("Are you sure you want to reset this checkbox?"))
		{
			var url = $(this).prop('href').replace('/portal/', '/ajax/portal/');
			loadPortalContent(contentArea, url);
		}
		return false;
	});
	
	contentAreaTable.children('tfoot').children('tr').children('.notify-checkbox').children('.cell-wrapper').children('button').unbind('click');
	contentAreaTable.children('tfoot').children('tr').children('.notify-checkbox').children('.cell-wrapper').children('button').click(function() {
		var enteredReasons = true;
		contentAreaTable.children('tbody, thead, tfoot').children('tr').children('td, th').children('.cell-wrapper').children('input.text.reason-text').each(function(index, element) {
			if ($(this).is(':visible') && $(this).is(':enabled') && ($(this).val()) == "")
			{
				enteredReasons = false;
				return false;
			}
		});
		if (enteredReasons)
		{
			initNotifyEmailPopup(contentArea, $(this));
			$('#send-notify-email-background').fadeIn(200);
		}
		else
		{
			alert('You must enter a reason');
		}
		return false;
	});
	
	contentArea.find('#portal-action-request-excess-funds a').unbind('click');
	contentArea.find('#portal-action-request-excess-funds a').click(function() {
		initRequestExcessFundsEmailPopup(contentArea, $(this));
		$('#send-excess-funds-email-background').fadeIn(200);
		return false;
	});
}

function initNotifyEmailPopup(contentArea, notifyButton)
{
	if (!contentArea) contentArea = $('#portal-content');
	
	$('#send-notify-email-cancel').unbind('click');
	$('#send-notify-email-cancel').click(function() {
		$('#send-notify-email-background').fadeOut(200);
		return false;
	});
	
	$('#send-notify-email-submit').unbind('click');
	$('#send-notify-email-submit').click(function() {
		var url = notifyButton.closest('form').prop('action').replace('/portal/', '/ajax/portal/');
		var filters = new Object();
		filters['send-notify-email-message'] = $('#send-notify-email-message').val();
		if (contentArea.attr('id') == 'portal-content')
		{
			notifyButton.closest('form').children('input').each(function(index, element) {
				if ($(this).attr('type') == 'hidden')
				{
					filters[$(this).prop('name')] = $(this).val();
				}
			});
			notifyButton.closest('form').find('table tr .field-filter input.text, table tr .field-filter select').each(function(index, element) {
				if ($(this).closest('.expanded-area').length == 0) filters[$(this).prop('name')] = $(this).val();
			});
			notifyButton.closest('form').find('.main-filters select, .main-filters input.date').each(function(index, element) {
				filters[$(this).prop('name')] = $(this).val();
			});
			notifyButton.closest('form').find('.main-filters input.checkbox').each(function(index, element) {
				if ($(this).is(':checked'))
				{
					filters[$(this).prop('name')] = $(this).val();
				}
			});
			notifyButton.closest('form').find('table tr .notify-checkbox input.checkbox').each(function(index, element) {
				if ($(this).closest('.expanded-area').length == 0 && $(this).is(':checked') && !$(this).is(':disabled')) filters[$(this).prop('name')] = $(this).val();
			});
			notifyButton.closest('form').find('table tr input.text.reason-text').each(function(index, element) {
				if ($(this).closest('.expanded-area').length == 0 && $(this).is(':visible') && !$(this).is(':disabled')) filters[$(this).prop('name')] = $(this).val();
			});
		}
		else
		{
			url = notifyButton.closest('.expanded-form').children('a.expanded-form-action').prop('href').replace('/portal/', '/ajax/portal/');
			notifyButton.closest('.expanded-form').children('input').each(function(index, element) {
				if ($(this).attr('type') == 'hidden')
				{
					filters[$(this).prop('name')] = $(this).val();
				}
			});
			notifyButton.closest('.expanded-form').children('.portal-table-wrapper').children('.portal-table').children('table').children('thead').children('tr:not(.header-row)').children('td, th').children('.cell-wrapper').children('.field-filter').children('input.text, select').each(function(index, element) {
				filters[$(this).prop('name')] = $(this).val();
			});
			notifyButton.closest('.expanded-form').children('.portal-table-wrapper').children('.portal-table').children('table').children('tbody').children('tr').children('.notify-checkbox').children('.cell-wrapper').children('input.checkbox').each(function(index, element) {
				if ($(this).is(':checked') && !$(this).is(':disabled')) filters[$(this).prop('name')] = $(this).val();
			});
			notifyButton.closest('.expanded-form').children('.portal-table-wrapper').children('.portal-table').children('table').children('tbody').children('tr').children('td, th').children('.cell-wrapper').children('input.text.reason-text').each(function(index, element) {
				if ($(this).is(':visible') && !$(this).is(':disabled')) filters[$(this).prop('name')] = $(this).val();
			});
		}
		/*var newHistoryUrl = $(this).closest('form').prop('action');
		if (contentArea.attr('id') != 'portal-content') newHistoryUrl = $(this).closest('.expanded-form').children('a.expanded-form-action').prop('href');
		var firstFilter = true;
		for (var filterName in filters)
		{
			if (firstFilter)
			{
				newHistoryUrl += '?';
				firstFilter = false;
			}
			else
			{
				newHistoryUrl += '&';
			}
			newHistoryUrl += filterName + '=' + filters[filterName];
		}*/
		loadPortalContent(contentArea, url, filters);
		$('#send-notify-email-background').fadeOut(200, function() {
			$('#send-notify-email-message').val('');
		});
		return false;
	});
}

function initRequestExcessFundsEmailPopup(contentArea, notifyButton)
{
	if (!contentArea) contentArea = $('#portal-content');
	
	$('#send-excess-funds-email-cancel').unbind('click');
	$('#send-excess-funds-email-cancel').click(function() {
		$('#send-excess-funds-email-background').fadeOut(200);
		return false;
	});
	
	$('#send-excess-funds-email-submit').unbind('click');
	$('#send-excess-funds-email-submit').click(function() {
		var url = notifyButton.prop('href').replace('/portal/', '/ajax/portal/');
		var filters = new Object();
		filters['send-excess-funds-email-message'] = $('#send-excess-funds-email-message').val();
		if (contentArea.attr('id') != 'portal-content') url = notifyButton.closest('.expanded-form').children('a.expanded-form-action').prop('href').replace('/portal/', '/ajax/portal/');
		/*var newHistoryUrl = $(this).closest('form').prop('action');
		if (contentArea.attr('id') != 'portal-content') newHistoryUrl = $(this).closest('.expanded-form').children('a.expanded-form-action').prop('href');
		var firstFilter = true;
		for (var filterName in filters)
		{
			if (firstFilter)
			{
				newHistoryUrl += '?';
				firstFilter = false;
			}
			else
			{
				newHistoryUrl += '&';
			}
			newHistoryUrl += filterName + '=' + filters[filterName];
		}*/
		loadPortalContent(contentArea, url, filters);
		$('#send-excess-funds-email-background').fadeOut(200, function() {
			$('#send-excess-funds-email-message').val('');
		});
		return false;
	});
}

function checkAllNotifyCheckboxes(contentArea, noAnimation)
{
	if (!contentArea) contentArea = $('#portal-content');
	
	var noReasonsChecked = true;
	var noneChecked = true;
	
	contentArea.children('.expanded-form, form').children('.portal-table-wrapper').children('.portal-table').children('table').children('thead').children('tr:not(.header-row)').children('.notify-checkbox').children('.cell-wrapper').children('.field-filter').children('input.checkbox').each(function(index, element) {
		var mainCheckboxId = $(this).prop('id');
		var mainCheckboxIdShort = mainCheckboxId.replace('check-all', 'check');
		var allChecked = true;
		contentArea.children('.expanded-form, form').children('.portal-table-wrapper').children('.portal-table').children('table').children('tbody').children('tr').children('.notify-checkbox').children('.cell-wrapper').children('input.checkbox').each(function(index, element) {
			var currentCheckboxId = $(this).prop('id');
			var currentCheckboxName = $(this).prop('name');
			if (allChecked && !$(this).is(':checked') && !$(this).is(':disabled') && currentCheckboxId.substring(0, mainCheckboxIdShort.length) == mainCheckboxIdShort)
			{
				allChecked = false;
			}
			
			var otherCheckbox = false;
			if ($(this).closest('tr').children('.notify-checkbox').children('.cell-wrapper').children('input.checkbox[name="' + currentCheckboxName + '"]').length > 0)
			{
				$(this).closest('tr').children('.notify-checkbox').children('.cell-wrapper').children('input.checkbox[name="' + currentCheckboxName + '"]').each(function(index, element) {
					if (currentCheckboxId != $(this).prop('id')) otherCheckbox = $(this);
				});
			}
			if (otherCheckbox != false && otherCheckbox.is(':checked') && $(this).is(':checked'))
			{
				otherCheckbox.prop('checked', false);
			}
			
			var showReasonBox = false;
			if ($(this).hasClass('reason'))
			{
				if ($(this).is(':checked'))
				{
					noReasonsChecked = false;
					showReasonBox = true;
				}
			}
			
			if (otherCheckbox != false && otherCheckbox.hasClass('reason'))
			{
				if (otherCheckbox.is(':checked'))
				{
					showReasonBox = true;
				}
			}
			
			if (showReasonBox)
			{
				$(this).closest('tr').find('.reason-text').show();
			}
			else
			{
				$(this).closest('tr').find('.reason-text').hide();
			}
			
			if (noneChecked && $(this).is(':checked') && !$(this).is(':disabled'))
			{
				noneChecked = false;
			}
		});
		
		if (allChecked)
		{
			$(this).prop('checked', true);
		}
		else
		{
			$(this).prop('checked', false);
		}
	});
	
	if (noReasonsChecked)
	{
		contentArea.children('.expanded-form, form').children('.portal-table-wrapper').children('.portal-table').children('table').children('tbody, thead, tfoot').children('tr').children('.reason-text-column').css('display', 'none');
	}
	else
	{
		contentArea.children('.expanded-form, form').children('.portal-table-wrapper').children('.portal-table').children('table').children('tbody, thead, tfoot').children('tr').children('.reason-text-column').css('display', '');
	}
	
	var tFoot = contentArea.children('.expanded-form, form').children('.portal-table-wrapper').children('.portal-table').children('table').children('tfoot');
	if (noneChecked)
	{
		var origPadding = contentArea.children('.expanded-form, form').css('padding-bottom');
		contentArea.children('.expanded-form, form').css('padding-bottom', 0);
		scaleAllExpandedAreas();
		alignEnterMessage(contentArea);
		
		if (noAnimation)
		{
			tFoot.hide();
		}
		else
		{
			contentArea.children('.expanded-form, form').css('padding-bottom', origPadding);
			tFoot.fadeOut(200);
			contentArea.children('.expanded-form, form').animate({ paddingBottom: 0 }, 200);
		}
	}
	else
	{
		var origPadding = contentArea.children('.expanded-form, form').css('padding-bottom');
		contentArea.children('.expanded-form, form').css('padding-bottom', tFoot.height());
		scaleAllExpandedAreas();
		alignEnterMessage(contentArea);
		
		if (noAnimation)
		{
			tFoot.show();
		}
		else
		{
			contentArea.children('.expanded-form, form').css('padding-bottom', origPadding);
			tFoot.fadeIn(200);
			contentArea.children('.expanded-form, form').animate({ paddingBottom: tFoot.height() }, 200);
		}
	}
}

var commodityPopupAlignElement = false;
var commodityPopupFadeOutTimeout = false;
var originalCommodityPopupContent = false;
var commodityAjaxLoading = false;
function initCommodityCodesPopup(contentArea)
{
	if (!contentArea) contentArea = $('#portal-content');
	
	contentArea.find('.commodity-code-mouseover').unbind('click mouseover mouseout');
	contentArea.find('.commodity-code-mouseover').click(function(e) {
		stopPropagation(e);
	});
	contentArea.find('.commodity-code-mouseover').mouseover(function(e) {
		if (!originalCommodityPopupContent) originalCommodityPopupContent = $('#commodity-popup .commodity-popup-box .popup-content').html();
		clearTimeout(commodityPopupFadeOutTimeout);
		var url = siteDirectory + '/ajax/portal/commodity-details';
		var filters = new Object();
		var commodityCodeMouseOver = $(this);
		var commodityId = commodityCodeMouseOver.attr('id').replace("commodity-mouseover-", "");
		commodityId = commodityId.split("_");
		var exchangeCode = commodityId[0];
		var commodityCode = commodityId[1];
		filters['ExchangeCode'] = exchangeCode;
		filters['CommodityCode'] = commodityCode;
		commodityPopupFadeOutTimeout = setTimeout(function() {
			if (!commodityPopupAlignElement || commodityPopupAlignElement.attr('id') != commodityCodeMouseOver.attr('id')) loadPortalContent($('#commodity-popup .commodity-popup-box .popup-content'), url, filters);
			if (!commodityPopupAlignElement) $('#commodity-popup .commodity-popup-box .popup-content .loading-message-background').fadeIn(0);
			commodityPopupAlignElement = commodityCodeMouseOver;
			positionCommodityPopup();
		}, 500);
	});
	contentArea.find('.commodity-code-mouseover').mouseout(function(e) {
		clearTimeout(commodityPopupFadeOutTimeout);
		commodityPopupFadeOutTimeout = setTimeout(function() {
			commodityPopupAlignElement = false;
			positionCommodityPopup();
		}, 2000);
	});
	
	$('#commodity-popup .commodity-popup-box').unbind('click mouseover mouseout');
	$('#commodity-popup .commodity-popup-box').click(function(e) {
		stopPropagation(e);
	});
	$('#commodity-popup .commodity-popup-box').mouseover(function(e) {
		clearTimeout(commodityPopupFadeOutTimeout);
	});
	$('#commodity-popup .commodity-popup-box').mouseout(function(e) {
		commodityPopupFadeOutTimeout = setTimeout(function() {
			commodityPopupAlignElement = false;
			positionCommodityPopup();
		}, 2000);
	});
}

function positionCommodityPopup(noAnimation)
{
	if (commodityPopupAlignElement)
	{
		var commodityId = commodityPopupAlignElement.attr('id').replace("commodity-mouseover-", "");
		commodityId = commodityId.split("_");
		var exchangeCode = commodityId[0];
		var commodityCode = commodityId[1];
		$('#commodity-popup .popup-title .commodity-title-code').text(exchangeCode + ', ' + commodityCode);
		var pos = commodityPopupAlignElement.offset();
		var newRight = $(window).width() - pos.left;
		var newTop = (pos.top + (commodityPopupAlignElement.height() / 2)) - ($('#commodity-popup').height() / 2);
		var arrowClass = 'right';
		var arrowX = 0;
		var arrowY = 50;
		if (newRight + $('#commodity-popup').outerWidth(true) > $(window).width()) {
			newRight = $(window).width() - ((pos.left + (commodityPopupAlignElement.width() / 2)) + ($('#commodity-popup').outerWidth(true) / 2));
			newTop = pos.top - $('#commodity-popup').outerHeight(true);
			arrowClass = 'bottom';
			arrowX = 50;
			arrowY = 0;
			if (newRight + $('#commodity-popup').outerWidth(true) > $(window).width()) {
				newRight = $(window).width() - $('#commodity-popup').outerWidth(true);
				arrowX = ((pos.left + (commodityPopupAlignElement.width() / 2)) / $('#commodity-popup').outerWidth(true)) * 100;
			}
		}
		$('#commodity-popup')
			.removeClass('with-right-arrow')
			.removeClass('with-bottom-arrow')
			.addClass('with-' + arrowClass + '-arrow');
		$('#commodity-popup .popup-arrow').css({
			backgroundPosition: arrowX + '% ' + arrowY + '%'
		});
		if (noAnimation)
		{
			$('#commodity-popup').stop().css({ opacity: 1, display: 'block', right: newRight, top: newTop });
		}
		else
		{
			$('#commodity-popup').stop().css({ display: 'block' });
			if (parseInt($('#commodity-popup').css('right')) == 0)
			{
				$('#commodity-popup').css({ right: newRight, top: newTop }).animate({ opacity: 1 }, 200);
			}
			else
			{
				$('#commodity-popup').animate({ opacity: 1, right: newRight, top: newTop }, 200);
			}
		}
	}
	else
	{
		if (noAnimation)
		{
			$('#commodity-popup').stop().css({ opacity: 0, display: 'none', right: 0, top: 0 });
			if (originalCommodityPopupContent) $('#commodity-popup .commodity-popup-box .popup-content').html(originalCommodityPopupContent);
		}
		else
		{
			$('#commodity-popup').stop().animate({ opacity: 0 }, 200, function() {
				$(this).css({ display: 'none', right: 0, top: 0 });
				if (originalCommodityPopupContent) $('#commodity-popup .commodity-popup-box .popup-content').html(originalCommodityPopupContent);
			});
		}
	}
}