var pp = {
    summary: {},
    course: null,
    venue: null,
    dates: [],
    apiUrl: 'booking/service.php',
    weekdays: null,

    removeSection: function(section) {
      $('#'+section).fadeOut('fast', function() {
         $(this).remove();
      });
    },

    loadVenues: function(course_id) {
        window['pp'].course = course_id;
        this.removeSection('venues');

        $.ajax({
            url: this.apiUrl,
            method: 'GET',
            data: {'method': 'venues', 'course': course_id},
            beforeSend: function() {
                $('#booking').append('<div id="loading">Loading, Please wait&hellip;</div>');
                $("#loading").fadeIn();
            },
            success: function(data) {
                $("#loading").fadeOut('fast', function() {
                    $(this).remove();
                    $("#booking").append(data);
                    $("#venues").fadeIn();
                    $('#venues select').selectbox();
                    $('div.selectbox-wrapper ul li').bind('click', function() {
                       $('#'+$(this).attr('id').substr(0, ($(this).attr('id').length - 2))).val($(this).html().substr(0, 22)+'..');
                       if($(this).attr('id').substr(($(this).attr('id').length - 1), 1) != window['pp'].venue) {
                           window['pp'].venue = $(this).attr('id').substr(($(this).attr('id').length - 1), 1);
                           $('#picker_'+$(this).attr('id').substr(15, 1)).val('');
                           $('span.booking_date_'+$(this).attr('id').substr(15, 1)).html('Click to select date');
                           $('#buy').fadeOut();
                           window['pp'].updateSummary();
                       }
                    });
                    $('#venues .picker').datepicker({
                       showOn: 'button',
                       buttonImage: 'gfx/date_icon.jpg',
                       buttonImageOnly: true,
                       minDate: '+0d',
                       maxDate: '+8w',
                       dateFormat: 'dd/mm/yy',
                       onSelect: function(dateText, inst) {
                         var date = dateText.split('/');
                         var year = date[2];
                         var month = date[1] - 1;
                         month = (month<10)?'0'+month:month;
                         var day = (date[0]<10)?'0'+date[0]:date[0];

                         var dObject = new Date(year, month, day);
                         
                           var shortDay = window['pp'].weekdays[dObject.getDay()].substr(0, 3);
                           
                           var time = '8.00pm';

                           for(var key in window['pp'].days) {
                             var day = window['pp'].days[key];

                             if(day.short == shortDay) {
                               if(typeof(day.venues) != "undefined") {
                                 for(var v in day.venues) {
                                   if(day.venues[v].id == window['pp'].venue) {
                                     time = day.venues[v]['@attributes']['time'];
                                   }
                                 }
                               }
                             }
                           }
                           
                           $(inst.trigger).siblings('span').html(dateText+' '+time);
                           window['pp'].updateSummary();
                       },
                       beforeShowDay: function(date) {
                           var shortDay = window['pp'].weekdays[date.getDay()].substr(0, 3);
                           var active = false;
                           
                           for(var key in window['pp'].days) {
                             var day = window['pp'].days[key];
                             
                             if(day.short == shortDay) {
                               if(typeof(day.venues) != "undefined") {
                                 for(var v in day.venues) {
                                   if(day.venues[v].id == window['pp'].venue) {
                                     active = true;
                                   }
                                 }
                               }
                             }
                           }
                           
                           return new Array(
                               active,
                               ''
                           );
                       }
                    });
                });
            }
        });
    },

    loadCourses: function() {
        this.removeSection('dates');
        this.removeSection('venues');
        this.removeSection('courses');

        $('.picker').val('');

        $.ajax({
            url: this.apiUrl,
            method: 'GET',
            data: {'method': 'courses'},
            beforeSend: function() {
                $('#booking').append('<div id="loading">Loading, Please wait&hellip;</div>');
                $("#loading").fadeIn();
            },
            success: function(data) {
                $("#loading").fadeOut('fast', function() {
                    $(this).remove();
                    $("#booking").append(data);
                    $("#courses").fadeIn();
                });
            }
        });
    },

    bindClicks: function() {
        $('#courses a').live('click', function() {
            $("#buy").fadeOut();

            window['pp'].loadVenues(
                $(this).parent().attr('id').replace(/course-/, '')
            );

            window['pp'].summary.course = $(this).html();
            window['pp'].summary.venue = '';
            window['pp'].updateSummary();

            return false;
        });

        $('#venues a').live('click', function() {
            $("#buy").fadeOut();

            window['pp'].venue = $(this).attr('name').replace(/venue-/, '');

            window['pp'].summary.venue = $(this).html();
            window['pp'].updateSummary();

            return false;
        });

        $('#venues').live('click', function() {

        });
    },

    updateSummary: function() {
        var summary = '';

        if(typeof(window['pp'].summary.course) != "undefined") {
            summary = window['pp'].summary.course;
        }

        var venues = Array(4);
        $('#venues select :selected').each(function(i, box) {
            if($(box).text() != "Click here to select venue") {
                venues[i] = {text: $(box).text(), date: $('.booking_date_'+(i+1)).html()};
            }
        });

        var j = 0;
        for(i in venues) {
            if(typeof(venues[i]) != "undefined") {
                summary += '<br />&nbsp;&nbsp;&gt;&nbsp;'+venues[i].text;
                if(venues[i].date != "Click to select date") {
                    summary += '<br />&nbsp;&nbsp;&nbsp;&nbsp;&gt;&nbsp;'+venues[i].date;
                    j += 1;
                }
            }
        }

        $('#summary').html(summary);

        if($('#venues select').length == j && j != 0) {
            $('#buy').fadeIn();
        }

        window['pp'].updatePrice();
        window['pp'].updateProduct(summary);
    },

    updateProduct: function(summary) {
        var summary = summary.replace(/&(nbsp|gt|lt|pound);/gi, '').replace(/&amp;/gi, 'and').replace(/<br \/>/gi, ' ').replace(/'.+/, '');
        summary = summary.replace(/£[0-9\.\s]+/gi, '');


        $('#booking_string').val(summary);
    },

    updatePrice: function() {
        var price = $('#summary').html().replace(/(&gt;.+)/, '').replace(/[^0-9.]+/gi, '');

	if(price == '') {
            price = 13.75;
	}

	$("#booking_value").val(price);
    },

    init: function() {
        if($('#booking')) {
            this.loadCourses();
            this.bindClicks();
            window['pp'].weekdays = new Array(7);
            window['pp'].weekdays[0] = "Sunday";
            window['pp'].weekdays[1] = "Monday";
            window['pp'].weekdays[2] = "Tuesday";
            window['pp'].weekdays[3] = "Wednesday";
            window['pp'].weekdays[4] = "Thursday";
            window['pp'].weekdays[5] = "Friday";
            window['pp'].weekdays[6] = "Saturday";
        }
    }
}
