$(document).ready(function() {
	
	var browser = BrowserDetect.browser+BrowserDetect.version;
	
	var useAnim = true;
	
	if (browser == "Explorer6")
	{
		useAnim = false;
	}

	
	$.tablesorter.defaults.widgets = ['zebra']; 
    $("#closures li div table").tablesorter( {
		sortList: [[0,0]],
		cssAsc: "headerSortUp",
		cssDesc: "headerSortDown"
	} ); 
	
	$('#bf-summary').hide();
	
	$('#closures li div table tbody tr').bind("mouseover", function() { $(this).addClass('highlight'); } );
	$('#closures li div table tbody tr').bind("mouseout", function() { $(this).removeClass('highlight'); } );
	
	$('#closures li div table tbody tr').css('cursor', 'pointer');
	$('#closures li div.heading').css('cursor', 'pointer');

	$('#closures li div table tbody tr').bind("click", function() {
		var thisTable = $(this).parent().parent().attr('id');
		var curSelection = $(this).attr('id');
		var clickable = $(this).hasClass('clickable');
		curSelection = curSelection.substring(curSelection.indexOf('-')+1);
		$('[id$="'+curSelection+'"]').each( function() {
			if ($(this).hasClass('selected'))
			{
				$(this).removeClass('selected');
				
				if (clickable)
				{
					// remove summary
					if ($('#bf-summary-container div[class="summary"]:visible').length == 1)
					{
						if (useAnim)
						{
							$('#bf-summary').slideUp(400);
						}
						else
						{
							$('#bf-summary').hide();
						}
					}
					$('#bf-summary-container div[id="sum-'+curSelection+'-sum"]').slideUp(400);
					
					// check if this table has other rows selected
					if (!$(this).siblings('tr').hasClass('selected'))
					{
						// this table has no other rows selected - close this
						if (thisTable != $(this).parent().parent().attr('id'))
						{
							if (useAnim)
							{
								$(this).parent().parent().parent().slideUp('750');
							}
							else
							{
								$(this).parent().parent().parent().hide();
							}
							$(this).parent().parent().parent().siblings('div.heading').children('div.control').addClass('control-closed');
							$(this).parent().parent().parent().siblings('div.heading').children('div.control').removeClass('control-open');
						}
					}
				}
			}
			else
			{
				$(this).addClass('selected');
				if (clickable)
				{
					if ($(this).parent().parent().parent().is(':hidden'))
					{
						if (useAnim)
						{
							$(this).parent().parent().parent().slideDown('750');
						}
						else
						{
							$(this).parent().parent().parent().show();
						}
						$(this).parent().parent().parent().siblings('div.heading').children('div.control').removeClass('control-closed');
						$(this).parent().parent().parent().siblings('div.heading').children('div.control').addClass('control-open');
					}
					if (useAnim)
					{
						$.scrollTo($('#bfsearch-position'), {duration: 200, axis:"y"});
					}
					else
					{
						$.scrollTo($('#bfsearch-position'), {duration: 0, axis:"y"});
					}
					updateSelected();
				}
			}
		});

		thisTable = false;
	} );
	
	$('#closures li[class="today"] div.table').each(function(){ 
		$(this).show();
		$(this).siblings('div.heading').children('div.control').addClass('control-open');
	});
	
	$('#closures li[class!="today"] div.table').each(function(){ 
		$(this).hide();
		$(this).siblings('div.heading').children('div.control').addClass('control-closed');
	});
	
	if ($('#closures li div.table').length == 1)
	{
		$('#closures li div.table').each(function(){ 
			$(this).show();
		});
	}
	
	var tableCounter = 0;
	$('#closures li div table').each( function() {
		$(this).attr('id', 'bfday-'+tableCounter);
		tableCounter++;
	});
	

	$('#closures li div.heading').click(function() { 
		if ($(this).children('div.control').length > 0)
		{
			if (useAnim)
			{
				$(this).siblings('div.table').slideToggle(750);
			}
			else
			{
				$(this).siblings('div.table').toggle();
			}
			if ($(this).children('div.control').hasClass('control-open'))
			{
				$(this).children('div.control').removeClass('control-open');
				$(this).children('div.control').addClass('control-closed');
			}
			else
			{
				$(this).children('div.control').addClass('control-open');
				$(this).children('div.control').removeClass('control-closed');
			}
		}
	} );




	function updateSelected()
	{
		var selected = Array();

		if ($('#bf-summary:hidden'))
		{
			if (useAnim)
			{
				$('#bf-summary').slideDown(100);
			}
			else
			{
				$('#bf-summary').show();
			}
		}

		$('#closures li div table tbody tr.selected').each(function() { 
			var newSelection = $(this).attr('id');
			newSelection = newSelection.substring(newSelection.indexOf('-')+1);
			if (!selected.inArray(newSelection))
			{
				selected[selected.length] = newSelection;
		
				if ($('#bf-summary-container div[id="sum-'+newSelection+'-sum"]').length == 0)
				{
					var tr = $('<div class="summary" id="sum-'+newSelection+'-sum"></div>');
					tr.hide();
					
					var del = $('<div class="bf-summary-delete">Delete</div>');
					del.css('cursor', 'pointer');
					del.attr('title', 'Delete');
					tr.append(del);
					
					del.click(function() {
						var ref = $(this).parent().attr('id').substr(4);
						if ($('#bf-summary-container div[class="summary"]:visible').length == 1)
						{
							if (useAnim)
							{
								$('#bf-summary').slideUp(400);
							}
							else
							{
								$('#bf-summary').hide();
							}
						}
						if (useAnim && browser != "Explorer7")
						{
							$('#bf-summary-container div[id="sum-'+ref+'"]').slideUp(400);
						}
						else
						{
							$('#bf-summary-container div[id="sum-'+ref+'"]').hide();
						}
						$('#closures li div table tbody tr[id$="'+ref.substring(0, ref.length-4)+'"].selected').removeClass('selected');
					});
										
					var data = Array();
					$(this).children('td').each( function() {
						data[data.length] = $(this).text();
					});
					
					tr.append('<div class="summary-name">'+data[1]+'</div>');
					tr.append('<div class="summary-address">'+data[2]+'</div>');
					tr.append('<div class="summary-suburb">'+data[0]+'</div>');
					
					var ul = $('<ul></ul>');
					
					$('#closures li div table tbody tr[id$="'+newSelection+'"]').each(function() { 
						var date = $(this).parent().parent().parent().siblings('div.heading').children('div.date').text();
						var status = $(this).children('td:last').text();
						var img = $('<img />');
						img.attr('width', 12);
						img.attr('height', 12);
						img.attr('alt', status);
						
						var statusClass = '';
						switch (status)
						{
							case "Closed":
								img.attr('src', '/images/template/bushfires/icon-closed.gif');
								statusClass = 'closed';
								break;
							case "Potentially Closed":
								img.attr('src', '/images/template/bushfires/icon-pclosed.gif');
								statusClass = 'pclosed';
								break;
							case "Open":
								img.attr('src', '/images/template/bushfires/icon-open.gif');
								statusClass = 'open';
								break;
						}
						var li = $('<li></li>');
						li.append(img);
						
						var sdate = $('<span>'+date+': </span>');
						var sstatus = $('<span class="bf-summary-'+statusClass+'">'+status+'</span>');
						
						li.append(sdate);
						li.append(sstatus);
						
						ul.append(li);
					});
					
					tr.append(ul);
					
					if ($('#bf-summary-container div').length == 0)
					{
						$('#bf-summary-container').append(tr);
					}
					else
					{
						var ins = false;
						$('#bf-summary-container div[id]').each(function() {
							if ($(this).children('div[class="summary-name"]').text() >= data[1])
							{
								$(this).before(tr);
								ins = true;
								return false;
							}
						});
						if (!ins)
						{
							$('#bf-summary-container').append(tr);
						}
					}
					
				
				}
				
					if (useAnim && browser != "Explorer7")
					{
						$('#bf-summary-container div[id="sum-'+newSelection+'-sum"]').slideDown(400);


					}
					else
					{
						$('#bf-summary-container div[id="sum-'+newSelection+'-sum"]').show();
					}
			}
		});
	}
	
	$('#bf-summary-header').append('<a href="#print" id="bf-summary-print">Print Page</a>');
	$('#bf-summary-print').click(function() {
		window.print();
		return false;
	});
	
	$('#bfsearch').bind("keyup", function() {
		// find list of schools that match
		var term = $(this).val();
		
		if (term != '')
		{
			var ids = new Array();
			var results = new Array();
			var hasResult = false;
			$('#closures li div.table tbody tr').each( function() { 
				var hasMatch = false;
				$(this).children('td:Contains("'+term+'")').each( function() { hasMatch = true; } );
				if (hasMatch)
				{
					var id = $(this).attr('id').substring($(this).attr('id').lastIndexOf('-')+1);
					if (!ids.inArray(id))
					{
						hasResult = true;
						//results[id] = new Array();
						var itemMatch = new Object();
						var itemPos = 0;
						$(this).children('td:not([class])').each(function() {
							itemMatch[itemPos] = $(this).text();
							itemPos++;
						});
						ids[results.length] = id;
						results[results.length] = itemMatch;
					}
				}
			});

			function compareNames(a, b) {
				var nameA = a[1].toLowerCase( );
				var nameB = b[1].toLowerCase( );
				if (nameA < nameB) {return -1}
				if (nameA > nameB) {return 1}
				return 0;
			}

			results.sort(compareNames);

			// 0 SUBURB
			// 1 NAME
			// 2 ADDRESS
			if (hasResult)
			{				
				var counter = 0;
				var res = $('<ul></ul>');
				for (var key in results)
				{
					if (counter == 10)
					{
						var li = $('<li class="status"></li>');
						li.append('Only the first 10 results have been displayed.');
						res.append(li);
						break;
					}
					if (key != 'inArray' && key != 'multiSort')
					{
						var li = $('<li></li>');
						if (counter % 2 != 0) { li.attr('class', 'odd'); }
						li.attr('id', 'res-'+ids[key]);
						li.append('<strong>'+results[key][1] + ', ' + results[key][0]+'</strong>');
						li.append('<br>');
						li.append(results[key][2]);
						li.css('cursor', 'pointer');
						
						li.bind("mouseover", function() { $(this).addClass('highlight'); } );
						li.bind("mouseout", function() { $(this).removeClass('highlight'); } );
						
						li.bind("click", function () { 
												   
							var curSelection = $(this).attr('id');
							curSelection = curSelection.substring(curSelection.indexOf('-')+1);
							$('[id$="'+curSelection+'"]').each( function() {
																	   
									$(this).addClass('selected');
									if ($(this).hasClass('clickable'))
									{
										if ($(this).parent().parent().parent().is(':hidden'))
										{
											$(this).parent().parent().parent().slideDown('750');
											$(this).parent().parent().parent().siblings('div.heading').children('div.control').removeClass('control-closed');
											$(this).parent().parent().parent().siblings('div.heading').children('div.control').addClass('control-open');
										}
										updateSelected();
									}
							});
							
							$('#bfsearch').val('');
							
						});
						
						res.append(li);
						
						counter++;
					}
				}

				$('#bfsearch-results').empty().append(res);
				$('#bfsearch-results').show();
			}
			else
			{
				var res = $('<ul></ul>');
				var li = $('<li></li>');
				li.append('There are no results found.');
				res.append(li);
				$('#bfsearch-results').empty().append(res);
				$('#bfsearch-results').show();
			}
		}
		else
		{
			$('#bfsearch-results').empty();
			$('#bfsearch-results').hide(); 
		}
	});

	//if ($('#closures').children('li').children('div.table').children('table').children('tbody').children('tr').length <= 100)
	// limit the search to only show if there are 130 TR elements within the closures ID. This is for performance reasons
	if ($('#closures').find('li div.table table tbody tr').length <= 130)
	{
		$('#bfsearch-position').show();
	}
	
	$('#bfsearch-results').bind('blur', function() { 
		$('#bfsearch-results').empty();
		$('#bfsearch-results').hide(); 
	} );
	
	$('#bfsearch-position input').bind('focus', function() {
		$('#bfsearch-position input').val('');
		$('#bfsearch-position input').css('color', '#333');
	});
	
	$('#bfsearch-position input').bind('blur', function() {
		if ($('#bfsearch-position input').val() == '')
		{
			$('#bfsearch-position input').css('color', '#999');	
			$('#bfsearch-position input').val('Service Name, Address or Suburb');
		}
	});
	
	$('body').bind('click', function() { 
		$('#bfsearch-results').empty();
		$('#bfsearch-results').hide(); 
	});
	
	jQuery.expr[':'].Contains = function(a,i,m){
		return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0;
	};
	
});

Array.prototype.inArray = function (value) {
	var i;
	for (i=0; i < this.length; i++) {
		if (this[i] === value) {
			return true;
		}
	}
	return false;
};