$(document).ready(function(){

	if ( $('input[name=bookingid]').length > 0)
		$('#workspace h2.propname').html( $('h2.propname').html() + ' <span style="font-size: 12px; font-weight: normal; color: #5E0D16;"> ( BookingId: ' + $('input[name=bookingid]').val() + ')</span>' )

	$('#bookingform input[name=provisional]').bind('click', function(){

		$('#bookingform input[name=amount]').parent().prev().text( ( $(this).attr('checked') ) ? 'Deposit Amount' : 'Total Already Paid' )

	})

	$('#bookingform input[name=paid]').bind('click', function(){

		var amount = $('#bookingform input[name=amount]')
		if ( amount.attr('initval') == undefined ) amount.attr( 'initval', amount.val() )

		amount.val( ( this.checked ) ? $('#bookingform input[name=bookingprice]').val() : amount.attr('initval') )


		var provisional = $('#bookingform input[name=provisional]')
		if ( provisional.attr('initval') == undefined ) provisional.attr( 'initval', provisional.attr('checked') )

		if ( this.checked )
			provisional.attr('checked', false )
		else
			provisional.attr('checked', (provisional.attr('initval') == 'true') ? true : false )

	})

	$('#bookingform').bind('submit', function(){
		return validateBooking(this);
	})

	$('#bookingform :submit[value=Delete]').bind('click', function(){

		var proceed = confirm('Click OK to confirm the deletion of this booking.')
		if ( proceed )
			$(this).parents('form:first').unbind('submit');

		return proceed;

	})

	$('#bookingform :submit[value=Make Dates Unavailable]').bind('click', function(){

		$(this).parents('form:first').unbind('submit');

	})

	$('#bookingform :submit[value=Cancel]').bind('click', function(){

		if( $(this).parents('form:first;').find(':input[name=bookingid]').val() == 0 ) {
			window.location.href = '/admin/';
			return false;
		}
		else
		var proceed = confirm('Click OK to confirm the cancellation of this booking.')
		if ( proceed )
			$(this).parents('form:first').unbind('submit');

		return proceed;

	})

	// cancellation fee
	if ( $('#cancelledbookings') ) {

		var bookingId = $('th:contains(BookingId)').next().text()

		var fee = $('th:contains(Cancellation Fee)').next()
		fee.html( '<input type="" name="" value="' + fee.text() +  '" />' )
		fee = fee.find('input')
		fee.bind('blur', function(){

			$.post('/admin/cancellations.asp', { action: 'update fee', bookingId: bookingId, fee: $(this).val() }, function(s){

				if ( s != fee.val() ) {
					fee.css('color','red')
					alert(s)
				}
				else {
					fee.css('color','green')
					setTimeout( function(){ fee.css('color','#000') }, 1500 )
				}

			})

		})

	}
});

function updatePartyTotal()
{
    var adults = (document.booking.adults.options[document.booking.adults.selectedIndex].text=='')?0:parseInt(document.booking.adults.options[document.booking.adults.selectedIndex].text)
    var children = (document.booking.children.options[document.booking.children.selectedIndex].text=='')?0:parseInt(document.booking.children.options[document.booking.children.selectedIndex].text)
    var toddlers = (document.booking.toddlers.options[document.booking.toddlers.selectedIndex].text=='')?0:parseInt(document.booking.toddlers.options[document.booking.toddlers.selectedIndex].text)
    var partyTotal = document.getElementById("partyTotal").getElementsByTagName('span')[0]
    var total = (adults + children + toddlers)
    if ( partyTotal != null) partyTotal.innerHTML = total
    partyTotal.style.color = ( total > 12 )?'#ff0000':'#000'
    partyTotal.parentElement.parentElement.getElementsByTagName('th')[1].style.color = ( total > 12 )?'#ff0000':'#000'
}

function updateBookingFee(e, price)
{
    if ( e.checked )
    {
        document.getElementById('bookingFee').getElementsByTagName('span')[0].innerHTML = "&pound;" + addCommas(price.toFixed(2))
    }
}

function addCommas(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
	    x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function validateBooking(f)
{
    var msg = 'The following errors occured...\n';

    // Booking Details
    var departure = null;
    if ( f.departure.value == undefined )
    {
        for ( i=0; i<f.departure.length; i++ )
            if (f.departure[i].checked) departure = f.departure[i].value
    }
    else if ( f.departure.value != '' )
        departure = f.departure.value

    if ( departure == null ) msg = msg + '\n    A departure date has not been selected.'

    var adults = parseInt(f.adults.options[f.adults.selectedIndex].value)
    var children = parseInt(f.children.options[f.children.selectedIndex].value)
    var toddlers = parseInt(f.toddlers.options[f.toddlers.selectedIndex].value)

    // Group Leader Contact Details
    if ( f.fullname.value == '' ) msg = msg + '\n    Your name is required.'
    if ( f.address.value == '' ) msg = msg + '\n    Your address is required.'
    if ( f.postcode.value == '' ) msg = msg + '\n    Your postcode address is required.'
    if ( !checkMail(f.email.value) ) msg = msg + '\n    Your email address is invalid.'

    if ( f.telhome.value + f.telwork.value + f.telmobile.value == '' ) msg = msg + '\n    At least one phone number is required.'

    if ( f.paymentmethod != null )
		if ( f.paymentmethod.value == '' ) msg = msg + '\n    A payment method is required.'

    // Confirmation
    if ( f.iagree != null )
        if ( f.iagree.value != 'I Agree' ) msg = msg + '\n    The confirmation value needs to be \'I Agree\'.'

    if ( msg != 'The following errors occured...\n' )
    {
        alert(msg)
		var e = $( f ).find(':input:visible[value=]:first')
		$.scrollTo( e.parents('table:first') , 500)
		e.focus()
        return false;
    }

    return true;
}
function checkMail(email)
{
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,6})+$/;
	return filter.test(email)
}