window.addEvent('domready', function()
{
	if ($$('[action=guests_merge.php]').getElements('[type=submit]')[0])
	{
		$$('[action=guests_merge.php]').getElements('[type=submit]')[0].addEvent('click', function(e){
	
			var aMergeWinnerSelected = 0;
			aMergeOptions = $$('[name=merge]');
			
			aMergeOptions.each(function(aMergeRadio){
				if (aMergeRadio) if (aMergeRadio.checked == true) aMergeWinnerSelected++;
			});
			
			if (aMergeWinnerSelected == 0) 
			{
				e.stop();
				alert('You must select a winning guest to continue.');
			}
		});
	}
	
	
	// Add confirmation to all elements with the 'rem' class
	if($$('.rem').length > 0)
	{
		$$('.rem').addEvent('click', function() {
			return Confirmation();
		});
	}
	
	if($$('.reminv').length > 0)
	{
		$$('.reminv').addEvent('click', function() {
			return ConfirmationImpact();
		});
	}
	
	// Add confirmation to the clear buttons
	if($$('a#clear').length > 0)
	{
		$$('a#clear').addEvent('click', function() {
			return ClearConfirmation();
		});
	} 
	
	var aCheckoutForm = document.getElementById('checkoutform');
	if (aCheckoutForm != null) aCheckoutForm.onsubmit = JSFnValidateCheckout;
	
	var aDeliveryForm = document.getElementById('deliveryinformation');
	if (aDeliveryForm != null) aDeliveryForm.onsubmit = JSFnValidateDelivery;
		
	if($('advanced'))
	{
		var aFormToSlide = new Fx.Slide('advanced');
		aFormToSlide.hide();

		$('advanced').style.display = 'block';

		$('advancedsearchlink').style.cursor = 'pointer';
		$('advancedsearchlink').style.color = '#A00';
		$('advancedsearchlink').style.textDecoration = 'underline';
		$('advancedsearchlink').addEvent('click', function(e){
			e.stop();
			aFormToSlide.toggle();
		});
	}

	if($('addtaskform'))
	{
		var aTaskFormToSlide = new Fx.Slide('addtaskform');
		aTaskFormToSlide.hide();
		$('addtaskform').style.display = 'block';
		$('addtasklink').style.cursor = 'pointer';
		$('addtasklink').addEvent('click', function(e){
			e.stop();
			aTaskFormToSlide.toggle();
		});
	}
	
	if($('addmediaform'))
	{
		var aMediaFormToSlide = new Fx.Slide('addmediaform');
		aMediaFormToSlide.hide();
		$('addmediaform').style.display = 'block';
		$('addmediaitemlink').style.cursor = 'pointer';
		$('addmediaitemlink').addEvent('click', function(e){
			e.stop();
			aMediaFormToSlide.toggle();
		});
	}
	
	if($('addaltrunform'))
	{
		var aRunTimeFormToSlide = new Fx.Slide('addaltrunform');
		aRunTimeFormToSlide.hide();
		$('addaltrunform').style.display = 'block';
		$('addruntimelink').style.cursor = 'pointer';
		$('addruntimelink').addEvent('click', function(e){
			e.stop();
			aRunTimeFormToSlide.toggle();
		});
	}
	
	
	
	if($('addcapacityform'))
	{
		var aCapacityFormToSlide = new Fx.Slide('addcapacityform');
		aCapacityFormToSlide.hide();
		$('addcapacityform').style.display = 'block';
		$('addcapacitylink').style.cursor = 'pointer';
		$('addcapacitylink').addEvent('click', function(e){
			e.stop();
			aCapacityFormToSlide.toggle();
		});
	}
	
	if($('addnoteform'))
	{
		var aNoteFormToSlide = new Fx.Slide('addnoteform');
		aNoteFormToSlide.hide();
		$('addnoteform').style.display = 'block';
		$('addnotelink').style.display = 'block';
		$('addnotelink').style.cursor = 'pointer';
		$('addnotelink').addEvent('click', function(e){
			e.stop();
			aNoteFormToSlide.toggle();
		});
	}
	
	if($('addspecialrequirementform'))
	{
		var aSpecialRequirementsFormToSlide = new Fx.Slide('addspecialrequirementform');
		aSpecialRequirementsFormToSlide.hide();
		$('addspecialrequirementform').style.display = 'block';
		$('addspecialrequirementlink').style.display = 'block';
		$('addspecialrequirementlink').style.cursor = 'pointer';
		$('addspecialrequirementlink').addEvent('click', function(e){
			e.stop();
			aSpecialRequirementsFormToSlide.toggle();
		});
	}

	if($('adddocumentform'))
	{
		var aDocFormToSlide = new Fx.Slide('adddocumentform');
		aDocFormToSlide.hide();
		$('adddocumentform').style.display = 'block';
		$('adddocumentlink').style.display = 'block';
		$('adddocumentlink').style.cursor = 'pointer';
		$('adddocumentlink').addEvent('click', function(e){
			e.stop();
			aDocFormToSlide.toggle();
		});
	}
	
	if($('addpaymentform'))
	{
		var aPaymentFormToSlide = new Fx.Slide('addpaymentform');
		aPaymentFormToSlide.hide();
		$('addpaymentform').style.display = 'block';
		$('addpaymentlink').style.display = 'block';
		$('addpaymentlink').style.cursor = 'pointer';
		$('addpaymentlink').addEvent('click', function(e){
			e.stop();
			aPaymentFormToSlide.toggle();
		});
	}
	
	if($('addchargeform'))
	{
		var aChargeFormToSlide = new Fx.Slide('addchargeform');
		aChargeFormToSlide.hide();
		$('addchargeform').style.display = 'block';
		$('addchargelink').style.display = 'block';
		$('addchargelink').style.cursor = 'pointer';
		$('addchargelink').addEvent('click', function(e){
			e.stop();
			aChargeFormToSlide.toggle();
		});
	}
	
	if($('guests_table_form'))
	{		
		if($('Comments'))
		{
			var aSMSTextareaSlide = new Fx.Slide('SMSHolder');
			aSMSTextareaSlide.hide();
			
			var aTextareaSlide = new Fx.Slide('Comments');
			aTextareaSlide.hide();
			
			$('Operation').addEvents({
				'focus': function(e)
				{
					e.stop();
					if(this.get('value') == 'SendSMS')
					{
						aTextareaSlide.hide();
						aSMSTextareaSlide.show();
					}
					else if(this.get('value') != 'Merge' && this.get('value') != 'SendSMS')
					{
						aTextareaSlide.show();
						aSMSTextareaSlide.hide();
					}
					else
					{
						aTextareaSlide.hide();
						aSMSTextareaSlide.hide();
					}
				},
				'change': function(e)
				{
					e.stop();
					if(this.get('value') == 'SendSMS')
					{
						aTextareaSlide.hide();
						aSMSTextareaSlide.show();
					}
					else if(this.get('value') != 'Merge' && this.get('value') != 'SendSMS')
					{
						aTextareaSlide.show();
						aSMSTextareaSlide.hide();
					}
					else
					{
						aTextareaSlide.hide();
						aSMSTextareaSlide.hide();
					}
				}
			});
		}
		else if ($('SMSHolder'))
		{
			var aSMSTextareaSlide = new Fx.Slide('SMSHolder');
			aSMSTextareaSlide.hide();
			
			$('Operation').addEvents({
				'focus': function(e)
				{
					e.stop();
					if(this.get('value') == 'SendSMS')
					{
						aSMSTextareaSlide.show();
					}
					else if(this.get('value') != 'Merge' && this.get('value') != 'SendSMS')
					{
						aSMSTextareaSlide.hide();
					}
					else
					{
						aSMSTextareaSlide.hide();
					}
				},
				'change': function(e)
				{
					e.stop();
					if(this.get('value') == 'SendSMS')
					{
						aSMSTextareaSlide.show();
					}
					else if(this.get('value') != 'Merge' && this.get('value') != 'SendSMS')
					{
						aSMSTextareaSlide.hide();
					}
					else
					{
						aSMSTextareaSlide.hide();
					}
				}
			});
		}
	}
	
	if($('SMSContent'))
	{		
		$('SMSContent').addEvents({
			'keyup': function(){
				aCurrentLength =  this.get('value').length;
				$('charactercount').set('html', (aCurrentLength));
			
				if(aCurrentLength <= 160)
				{
				   $('messagecount').set('html', 1);
				}
				else if(aCurrentLength >= 320  && aCurrentLength < 459)
				{
				   $('messagecount').set('html', 2);
				}
				else if(aCurrentLength > 459)
				{
					alert('Messages over 459 characters in length will not be sent!');
				}
			},
			'blur': function(){
				aCurrentLength =  this.get('value').length;
				$('charactercount').set('html', (aCurrentLength));
			
				if(aCurrentLength <= 160)
				{
				   $('messagecount').set('html', 1);
				}
				else if(aCurrentLength > 160  && aCurrentLength < 320)
				{
				   $('messagecount').set('html', 2);
				}
				else if(aCurrentLength > 320  && aCurrentLength < 459)
				{
				   $('messagecount').set('html', 3);
				}
				else if(aCurrentLength > 459)
				{
					alert('Messages over 459 characters in length will not be sent!');
				}
			},
			'focus': function(){
				aCurrentLength =  this.get('value').length;
				$('charactercount').set('html', (aCurrentLength));
			
				if(aCurrentLength <= 160)
				{
				   $('messagecount').set('html', 1);
				}
				else if(aCurrentLength >= 320  && aCurrentLength < 459)
				{
				   $('messagecount').set('html', 2);
				}
			}
		});
	}
	
	
	if($('BookingMakeForm'))
	{
		var aSelectedLocation = $('UnitLocation').get('value');
		
		$('MonthSelection').addEvents({
			'focus': function(){
				var aYearSelection= $('YearSelection').get('value');
				var aSelectedDate = this.value;
				
				if($('StayLengths').style.display == 'none')
				{
					LookupAvailableStayLengths(aSelectedDate, aYearSelection, aSelectedLocation);
					$('StayLengths').style.display = 'block';
				}
			},
			'change': function(){
				var aYearSelection= $('YearSelection').get('value');
				var aSelectedDate = this.value;
				LookupAvailableStayLengths(aSelectedDate, aYearSelection, aSelectedLocation);
				$('StayLengths').style.display = 'block';
				$('BookingDates').style.display = 'none';
			}
		});
		
		$('YearSelection').addEvents({
			'focus': function(){
				var aSelectedDate = $('MonthSelection').get('value');
				var aYearSelection = this.value;
				
				if($('BookingDates').style.display == 'none')
				{
					LookupAvailableStayLengths(aSelectedDate, aYearSelection, aSelectedLocation);
					$('StayLengths').style.display = 'block';
				}
			},
			'change': function(){
				var aSelectedDate = $('MonthSelection').get('value');
				var aYearSelection = this.value;
				LookupAvailableStayLengths(aSelectedDate, aYearSelection, aSelectedLocation);
				$('StayLengths').style.display = 'block';
				$('BookingDates').style.display = 'none';
			}
		});
		
		$('BookingStayLength').addEvents({
/*			'focus': function(){
				var aSelectedDate = $('MonthSelection').get('value');
				var aSelectedYear = $('YearSelection').get('value');
				var aStayLength = this.value;
				
				if($('BookingDates').style.display == 'none')
				{
					LookupAvailableStayDates(aSelectedDate, aSelectedYear, aStayLength);
					$('BookingDates').style.display = 'block';
				}
			},*/
			'change': function(){
				var aSelectedDate = $('MonthSelection').get('value');
				var aSelectedYear = $('YearSelection').get('value');
				var aStayLength = this.value;
				LookupAvailableStayDates(aSelectedDate, aSelectedYear, aStayLength, aSelectedLocation);
				$('BookingDates').style.display = 'block';
			}
		});
	}

	/* Sortable Tables */
	if($('admintasks_table')) adminTaskTable = new sortableTable('admintasks_table', {overCls: 'over', sortOn: -1, onClick: function(){}});

	if($('dashboard_bookings_table')) adminTaskTable = new sortableTable('dashboard_bookings_table', {overCls: 'over', sortOn: 4, onClick: function(){}});
	
	if($('guests_table')) clientTable = new sortableTable('guests_table', {overCls: 'over', onClick: function(){}});
	if($('units_table')) clientTable = new sortableTable('units_table', {overCls: 'over', onClick: function(){}});
	if($('allbookings_table')) aAllbookingsTable = new sortableTable('allbookings_table', {overCls: 'over', onClick: function(){}});
	
	if($('users_table')) usersTable = new sortableTable('users_table', {overCls: 'over', onClick: function(){}});
	if($('documents_table')) usersTable = new sortableTable('documents_table', {overCls: 'over', sortBy: 'DESC', onClick: function(){}});
	if($('tabmenu')) ApplyTabs();
});

function Confirmation()
{
    var deleteconf = confirm("Are you sure you want to delete this item?");
    return deleteconf;
}

function ConfirmationImpact()
{
	var deleteconf = confirm("Are you sure you want to delete this item? \n It may be attached to an invoice.");
    return deleteconf;
}


function ClearConfirmation()
{
	var deleteconf = confirm("Are you sure you want to clear this guest record? \n This cannot be undone!");
    return deleteconf;
}

function HideTabs()
{
	var aListItems = $('tabmenu').getElements('li');

	for(aIndex=0; aIndex < aListItems.length; aIndex++)
	{
		aListItems[aIndex].className = '';

		$(aListItems[aIndex].get('id').substr(1)).style.display = 'none';
	}
}

function ShowTab(aTabMenuID)
{
	HideTabs();
	$(aTabMenuID).className = 'selected';
	$(aTabMenuID.substr(1)).style.display = 'block';
}

function ClickTab()
{
	ShowTab(this.parentNode.id);
	return false;
}

function ApplyTabs()
{
	var aListItems = $('tabmenu').getElements('li');
	var showTabID = '';
	var url = location.href;
	var len = url.length;
	var foundAt = url.indexOf("#")+1;

	for(aIndex=0; aIndex < aListItems.length; aIndex++)
	{
		if(aIndex == 0) aFirstID = aListItems[aIndex].get('id');
		aListItems[aIndex].childNodes[0].onclick = ClickTab;
	}

	if(foundAt > 0)
	{
		window.scrollTo(0,0);
		showTabID = url.substr(foundAt, len);
	}

	if(showTabID != '') ShowTab('_' + showTabID)
	else ShowTab(aFirstID);
}


function JSFnValidateCheckout()
{
	return JSFnValidateForm(CheckoutRequiredFields);
}

DeliveryRequiredFields = new Array ("CustomerName","You must enter your name to continue.",
									"CustomerEmail","You must enter your email address to continue.",
									"DeliveryAddressLine1","You must enter the first line of your delivery address to continue.",
									"DeliveryAddressLine4","You must enter your delivery city/town to continue.",
									"DeliveryPostCode","You must enter your delivery postcode to continue.",
									"DeliveryType", "You must select a delivery method before you can continue.",
									"ContactNumber","You provide a contact number before you an place an order.");

DeliveryBillingRequiredFields = new Array ("BillingName","You must enter your billing name to continue.",									   
										   "BillingAddressLine1","You must enter the first line of your billing address to continue.",
										   "BillingAddressLine4","You must enter your billing city/town to continue.",
										   "BillingPostCode","You must enter your billing postcode to continue.");

function JSFnValidateDelivery()
{
	aResult = JSFnValidateForm(DeliveryRequiredFields);

	if (aResult != false)
	{
		var aBillingFirstName = document.getElementById('BillingName');
		var aBillingAddress = document.getElementById('BillingAddressLine1');
		var aBillingCity = document.getElementById('BillingAddressLine4');
		var aBillingPostcode = document.getElementById('BillingPostcode');
		
		if ((aBillingFirstName.value != '') || (aBillingAddress.value != '') || (aBillingCity.value != '') || (aBillingPostcode.value != ''))
		{
			aResult = JSFnValidateForm(DeliveryBillingRequiredFields);	
		}
	}
	
	return aResult;
}

function JSFnValidateForm(aRequiredFields)
{
	for (aIndex = 0; aIndex < aRequiredFields.length; aIndex = aIndex + 2)
	{
		currElement = document.getElementById(aRequiredFields[aIndex]);
		if (currElement != null)
		{
			if  (   (   (currElement.type == 'text')
				     && (currElement.value == ''))
				 || (   (currElement.type == 'password')
				     && (currElement.value == ''))
				 || (   (currElement.type == 'checkbox')
				     && (currElement.checked == false))
				 || (   (currElement.type == 'file')
				     && (currElement.value == ''))
				 || (   (currElement.type == 'textarea')
				     && (currElement.value == ''))
				 || (   (currElement.type == 'select-one')
				     && (currElement.value == '')))
			{
				alert(aRequiredFields[aIndex + 1]);
				return false;
			}
			else if (currElement.type == 'radio')
			{
				aIndex = aIndex + 2;
				if (!currElement.checked)
				{
					currElement = document.getElementById(aRequiredFields[aIndex]);
					if ((currElement.type == 'radio') && (!currElement.checked))
					{
						alert(aRequiredFields[aIndex + 1]);
						return false;
					}
				}
			}
		}
	}
	return true;
}

function LookupAvailableStayLengths(aFilterMonth, aYearSelection, aLocation)
{
	new Request.HTML({
		url: "../admin/ajax.php",
		update: $('BookingStayLength'),
		onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript)
		{			
			if(responseHTML.clean() == '<option value="">No available bookings</option>')
			{
				$('BookingDates').style.display = 'none';
				$('BookingUnitSearch').style.display = 'none';
			}
		}
	}).post({'FilterMonth': aFilterMonth, 'FilterYear' : aYearSelection,  'Loc': aLocation, 'type': 'bookingavailstays'});
}

function LookupAvailableStayDates(aSelectedDate, aSelectedYear, aStayLength, aLocation)
{
	new Request.HTML({
		url: "../admin/ajax.php",
		update: $('BookingStartDate'),
		onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript)
		{
			if(responseHTML.clean() == '')
			{
				$('BookingDates').style.display = 'none';
			}
			else $('BookingUnitSearch').style.display = 'block';
		}
	}).post({'FilterMonth': aSelectedDate, 'FilterYear' : aSelectedYear, 'StayLength': aStayLength, 'Loc': aLocation, 'type': 'bookingavaildates'});
}
