$(function(){
    // Put some initial data
    $('#courses_index').data('calendar_current_month', 0);
    $('#courses_index').data('calendar_current_category', 0);
    $('#courses_index').data('calendar_current_course', 0);

    // Hide info and picker
    $('#courseinfo').hide();
    $('#coursepicker').hide();
    $('#categoryinfo').hide();

    // Refresh calendar
    refreshCalendar();

    // FIREBUG
    //$().log('Loaded firebug module');

    // Bind some flashy effects to calendar prev and next
    $('.calendar-next, .calendar-prev').hover(
        function(){
            $(this).addClass('ui-state-hover');
        },
        function(){
            $(this).removeClass('ui-state-hover');
        }
        )
        .mousedown(function(){
            $(this).addClass('ui-state-active');
        })
        .mouseup(function(){
            $(this).removeClass('ui-state-active');
        })
        .mouseout(function(){
            $(this).removeClass('ui-state-active');
        });

    // Bind some flashy effects to highligted calendar days
    $('.calendar-activeday').hover(calendar_mouseover, calendar_mouseout);

    // Unbind all flashy effects from normal days
    $('.calendar-table .ui-state-default')
        .unbind('mouseover')
        .unbind('mouseout')
        .unbind('mousedown')
        .unbind('mouseup');
    
    // Create course category select
    $('#select_courseCategory')
    	.selectmenu({
    		style: 'dropdown',
    		width: 255
    	})
    	.change(function() {
    		// Save setting
    		$('#courses_index').data('calendar_current_category', $(this).val());

    		// Refresh calendar
    	    refreshCalendar();
    	});
});

function calendar_mouseover() {
    // Get courses array from the active day
    var courses = $(this).data('courses');
    // FIREBUG
    //$(this).log('calendar_mouseover: triggered');
    var cur_course = 0;

    // Create func so we can trigger it emidiately
    var hightlight_func = function() {
        // Reset hightlights
        $('.calendar-activeday').each(function() {
            $(this).addClass('ui-state-highlight');
            $(this).removeClass('ui-state-hover');
        });

        // Store current course id
        var course_id = parseInt(courses[cur_course], 10);
        // Itterate through all active days and highlight those that got this course
        $('.calendar-activeday').each(function() {
            // If the course id is stored in the active day then highlight
            if(0 <= $.inArray(course_id, $(this).data('courses'))) {
                $(this).addClass('ui-state-hover');
                $(this).removeClass('ui-state-highlight');
            }
        });
        // add cur_course with one, if it goes pass courses.length then back to 0
        cur_course = (cur_course == ($(courses).length - 1)) ? 0 : cur_course + 1;
    };

    // Check so we don't loop on only one course
    if($(courses).length > 1) {
        // FIREBUG
        //$(this).log('calendar_mouseover: rotation highlight');
        // Make highlight
        hightlight_func();
        // Itterate through all courses with 1sec delay
        $('#courses_index').everyTime('1s','course_hightlight_switch', hightlight_func);
    } else {
        // FIREBUG
        //$(this).log('calendar_mouseover: singel highlight');
        // Make hightlight
        hightlight_func();
    }
}

function calendar_mouseout() {
    // FIREBUG
    //$(this).log('calendar_mouseout: triggered');
    // Stop timer for course highlight rotation if active
    $('#courses_index').stopTime('course_hightlight_switch');
    // Switch from hover to highlightstate for all active days
    $('.calendar-activeday').each(function() {
        $(this).addClass('ui-state-highlight');
        $(this).removeClass('ui-state-hover');
    });
}

function calendar_prev() {
    // Subtract one from current month
    $('#courses_index').data('calendar_current_month', $('#courses_index').data('calendar_current_month') - 1);
    refreshCalendar()
}

function calendar_next() {
    // Add one to current month
    $('#courses_index').data('calendar_current_month', $('#courses_index').data('calendar_current_month') +1);
    refreshCalendar();
}

function refreshCalendar() {
    // Show progress overlay
    $('.calpro').show();
    $.ajax({
        type: 'GET',
        url: $('#courses_index').data('settings')['coursesbaseurl']+"/xmlcalendar/"+$('#courses_index').data('calendar_current_category')+"/"+ $('#courses_index').data('calendar_current_month'),
        dataType: 'xml',
        error: function (xhr, desc, exceptionobj) {
            alert(desc);
        },
        success: function(xml) {
            var calendar = $(xml).find('calendar');
            
            // Check so the request offset month is the same as current month.
            if($(calendar).find('left').attr('offset') != $('#courses_index').data('calendar_current_month'))
                return true;
            
            // Get language for the calendar
            var langmonths = $('#courses_index').data('settings')['lang']['months'];
            
            // Set titles
            $('.calendar-title-left').text(langmonths[$(calendar).find('left').attr('month')] + " " + $(calendar).find('left').attr('year'));
            $('.calendar-title-right').text(langmonths[$(calendar).find('right').attr('month')] + " " + $(calendar).find('right').attr('year'));

            // Clear calendar from styles and events (we let the data be)
            $('#calleft td, #calright td').each(function() {
                $(this).text('').removeClass('ui-state-default calendar-activeday ui-state-highlight')
                    .unbind('mouseover')
                    .unbind('mouseout')
                    .unbind('mousedown');
            });

            var sides = new Array('left', 'right');

            for(var i in sides) {
                // Populate left calendar
                $(xml).find('boxes').find(sides[i]).find('box').each(function() {
                    var curbox = $('#cal' + sides[i] +' td').eq($(this).attr('id'));
                    $(curbox).text($(this).attr('date'));

                    // Create new array for courses
                    var courses = new Array();

                    // Push courses to the array
                    $(this).find('course').each(function() {
                       courses.push(parseInt($(this).attr('id'), 10));
                    });
                    
                    // If there are any courses then save data to the box and apply classes
                    if(courses.length > 0) {
                        // Add course array to data for the box (td)
                        $(curbox).data('courses', courses)
                            .addClass('ui-state-highlight')
                            .addClass('calendar-activeday')
                            .bind('mouseover', calendar_mouseover)
                            .bind('mouseout', calendar_mouseout)
                            .bind('mousedown', showCourseInfo);

                        // FIREBUG
                        //$(curbox).log('refreshCalendar: ('+sides[i]+':'+ $(this).attr('id') + ') added courses, events and style');
                        //$(courses).log('refreshCalendar: ('+sides[i]+':'+ $(this).attr('id') + ') coursedata');
                    } else {
                        // Add style for empty day
                        $(curbox).addClass('ui-state-default');
                    }
                });
            }
            // Hide progress overlay
            $('.calpro').hide();
        }
    });
}

function showCourseInfo() {
    // FIREBUG
    //$(this).log('showCourseInfo: ' + $(this).data('courses')[0]);
    // Hide the coursepicker and courseinfo
    $('#coursepicker').hide();
    $('#courseinfo').hide();
    
    // Set current course
    $('#courses_index').data('calendar_current_course', $(this).data('courses')[0]);
    
    // If more than one course then coursepicker
    if($(this).data('courses').length > 1) {
        // This day have more than one course, show the course picker with all courses
        // Get the course ids and parse it into a url string
        //var courses = $(this).data('courses');
        var courses = $(this).data('courses');
        var strcourses = '';
        for(var i in courses) {
            strcourses += '/' + courses[i];
        }
        
        // Empty the coursepicker-table
        $('#coursepicker-table li').remove();
        
        $.ajax({
            type: "GET",
            url: $('#courses_index').data('settings')['coursesbaseurl']+"/xmlview" + strcourses,
            success: function(xml) {
                // Get language
                var lang = $('#courses_index').data('settings')['lang'];

                // Itterate over all courses
                $(xml).find('course').each(function() {
                    var course = this;
                    var row = '<li class="course-select ui-widget-content">';

                    // Add Course category name
                    row += '<b>' + $(course).find('category').find('name').text() + ' - ';

                    if(parseInt($(course).find('numparticipants').text()) >= parseInt($(course).find('maxparticipants').text())) {
                        // Course is full
                        row += 'Kursen &auml;r full</b>';
                    } else {
                        // There are still spots on the course, show how many.
                        row += $(course).find('numparticipants').text() + ' / ' + $(course).find('maxparticipants').text() + ' deltagare</b>';
                    }
                    row += '<ul>';
                    // Add occasions to the row
                    $(course).find('occasions').find('occasion').each(function () {
                        var d = new Date($(this).find('date').text());
                        row += '<li>' + lang['days'][d.getDay()] + ' <i>(' + d.getDate() + ' '+ lang['months'][d.getMonth() + 1] + ')</i>'
                            + ' '
                            + $(this).find('from').text()
                            + ' - '
                            + $(this).find('to').text() +'</li>';
                    });
                    row += '</ul>'
                    row += '</li>';
                    $('#coursepicker-table').append(row);

                    // Add course id to row data
                    var courseid = new Array();
                    courseid[0] = $(course).attr('id');
                    $('#coursepicker-table li.course-select:last').data('courses', courseid)
                            .bind('mouseover', calendar_mouseover)
                            .bind('mouseout', calendar_mouseout)
                            .bind('mousedown', showCourseInfo)
                            .hover(
                                function(){
                                    $(this).addClass('ui-state-hover');
                                },
                                function(){
                                    $(this).removeClass('ui-state-hover');
                                }
                                );

                });

                // Show courseinfo window
                $('#coursepicker').show();
            }
        });
    } else {
        showCourse($('#courses_index').data('calendar_current_course'));
    }
}

function showCourse(id) {
	$.ajax({
        type: "GET",
        url: $('#courses_index').data('settings')['coursesbaseurl']+"/xmlview/" + id,
        success: function(xml) {
            //FIREBUG
            //$(this).log('Course id: ' + $(xml).find('course').attr('id'));
            // Set id
            $('#FormCourseId').val($(xml).find('course').attr('id'));
            
            // Check if there are any spots left
            if(parseInt($(xml).find('numparticipants').text()) >= parseInt($(xml).find('maxparticipants').text())) {
                // Course is full, lets hide the add to cart button
                $('#FormCourseParticipants').html('<b>Kursen &auml;r full</b>');
                $('#FormAddtoCart').hide();
            } else {
                // There are still spots on the course, show how many.
                $('#FormCourseParticipants').html($(xml).find('numparticipants').text() + ' / ' + $(xml).find('maxparticipants').text());
                $('#FormAddtoCart').show();
            }

            // Set Course category name
            $('#FormCourseCategoryName').html($(xml).find('course').find('category').find('name').text());
            $('#categoryinfo-name').html($(xml).find('course').find('category').find('name').text());
            $('#categoryinfo-description').html($(xml).find('course').find('category').find('description').text());

            // Set Course instructor
            $('#FormCourseInstructor').html('<a href="http://www.vindsurfing.se/dynpages/view/6">'+$(xml).find('course').find('instructor').text()+'</a>');

            // Set Course price
            $('#FormCoursePrice').html($(xml).find('course').find('price').text()+',00 kr');

            var lang = $('#courses_index').data('settings')['lang'];

            // Set Occasions
            $('#FormCourseOccasions').html('');
            $(xml).find('occasions').find('occasion').each(function () {
                var d = new Date($(this).find('date').text());
                
                $('#FormCourseOccasions').append('<tr><td>'
                    + lang['days'][d.getDay()] + ' <i>(' + d.getDate() + ' '+ lang['months'][d.getMonth() + 1] + ')</i>'
                    + ' '
                    + $(this).find('from').text()
                    + ' - '
                    + $(this).find('to').text() +'</td></tr>');
            });

            // Show courseinfo window
            $('#courseinfo').show();
            $('#categoryinfo').show();
        }
    });
}

function addCoursetoCart() {
    if($('#CourseBookingPerson').text == "") {
        showMessage('Info', 'Var god fyll i namn');
    } else {
        $('#OrderAddForm').submit();
    }
}