﻿$(document).ready(function(){

	if( $("#workspace #equipment.sortable").length > 0 ) {

		$("#equipment.sortable").sortable({

			axis: 'y',
			containment: 'parent',
			opacity: .4,
			stop: function(){

					var ids = '';
					$("#equipment.sortable li.item").each(function(){

						ids = ids + $(this).children(':first').attr('id') + ','

					})
					$.get( '/admin/equipment.asp', { action: "reorder", ids: ids.substring(0, ids.length-1 ) } );
					$('#equipment li').removeClass('alt');
					$('#equipment li:even').addClass('alt');
			}
		});

	}

	$('#workspace #equipment li input[name^=equipment]').bind('blur', function(){


		$.get( '/admin/equipment.asp', {

				action: "Associate Equipment",
				equipmentid: $(this).attr('name').replace('equipment',''),
				quantity: parseInt($(this).val()),
				id: $(this).parents('ul:first').attr('propertyid')

		});

	})

	$('#workspace #equipment li:even').addClass('alt');

	$('#workspace #equipment input[name=description]').focus()


	// Hide select list (rooms) of items not checked.
	$('.equipment :checkbox:not(:checked)').each(function(){

		$(this).parents('tr:first').find('select').hide();

	});
	// Hide the title of the second column if there are no visible select lists.
	$('.equipment th:eq(1)').text( ( $('.equipment select:visible').length == 0 ) ? '' : 'Room' )

	// Set the width of the select list's table cell to prevent
	// it collapsing when the select lists are all hidden.
	$('.equipment select').each(function(){

		$(this).parent().css('width', $(this).width()+4+'px' )

	});

	// Toggle the visibility of the select list when an item state is changed.
	$('.equipment :input[type=checkbox]').bind('click', function(){

		$(this).parents('tr:first').find('select').toggle().val('');

		// Hide the title of the second column if there are no visible select lists.
		$('.equipment th:eq(1)').text( ( $('.equipment select:visible').length == 0 ) ? '' : 'Room' )

		$(this).parents('tr').next().show()
		alternate()

	});

	//
	$("table.equipment").each(function(){

		var items = $(this).find("tbody:first tr").get();
		//iterate through this array in reverse order
		for ( var i = items.length - 1; i >= 0; --i){

			if (i > 0) {

				var item = $(items[i]).find('input[name^=equipment]').attr('name')
				item = item.substring(0, item.indexOf(':', item.indexOf(':')+1) )

				var prevItem = $(items[i-1]).find('input[name^=equipment]')

				if ( item == prevItem.attr('name').substring(0, item.length) && !$(items[i]).attr('checked') && !prevItem.attr('checked') )
					$(items[i]).hide()

			}

		}

	});
	alternate()
});

function alternate() {
	$("table.equipment").each(function(){
		$(this).find('tbody:first tr').removeClass('alt');
		$(this).find('tbody:first tr:visible:even').addClass('alt');
	});
}