window.addEvent('domready', function() {
	

		
	// This is the ajax for block booking 
	if($('block_tickets')) {
	
		var updatePricesAjax = new Request.HTML({url:'/prices.ajax.php',update: $('single_ticket_prices')});
		
		function add_quantity_event() {
			$('quantity').addEvent('change',function() {
				updatePricesAjax.post($('block_tickets'));
				updateQuantityAjax.post($('block_tickets'));			
			}).fireEvent('change');
		}
				
		var updateQuantityAjax = new Request.HTML({		
			url:'/quantity.ajax.php',
			update: $('quantity_div'),
		 	onComplete: function() {
		 		add_quantity_event()
		 	}
		});
				
		$('block_tickets').addEvent('change',function() {
			updatePricesAjax.post($('block_tickets'));
			updateQuantityAjax.post($('block_tickets'));			
		}).fireEvent('change');		
		
		$('events_ticket_types_id').addEvent('change',function() {
			updatePricesAjax.post($('block_tickets'));
			updateQuantityAjax.post($('block_tickets'));						
		}).fireEvent('change');		
		
	
		add_quantity_event();
				
	} else if($('grid')) {
		
		// If there is a grid
		// ... well there's no point if there is no grid!
		
		// Do loading
		$('grid').setStyle('display','block');
		$('grid-loading').setStyle('display','none');
		$$('body').setStyle('cursor','default');
		
		// Make the grid 'unselectable'		
		$('grid').onselectstart = function() {return false};		
		$('grid').style.MozUserSelect = "none";
	

		
		// Because for whatever reason IE doesn't like doing in the normal way
		function returnCheckedElement(radioName) {
			var element = null;
			$$('input[name='+radioName+']').each(function(radio){		
				if(radio.get('checked') == true) {
				 	element = $(radio);
				}
			});
			return element;
		}
		
		// Because for whatever reason IE doesn't like doing in the normal way
		function returnRadioWithGivenValue(radioName,value) {
			var element = null;
			$$('input[name='+radioName+']').each(function(radio){		
				if(radio.get('value') == value) {
				 	element = $(radio);
				}
			});
			return element;
		}
		
		// Because the MooTools method doesn't seem to work properly
		// TODO: is that just because I was doing it wrong?
		function setSelectedIndex(s, v) {
		    for(var i=0;i<s.options.length;i++) {
		        if(s.options[i].value == v) {
		        	s.options[i].selected = true;
		            return true;
		        }
		    }
		    return false;
		}
			
		// Tooltips
		var soldTip = new Tips('.sold',{className: 'soldTip',fixed: false});
		var reservedTip = new Tips('.reserved',{className: 'reservedTip',fixed: false});
		var reservedTip = new Tips('.holding',{className: 'holdingTip',fixed: false});
		var toggleTip = new Tips('.toggle',{className: 'seatTip',fixed: false});
		
		// Update the prices AJAX
		var updatePricesAjax = new Request.HTML({url:'/prices.ajax.php',update: $('ticket_prices')}).post($('grid'));
		
		// Instantiate all the variables we shall be using 
		var startingElement;
		var endingElement;			
		var dragging = false;		
		var highlightedArray = [];
		var specificValue = 0;
		var draggingImage = ""; 
		
		// Get the specific value from the radio options
		$$('input[name=dragValue]').addEvent('change',function(){
			// Set the 'specificValue' variable so we 
			// know what the currently selected value is
			specificValue = returnCheckedElement('dragValue').get('value');
			// Set the dragging image for future use 
			draggingImage = $$('label[for='+returnCheckedElement('dragValue').get('id')+'] img').get('src');
		}).fireEvent('change');		
			
		// This is the function that actually changes the dropdown selection 
		// and updates the background-image for the div	
		// Do drowdown expects the actual element 
			
		function doDropdown(element) {
						
			// This is really just for my debugging!				
			if($type(element) != "element") {
				alert("doDropdown expects to be passed an element, you passed it a " + $type(element));
			}
			
			setSelectedIndex(element,specificValue);
						
			// Get the toggle element from the seat element (by replacing the 'seat' and 'toggle')...
			// TODO: thinking about this it could probably be done with getFirstParent or something
			// a bit more neatly...
			div = $(element.id.replace('seat','toggle'));
	
			// Update the innerHTML (no longer required)
			// div.innerHTML = element.options[element.selectedIndex].text;	
			
			if(element.options[element.selectedIndex].value == 0) {
				// Remove the 'selected' class and unset the background image if the selected element is 0
				div.removeClass('selected');
				div.setStyle('background-image','');
			} else {
				// Set the 'selected' background to the relevant image							
				div.addClass('selected');				
				div.setStyle('background-image','url('+draggingImage+')');				
			}							
			
		}
		
		
		// This is a new function required to set the 'correct' background image
		// for any given div. I need it to get the images right for seats which
		// are holding and owned by the user, and also to restore images which have
		// just been dragged over and thus lost 				
		function setCorrectImage(element) {
		
			// Let's be nice and let setCorrectImage accept a DIV if it must
			// If an element is provided then we assume we'v been given a div instead			
			if($type(element) != "element") {
				alert("setCorrectImage expects to be passed an element, you passed it a " + $type(element));			
			}
			
			// Only set the image if the element is not set to nothing						
			if(element.value != 0) {		
				var div = $(element.id.replace('seat','toggle'));									
				// Get the relevant radio button for this element's selected value	
				draggingImage = $$('label[for='+returnRadioWithGivenValue('dragValue',element.value).get('id')+'] img').get('src');				
				div.addClass('selected');				
				div.setStyle('background-image','url('+draggingImage+')');
			}
		}	
	
		function setImages() {
			$$('select.hstoggle[value!=0]').each(function(element){
				setCorrectImage(element);
			})
		}
			
		// Default any images that may have still been in the basket
		setImages()
		
		function startDrag(element) {
		
			// This is really just for my debugging!				
			if($type(element) != "element") {
				alert("startDrag expects to be passed an element, you passed it a " + $type(element));
			}
			
			dragging = true;
			startingElement = $(element).get('id');		
					
			$$('div.toggle').each(function(totoggle) {					
				$(totoggle).removeClass('dragging');								
			})		
			
			$(startingElement.replace('seat','toggle')).addClass('dragging');
		}
	
		function midDrag(element) {
	
			// This is really just for my debugging!				
			if($type(element) != "element") {
				alert("midDrag expects to be passed an element, you passed it a " + $type(element));
			}			
							
			// Get the starting and ending coordinates of the drag
			tempstartingElement = startingElement.replace('seat','').split('x'); 
			tempendingElement = element.id.replace('seat','').split('x'); 	

			var startx = parseInt(tempstartingElement[0]);
			var starty = parseInt(tempstartingElement[1]);
			var endx = parseInt(tempendingElement[0]);
			var endy = parseInt(tempendingElement[1]);
			
	
			if(parseInt(startx) < parseInt(endx)) {
				fillStartX = startx;
				fillEndX = endx;
			} else {
				fillStartX = endx;
				fillEndX = startx;
			}

			if(parseInt(starty) < parseInt(endy)) {
				fillStartY = starty;
				fillEndY = endy;
			} else {
				fillStartY = endy;
				fillEndY = starty;
			}

			// TODO: Dragged elements shopuld actually be called 
			// 'draggedDivIdArray' because it's the DIV id that's passed
			draggedelements = [];
			
			for(x=fillStartX;x<=fillEndX;x++) {
				for(y=fillStartY;y<=fillEndY;y++) {				
					draggedelements.push('toggle' + x + 'x' + y);
				}
			}

			// Remove anything that was previously marked as dragging			
			$$('div.dragging').each(function(totoggle) {	
				$(totoggle).removeClass('dragging');				
				$(totoggle).setStyle('background-image','');				
			})
			
			// Reselect the elements that are now dragging
			draggedelements.each(function(dragged) {
				$(dragged).addClass('dragging');	
				$(dragged).setStyle('background-image','url('+draggingImage+')');								
			})
				
		}
					
		function endDrag(element) {
	
			// This is really just for my debugging!				
			if($type(element) != "element") {
				alert("endDrag expects to be passed an element, you passed it a " + $type(element));
			}
			
			// Remove the dragging classes
			$$('div.dragging').each(function(totoggle) {
				totoggle.removeClass('dragging');
				$(totoggle).setStyle('background-image','');
			})
			
			// Reset selected images
			setImages();			
	
			endingElement = element.id;
	
			if(startingElement != "" && endingElement != "" && (startingElement != endingElement)) {
	
				// Get the starting and ending coordinates of the drag
				startingElement = startingElement.replace('seat','').split('x'); 
				endingElement = endingElement.replace('seat','').split('x'); 
	
				var starty = parseInt(startingElement[1]);
				var startx = parseInt(startingElement[0]);
				var endy = parseInt(endingElement[1]);
				var endx = parseInt(endingElement[0]);
		
				if(parseInt(startx) < parseInt(endx)) {
					fillStartX = startx;
					fillEndX = endx;
				} else {
					fillStartX = endx;
					fillEndX = startx;
				}
	
				if(parseInt(starty) < parseInt(endy)) {
					fillStartY = starty;
					fillEndY = endy;
				} else {
					fillStartY = endy;
					fillEndY = starty;
				}
				
				draggedelements = [];
				
				// Oh, and here the X and Y is backwards too!
				for(x=fillStartX;x<=fillEndX;x++) {				
					for(y=fillStartY;y<=fillEndY;y++) {					
						draggedelements.push('seat' + x + 'x' + y);				
					}
				}
	
				draggedelements.each(function(dragged) {
					doDropdown($(dragged));		
				})

				
			};
			
			if(startingElement != "" && endingElement != "" && (startingElement == endingElement)) {
				doDropdown($(endingElement));
			};
	
			endingElement = "";
			startingElement = "";
			dragging = false;

			// Update the prices			
			updatePricesAjax.post($('grid'));
			
			// Refire the seating type selector to make sure it's still set
			$$('input[name=dragValue]').fireEvent('change');
			
		}
		
		
		// Add a mousup event to stop the user from mousing up in the wrong place
		$('grid').addEvent('mouseup',function(){
			if(dragging == true) {
				$$('div.dragging').each(function(totoggle) {						
					totoggle.removeClass('dragging');	
					$(totoggle).setStyle('background-image','');	
					$$('input[name=dragValue]').fireEvent('change');					
				})
				endingElement = "";
				startingElement = "";
				dragging = false;
			}
			// Reset selected images
			setImages();			
		})	
	
			
		
			
		// Loop through the actual dropdowns (the select elements not the toggle divs)
		$$('select.hstoggle').each(function(element) {		
			
			// Although we are looping through the dropdown elements (element)
			// we are also very interested in the toggling div element (div)
			// Both 'div' and 'element' of these are elements.						
			div = $(element.id.replace('seat','toggle'));
	
			
			// Add onclick to the div label 			
			div.addEvent('click',function(){ 
				endDrag(element);
			}); 
	
			// Add mouseDown capture to each element
			div.addEvent('mousedown',function(){			
				// TODO: this should all be in 'startDrag'- don't know why it wasn't firing on time...
				// If we're starting to drag on the same element that is already selected/
				// then we toggle the ticket selection to remove				
				
				if(specificValue == $(this.id.replace('toggle','seat')).value) {
					specificValue = 0;	
					var specificValueID = $$('input[name=dragValue][value=0]').get('id');
					draggingImage = $$('label[for='+specificValueID+'] img').get('src');	
				}						  			
				this.addClass('dragging');
				this.setStyle('background-image','url('+draggingImage+')');														
				startDrag(element);				
			}); 
	
			// Add mouseUp capture
			div.addEvent('mouseup',function(){  			
				endDrag(element);
			}); 
									
			div.addEvent('mouseenter',function(){
				if(dragging == true) {					
					midDrag(element);
				}
				if(dragging == false) {					
					$$('div.dragging').each(function(totoggle) {	
						totoggle.removeClass('dragging');	
									
					});						
					this.addClass('hover');								
				}
			}); 				
			
			div.addEvent('mouseleave',function(){
				this.removeClass('hover');
			}); 				
									 				
			// Change the DIV's text to the correct default
			//div.innerHTML = element.options[element.selectedIndex].text;	
			 
			//Set the class					
			//div.addClass('item' + element.options[element.selectedIndex].value);
										
		})
	}
	
});
