var HTMLElement = ECTYPE.display.HTMLElement;
var selectedScheduleDates = [];
var scheduleIsVisible = [];

/**
 * Goes out and gets the schedule for the link clicked and places it into the dom.
 */
function getScheduleInfo(id, index)
{
	var a = document.getElementById('schedule-' + id);
	
	// check to see if this schedule info is already available
	for(var i = 0; i < selectedScheduleDates.length; i++)
	{		
		if(id == selectedScheduleDates[i])
		{
		    var tr = document.getElementById('schedule-expanded-' + id);
		
            if (scheduleIsVisible[id])
            {
                tr.style.display = 'none';
				a.className = '';
            }
            else
            {
                tr.style.display = '';
				a.className = 'close';
            }
            
            // Refresh the ScrollPane.. would do this less hacky like if
            // had more time.
            var tmp = tr;
            while ((tmp = tmp.parentNode).className != 'ScrollPane'){};
            tmp.refresh();
            scheduleIsVisible[id] = !scheduleIsVisible[id];
			return;
		}
	}
	
	var variables = new URLVariables();
	variables.id = id;
			
	var request = new URLRequest('./includes/getScheduleInfo.php');
	request.data = variables;
			
	var loader = new URLLoader(request);
	loader.addEventListener(
		'complete',
		function(e)
		{			
			a.className = 'close';
			
			// get the tr that holds our anchor
            var tr = document.getElementById('schedule-' + id);
			while(tr.nodeName != 'TR')
			{
				tr = tr.parentNode;
			}
			
			var newTr = new HTMLElement(document.createElement('tr'));
			newTr.id = 'schedule-expanded-' + id;
			
			if(tr.className == 'alternate')
			{
				newTr.className = 'alternate';
			}
			
			new HTMLElement(tr.parentNode);

            var index = tr.parentNode.getChildIndex(tr);
            tr.parentNode.addChildAt(newTr, index + 1);

            var htmlFragment = new HTMLFragment(e.currentTarget.data);
            var td;
            while (td = htmlFragment.childNodes[0])
            {
                newTr.addChild(td);
            }

			// add the selected tour date to the array so we know if its been clicked or not
			selectedScheduleDates.push(id);
			scheduleIsVisible[id] = true;
		}
	);
};

/**
 * Assign schedule actions
 */
function createScheduleChooser()
{
	var schedule = document.getElementById('tourSchedule');
	var rows = schedule.getElementsByTagName('tr');
	
	for(var i = 0; i < rows.length; i++)
	{
		var a = rows[i].getElementsByTagName('a');
		a = a[a.length - 1];
		a.number = i;
		
		new HTMLElement(a);
		
		a.addEventListener(
			'click', 
			function(e)
			{
				var id = e.currentTarget.id.split('-').pop();

				e.preventDefault();					 
				getScheduleInfo(id, e.currentTarget.number);
			}
		);
	}
};

window.addEventListener('load', createScheduleChooser);
