/**
 * Created by Benny on 12.10.2014.
 */

"use strict";

var TB = TB || {};
TB.Control = TB.Control || {};

TB.Control.Appointment =  {
    index: function( params ) {
        TB.GUI.showLoader();
        var page = new TB.Page( 'appointment' ),
            pageData = [];

        TB.Service.request('Appointment', 'getList', {}, function (data) {
            TB.GUI.hideLoader();

            pageData = data;
            data.profile = TB.Client.profile;
            TB.GUI.show( page, data );

            // Content Big
            page.$container.find( 'table tbody tr').on( "click", "label.btn-disabled", function() {
                var $label = $( this),
                    appointmentId = $label.attr( 'data-appointment-id'),
                    status = $label.attr( 'data-label-type' ) == 'accept' ? 'accepted' : 'declined';

                TB.Service.request(
                    'Appointment',
                    'setAttendanceStatus',
                    { status: status, appointment_id: appointmentId, ext_result: true },
                    function( data ) {
                        if ( data.error )
                        {
                            TB.Ext.Alert.show(
                                'Zusagefrist abgelaufen',
                                data.appointment.feedback_deadline_notice
                            );
                        }
                        else
                        {
                            TB.Ext.Notification.show( 'Teilnahme Einstellung gespeichert.', TB.Ext.Notification.TYPE_SUCCESS );
                            if ( 'accept' == $label.attr( 'data-label-type' ) ) {
                                $label.parent( 'div').find( 'label[data-label-type="decline"]').removeClass( 'active').removeClass( 'btn-danger').addClass( 'btn-disabled' );
                                $label.addClass( 'btn-success').addClass( 'active').removeClass( 'btn-disabled' );
                            } else {
                                $label.parent( 'div').find( 'label[data-label-type="accept"]' ).removeClass( 'active').removeClass( 'btn-success' ).addClass( 'btn-disabled' );
                                $label.addClass( 'btn-danger').addClass( 'active').removeClass( 'btn-disabled' );
                            }
                            page.$container.find( 'span[data-accepted-label-id="' + appointmentId + '"]').html( data.ext_result.num_accepted );
                            page.$container.find( 'span[data-declined-label-id="' + appointmentId + '"]').html( data.ext_result.num_declined );
                        }
                    },
                    $( this )
                );
            });

            // Content Small
            page.$container.find( 'table tbody tr').on( "click", 'span[data-action="setstatus"].clickable', function() {

                var $span = $(this),
                    appointmentId = $span.attr( 'data-appointment-id'),
                    status = $span.attr( 'data-label-type' );

                TB.Service.request(
                    'Appointment',
                    'setAttendanceStatus',
                    { status: status, appointment_id: appointmentId, ext_result: false },
                    function( data ) {
                        if ( data.error ) {
                            TB.Ext.Alert.show(
                                'Zusagefrist abgelaufen',
                                data.appointment.feedback_deadline_notice
                            );
                        } else {
                            TB.Ext.Notification.show( 'Teilnahme Einstellung gespeichert.', TB.Ext.Notification.TYPE_SUCCESS );
                            if ( 'accepted' == status ) {
                                $span.addClass( 'label-success').removeClass( 'clickable' );
                                $span.parent( 'td').find( 'span[data-label-type="declined"]').removeClass( 'label-danger').addClass( 'clickable' );
                            } else {
                                $span.addClass( 'label-danger').removeClass( 'clickable' );
                                $span.parent( 'td' ).find( 'span[data-label-type="accepted"]').removeClass( 'label-success').addClass( 'clickable' );
                            }
                            page.$container.find( 'span[data-accepted-label-id="' + appointmentId + '"]').html( data.ext_result.num_accepted );
                            page.$container.find( 'span[data-declined-label-id="' + appointmentId + '"]').html( data.ext_result.num_declined );
                        }
                    },
                    $( this )
                );

                return false;

            });


            page.$container.find( 'button[data-id="btn_appointment_create_match"]').click( function() {
                TB.Controller.do( 'Appointment', 'create_match' );
            });

            page.$container.find( '#btn-coach-help').click( function() {
                TB.GUI.showModal(
                    "Termine",
                    TB.Config.Content.helpHtml.termine
                );
            });

            page.$container.find( 'button[data-id="btn_appointment_export"]').click( function()
            {
                if ( TB.Premium.isPremium() )
                {
                    TB.Service.request( 'Team', 'load', { addPremium: true } , function( teamData ) {

                        var filename = TB.Client.getCurrentTeam().display_name + "-" + moment().format( 'D-M-Y' ),
                            appointmentDate, appointmentName, appointmentLocation, attendees,
                            fnGetAttendeeFirstname, fnGetAttendeeLastname,
                            config = {},
                            rows = [];

                        fnGetAttendeeFirstname = function( profileId )
                        {
                            var firstName = 'Unbekannt';

                            for ( var pi = 0; pi < teamData.profiles.length; pi++ )
                            {
                                if ( profileId == teamData.profiles[ pi ].id )
                                {
                                    firstName = teamData.profiles[ pi ].first_name;
                                    break;
                                }
                            }

                            return firstName;
                        };

                        fnGetAttendeeLastname = function( profileId )
                        {
                            var lastName = 'Unbekannt';

                            for ( var pi = 0; pi < teamData.profiles.length; pi++ )
                            {
                                if ( profileId == teamData.profiles[ pi ].id )
                                {
                                    lastName = teamData.profiles[ pi ].last_name;
                                    break;
                                }
                            }

                            return lastName;
                        };

                        //  Wann | Was | Wo | Vorname | Nachname | Mailadresse | Status | Status vom | Kommentar
                        rows.push(
                            [
                                { value : 'Wann', type : 'string' },
                                { value : 'Was', type : 'string' },
                                { value : 'Wo', type : 'string' },
                                { value : 'Vorname', type : 'string' },
                                { value : 'Nachname', type : 'string' },
                                { value : 'Status', type : 'string' },
                                { value : 'Status vom', type : 'string' },
                                { value : 'Kommentar', type : 'string' }
                            ]
                        );

                        for ( var ai = 0; ai < pageData.appointments.length; ai++ )
                        {
                            appointmentDate = TB.Utils.getDatetimeStringFromUnixTimestamp( pageData.appointments[ ai ].starttime );
                            appointmentName = TB.Utils.getAppointmentName( pageData.appointments[ ai ] );
                            appointmentLocation = pageData.appointments[ ai ].location;


                            if ( false === pageData.hasOwnProperty( 'attendees_' + pageData.appointments[ ai ].id ) )
                            {
                                continue;
                            }

                            attendees = pageData[ "attendees_" + pageData.appointments[ ai ].id ];

                            if ( 0 === attendees.length )
                            {
                                continue;
                            }

                            for ( var aai = 0; aai < attendees.length; aai++ )
                            {
                                rows.push(
                                    [
                                        { value : appointmentDate , type : 'string' },
                                        { value : appointmentName , type : 'string' },
                                        { value : appointmentLocation , type : 'string' },
                                        { value : fnGetAttendeeFirstname( attendees[ aai ].profile_id ) , type : 'string' },
                                        { value : fnGetAttendeeLastname( attendees[ aai ].profile_id ) , type : 'string' },
                                        { value : attendees[ aai ].status === "accepted" ? 'zugesagt' : 'abgesagt' , type : 'string' },
                                        { value : TB.Utils.getDatetimeStringFromUnixTimestamp( attendees[ aai ].last_update ) , type : 'string' },
                                        { value : attendees[ aai ].comment ? attendees[ aai ].comment : '' , type : 'string' }
                                    ]
                                )
                            }
                        }

                        //TB.Utils.exportToCsv( filename, rows, ',' );
                        config.filename = filename;
                        config.sheet = { data : rows };
                        zipcelx( config );
                    });
                }
                else
                {
                    TB.Premium.handleNoPremium();
                }
            });

            page.$container.find( 'button[data-id="btn_appointment_subscribe"]').click( function()
            {
                TB.Premium.callPremium( 'Appointment', 'subscribe' );
            });


            page.$container.find( 'button[data-id="btn_appointment_create_other"]').click( function() {
                TB.Controller.do( 'Appointment', 'create_other' );
            });

            page.$container.find( 'button[data-id="btn-show-old-appointments"]').click( function() {
                if ( TB.Premium.isPremium() )
                {
                    $(this).blur();
                    $(this).find( 'i.glyphicon-chevron-right').toggle();
                    $(this).find( 'i.glyphicon-chevron-down').toggle();
                    if ( page.$container.find( '.specialContentSmall').is( ":visible" ) ) {
                        page.$container.find( '#appointment-table-old-appointment-small').slideToggle("slow");
                    } else {
                        page.$container.find( '#appointment-table-old-appointment').slideToggle("slow");
                    }
                }
                else
                {
                    TB.Premium.handleNoPremium();
                }
            });

            // Create new match appointment
            page.$container.find('#btn_appointment_save_match').click( function () {
                if ( !TB.GUI.performFormValidation( $( '#form_new_appointment_match' ) ) ) {
                    return false;
                }

                var props = $( '#form_new_appointment_match').serializeObject();
                props.starttime = TB.Utils.getUnixTimestampFromDatetimeString( props.starttime );
                TB.Service.request(
                    'Appointment',
                    'create',
                    props,
                    function() {
                        TB.Ext.Notification.show( 'Spieltermin erstellt.', TB.Ext.Notification.TYPE_SUCCESS );
                        // Reload
                        TB.Controller.do( 'Appointment', 'index' )
                    },
                    $( this )
                );

                // Dont do FORM post
                return false;
            });

            // Create new other appointment
            page.$container.find('#btn_appointment_save_other').click( function () {
                if ( !TB.GUI.performFormValidation( $( '#form_new_appointment_other' ) ) ) {
                    return false;
                }

                var props = $( '#form_new_appointment_other').serializeObject();
                props.starttime = TB.Utils.getUnixTimestampFromDatetimeString( props.starttime );
                TB.Service.request(
                    'Appointment',
                    'create',
                    props,
                    function() {
                        TB.Ext.Notification.show( 'Termin erstellt.', TB.Ext.Notification.TYPE_SUCCESS );
                        // Reload
                        TB.Controller.do( 'Appointment', 'index' )
                    },
                    $( this )
                );

                // Dont do FORM post
                return false;
            });
        });

    },

    subscribe : function( params )
    {
        TB.GUI.showLoader();
        var page = new TB.Page( 'appointment_subscribe' ),
            pageData = [],
            fnCopyToClipboard = function( $elem ) {
                var input = $elem.get(0);
                var isiOSDevice = navigator.userAgent.match(/ipad|iphone/i);

                if (isiOSDevice) {

                    var editable = input.contentEditable;
                    var readOnly = input.readOnly;

                    input.contentEditable = true;
                    input.readOnly = false;

                    var range = document.createRange();
                    range.selectNodeContents(input);

                    var selection = window.getSelection();
                    selection.removeAllRanges();
                    selection.addRange(range);

                    input.setSelectionRange(0, 999999);
                    input.contentEditable = editable;
                    input.readOnly = readOnly;

                } else {
                    input.select();
                }

                return document.execCommand('copy');
            };

        TB.Service.request( 'Appointment', 'subscribe', {}, function (data) {
            TB.GUI.hideLoader();

            pageData = data;
            pageData.profile = TB.Client.profile;
            TB.GUI.show( page, pageData );

            page.$container.find('[data-id="btn-copy-ics-team"]').click(function ()
            {
                var copyResult = fnCopyToClipboard( page.$container.find('[data-id="tbuddy-ics-team"]').first() ),
                    html = '<p>Die URL zu deinem Kalender befindet sich nun im Zwischenspeicher.</p><p>Gehe nun in die Kalenderapp deiner Wahl und importiere dort den Kalender.</p><p><b>Tipp</b></p><p>Schau in unsere Hilfe für weitere Tipps</p>';
                if (false === copyResult) {
                    html = '<p>Drücke STRG+C, um die URL zum Kalender in den Zwischenspeicher zu kopieren.</p><p>Gehe nun in die Kalenderapp deiner Wahl und importiere dort den Kalender.</p><p><b>Tipp</b></p><p>Schau in unsere Hilfe für weitere Tipps</p>';
                }
                TB.Ext.Alert.modal({
                    title: 'Kalender URL kopiert',
                    html: html,
                    showCancelButton: false,
                    confirmButtonColor: '#048DBF',
                    type: 'success'
                });
            });

            page.$container.find('[data-id="btn-copy-ics-team-profile"]').click(function ()
            {
                var copyResult = fnCopyToClipboard( page.$container.find('[data-id="tbuddy-ics-team-profile"]').first() ),
                    html = '<p>Die URL zu deinem Kalender befindet sich nun im Zwischenspeicher.</p><p>Gehe nun in die Kalenderapp deiner Wahl und importiere dort den Kalender.</p><p><b>Tipp</b></p><p>Schau in unsere Hilfe für weitere Tipps</p>';
                if (false === copyResult) {
                    page.$container.find('[data-id="tbuddy-ics-team-profile"]').first().removeAttr( 'readonly' );
                    page.$container.find('[data-id="tbuddy-ics-team-profile"]').first().select();
                    html = '<p>Drücke STRG/CMD+C, um die URL zum Kalender in den Zwischenspeicher zu kopieren.</p><p>Gehe nun in die Kalenderapp deiner Wahl und importiere dort den Kalender.</p><p><b>Tipp</b></p><p>Schau in unsere Hilfe für weitere Tipps</p>';
                }
                TB.Ext.Alert.modal({
                    title: 'Kalender URL kopiert',
                    html: html,
                    showCancelButton: false,
                    confirmButtonColor: '#048DBF',
                    type: 'success'
                });
            });


        });

    },

    create_match : function( params ) {
        TB.GUI.showLoader();
        var page = new TB.Page( 'appointment_create_match' ),
            pageData = [];


        TB.Service.request('Team', 'getCurrent', { including_members : true }, function (data) {
            TB.GUI.hideLoader();
            pageData = data;

            var isAllowed = true;

            if ( data.team.active_premium_package === TB.Premium.PACKAGE_STANDARD &&
                 data.team.created_ts < ( moment().unix() - (86400 * 60) ) &&
                 data.team_members.length > 10 )
            {
                isAllowed = false;
            }

            data.isAllowed = isAllowed;
            TB.GUI.show(page, data);



            $('[data-toggle="tooltip"]').tooltip();

            page.$container.find('#btn_appointment_save_match_cancel').click(function () {
                TB.Controller.do('Appointment', 'index');
            });

            page.$container.find('button[data-use="teamshortlink"]').click(function () {
                $(this).blur();
                var $input = $(this).parent().next('input');
                if ('' == $input.val()) {
                    $input.val( pageData.team.display_name );
                    $input.focus();
                    $input.blur();
                } else {
                    $input.val('');
                    $input.focus();
                    $input.blur();
                }
            });

            // Create new match appointment
            page.$container.find('#btn_appointment_save_match').click(function () {
                if (!TB.GUI.performFormValidation($('#form_new_appointment_match'))) {
                    return false;
                }

                var props = $('#form_new_appointment_match').serializeObject();
                props.starttime = TB.Utils.getUnixTimestampFromDatetimeString(props.starttime);
                TB.Service.request(
                    'Appointment',
                    'create',
                    props,
                    function () {
                        TB.Ext.Notification.show('Spieltermin erstellt.', TB.Ext.Notification.TYPE_SUCCESS);
                        // Reload
                        TB.Controller.do('Appointment', 'index')
                    },
                    $(this)
                );

                // Dont do FORM post
                return false;
            });
        });

    },

    create_other : function( params ) {

        TB.GUI.showLoader();

        var page = new TB.Page( 'appointment_create_other' ),
            pageData = [];

        TB.Service.request('Team', 'getCurrent', { including_members : true }, function (data) {
            TB.GUI.hideLoader();
            pageData = data;

            var isAllowed = true;

            if (data.team.active_premium_package === TB.Premium.PACKAGE_STANDARD &&
                data.team.created_ts < (moment().unix() - (86400 * 60)) &&
                data.team_members.length > 10) {
                isAllowed = false;
            }

            data.isAllowed = isAllowed;

            TB.GUI.show(page, data);

            page.$container.find('#btn_appointment_save_other_cancel').click(function () {
                TB.Controller.do('Appointment', 'index');
            });

            page.$container.find('input[type="radio"][name="frequency"]').change(function () {
                page.$container.find('div[data-id="frequency-serial-details"]').slideToggle("slow");
            });

            // Create new other appointment
            page.$container.find('#btn_appointment_save_other').click(function () {
                if (!TB.GUI.performFormValidation($('#form_new_appointment_other'))) {
                    return false;
                }

                var props = $('#form_new_appointment_other').serializeObject(), action = 'create';
                props.starttime = TB.Utils.getUnixTimestampFromDatetimeString(props.starttime);

                if ("serial" === props.frequency) {
                    action = 'createSerial'
                }

                TB.Service.request(
                    'Appointment',
                    action,
                    props,
                    function () {
                        TB.Ext.Notification.show('Termin erstellt.', TB.Ext.Notification.TYPE_SUCCESS);
                        // Reload
                        TB.Controller.do('Appointment', 'index')
                    },
                    $(this)
                );

                // Dont do FORM post
                return false;
            });

        });
    },

    detail : function( params ) {
        TB.GUI.showLoader();
        var page = new TB.Page( 'appointment_detail'),
            pageData = [];

        TB.Service.request('Appointment', 'getDetail', { appointment_id: params.appointment_id }, function (data) {
            var createCalendarLinks,
                canSetStatus = ( (data.appointment.starttime ) > TB.Utils.getUnixTimestamp() );

            // Prepare data
            data.listAccepted = [],
            data.listUndecided = [],
            data.listDeclined = [];

            $.each( data.profiles, function( i, p ) {
                p.orig_status = p.status;
                p.status = null;
                p.comment = null;

                $.each( data.attendees, function( j, a ) {
                    if ( a.profile_id == p.id ) {
                        p.status = a.status;
                        p.comment = a.comment;
                        p.last_update = a.last_update;
                        p.last_accepted_ms = ( a.last_accepted !== null ) ? moment(a.last_accepted).toDate().getTime() : null;
                        return false;
                    }
                });

                if ( p.status == 'accepted' ) {
                    data.listAccepted.push( p );
                } else  if ( p.status == 'declined' ) {
                    data.listDeclined.push( p );
                } else {
                    // Only add to list if not a fan
                    if ( !TB.GUI.isFan(  p ) ) {
                        data.listUndecided.push( p );
                    }
                }

            });

            data.listAccepted = data.listAccepted.sort( function( a, b ) {
                if ( a.last_accepted_ms == null && b.last_accepted_ms == null ) {
                    return 0;
                } else if ( a.last_accepted_ms == null ) {
                    return 1;
                } else if ( b.last_accepted_ms == null ) {
                    return -1;
                } else {
                    return  a.last_accepted_ms - b.last_accepted_ms;
                }
            });

            TB.GUI.hideLoader();
            // Create calendarLinks
            createCalendarLinks = TB.Utils.createCalendar( {
                title: (( data.appointment.subject ) ? data.appointment.subject : data.appointment.home + ':' + data.appointment.guest),
                start : TB.Utils.getDateFromUnixTimestamp( data.appointment.starttime ),
                duration : data.appointment.duration,
                address : data.appointment.location,
                description : data.appointment.comment
            });
            data.addToCalendarLinks = createCalendarLinks;
            data.canSetStatus = canSetStatus;
            TB.GUI.show(page, data);

            page.$container.find( '#btn_edit_appointment').click( function() {
                TB.Controller.do( 'Appointment', 'edit', { appointment_id: params.appointment_id } );
            });

            page.$container.find( '#btn_delete_appointment').click( function() {
                TB.Ext.Alert.modal({
                    title: 'Diesen Termin wirklich löschen?'
                }, function() {
                    TB.Controller.do('Appointment', 'delete', { appointment_id: params.appointment_id } );
                });
            });

            page.$container.find( '#btn_appointment_reminder').click( function() {

                if ( !data || !data.listUndecided || 0 == data.listUndecided ) {
                    TB.Ext.Notification.show( 'Alle Buddies haben bereits zu- oder abgesagt.', TB.Ext.Notification.TYPE_INFO );
                    return false;
                }

                TB.Ext.Alert.modal({
                    title: 'Erinnerung senden?',
                    text : 'Möchtest du wirklich allen ausstehenden Buddies eine Erinnerung via Email senden?'
                }, function() {
                    TB.Service.request(
                        'Appointment',
                        'sendReminder',
                        {
                            appointment_id : data.appointment.id
                        },
                        function() {
                            TB.Ext.Notification.show( 'Erinnerung verschickt.', TB.Ext.Notification.TYPE_SUCCESS );
                            // Reload
                            TB.Controller.do( 'Appointment', 'detail', { appointment_id: data.appointment.id  } )
                        },
                        $( this )
                    );

                });

            });

            page.$container.find( '[data-id="btn-whats-app-reminder"]' ).click( function()
            {
                if ( !TB.Env.isMobile() )
                {
                    TB.Ext.Notification.show( 'Diese Funktion kann nur auf mobilen Geräten verwendet werden, die WhatsApp installiert haben', TB.Ext.Notification)
                    return false;
                }
            });

            page.$container.find( '#btn_pdf_export').click( function() {
                TB.Ext.PDF.downloadAppointment( data );
                return false;
            });

            page.$container.find( '#btn_edit_appointment_attendees').click( function() {
                TB.Premium.callPremium( 'Appointment', 'edit_attendees', { appointment_id: params.appointment_id } );
                return false;
            });

            page.$container.find( '#btn_set_attendee_status').click( function() {
                var appointmentId = $( this).attr( 'data-appointment-id'),
                    comment = $( '#comment').val(),
                    status = ( $( '#form_appointment_attendance label.active').attr( 'data-label-type') == 'accept' ) ? 'accepted' : 'declined';

                if ( !( $( '#form_appointment_attendance label.active').attr( 'data-label-type') == 'accept' ) &&
                     !( $( '#form_appointment_attendance label.active').attr( 'data-label-type') == 'decline' ) ) {
                    return false;
                }

                TB.Service.request(
                    'Appointment',
                    'setAttendanceStatus',
                    { appointment_id: appointmentId, comment: comment, status: status },
                    function( data ) {
                        if ( data.error ) {
                            TB.Ext.Alert.show(
                                'Zusagefrist abgelaufen',
                                data.appointment.feedback_deadline_notice
                            );
                        } else {
                            TB.Ext.Notification.show( 'Teilnahme Einstellung gespeichert.', TB.Ext.Notification.TYPE_SUCCESS );
                            TB.Controller.reload();
                        }
                    },
                    $( this )
                );
                return false;
            });

            page.$container.find( '#form_appointment_attendance').on( "click", "label.btn-disabled", function() {
                var $label = $( this),
                    appointmentId = $label.attr( 'data-appointment-id'),
                    status = $label.attr( 'data-label-type' ) == 'accept' ? 'accepted' : 'declined';
                if ( 'accept' == $label.attr( 'data-label-type' ) ) {
                    $label.parent( 'div').find( 'label[data-label-type="decline"]').removeClass( 'active').removeClass( 'btn-danger').addClass( 'btn-disabled' );
                    $label.addClass( 'btn-success').addClass( 'active').removeClass( 'btn-disabled' );
                } else {
                    $label.parent( 'div').find( 'label[data-label-type="accept"]' ).removeClass( 'active').removeClass( 'btn-success' ).addClass( 'btn-disabled' );
                    $label.addClass( 'btn-danger').addClass( 'active').removeClass( 'btn-disabled' );
                }
            });
        });
    },

    reminder : function( params ) {




        return false;

        TB.GUI.showLoader();
        var page = new TB.Page( 'appointment_send_reminder'),
            pageData = [];

        TB.Service.request('Appointment', 'getReminder', { appointment_id: params.appointment_id }, function (data) {
            TB.GUI.hideLoader();
            pageData = data;
            TB.GUI.show(page, data);

            page.$container.find( '#btn_appointment_reminder_cancel').click( function() {
                TB.Controller.do( 'Appointment', 'detail', { appointment_id: pageData.appointment.id } );
            });

            page.$container.find( '#btn_appointment_reminder_submit').click( function() {
                if ( !TB.GUI.performFormValidation( $( '#form_appointment_edit' ) ) ) {
                    return false;
                }

                var props = $( '#form_appointment_send_reminder').serializeObject();

                TB.Service.request(
                    'Appointment',
                    'sendReminder',
                    props,
                    function() {
                        TB.Ext.Notification.show( 'Erinnerung verschickt.', TB.Ext.Notification.TYPE_SUCCESS );
                        // Reload
                        TB.Controller.do( 'Appointment', 'detail', { appointment_id: pageData.appointment.id  } )
                    },
                    $( this )
                );

                // Dont do FORM post
                return false;

            });


        });

    },

    delete : function( params ) {
        TB.Service.request(
            'Appointment',
            'delete',
            { appointment_id: params.appointment_id },
            function (data) {
                TB.Ext.Notification.show( 'Termin erfolgreich gelöscht.', TB.Ext.Notification.TYPE_SUCCESS );

                TB.Controller.do( 'Appointment' );
            },
            $( '#btn_delete_appointment' )
        );
    },

    edit : function( params ) {
        TB.GUI.showLoader();
        var page = new TB.Page( 'appointment_edit' ),
            pageData = [];

        TB.Service.request('Appointment', 'getDetail', { appointment_id: params.appointment_id }, function (data) {
            TB.GUI.hideLoader();
            pageData = data;
            TB.GUI.show(page, data);

            page.$container.find( '#btn_update_appointment_cancel').click( function() {
                TB.Controller.do( 'Appointment', 'detail', { appointment_id: params.appointment_id } );
            });

            page.$container.find( '#btn_update_appointment').click( function() {
                if ( !TB.GUI.performFormValidation( $( '#form_appointment_edit' ) ) ) {
                    return false;
                }

                var props = $( '#form_appointment_edit').serializeObject();
                props.starttime = TB.Utils.getUnixTimestampFromDatetimeString( props.starttime );

                TB.Service.request(
                    'Appointment',
                    'update',
                    props,
                    function() {
                        TB.Ext.Notification.show( 'Termin geändert.', TB.Ext.Notification.TYPE_SUCCESS );
                        // Reload
                        TB.Controller.do( 'Appointment', 'detail', { appointment_id: props.id } )
                    },
                    $( this )
                );

                // Dont do FORM post
                return false;

            });
        });
    },

    edit_attendees : function( params ) {
        TB.GUI.showLoader();
        var page = new TB.Page( 'appointment_edit_attendees');

        TB.Service.request('Appointment', 'getDetail', { appointment_id: params.appointment_id }, function (data) {
            var appointmentId = data.appointment.id;
            TB.GUI.hideLoader();

            $.each( data.profiles, function( i, p ) {
                p.status = null;
                p.comment = null;

                $.each( data.attendees, function( j, a ) {
                    if ( a.profile_id == p.id ) {
                        p.status = a.status;
                        p.comment = a.comment;
                        p.last_update = a.last_update;
                        return false;
                    }
                });
            });

            TB.GUI.show(page, data);

            $( 'td[data-title="Status"]' ).find( 'span.label' ).on( "click", function() {
                var $span = $(this);
                TB.Service.request( 'Appointment', 'setAttendanceStatusByTrainer', {
                    appointment_id : appointmentId,
                    profile_id : $(this).closest( "tr").attr( "data-profile_id"),
                    status : $(this).attr( "data-status" )
                }, function() {
                    TB.Ext.Notification.show( "Status erfolgreich geändert.", TB.Ext.Notification.TYPE_SUCCESS );
                    if ( "accepted" === $span.attr( "data-status") ) {
                        $span.toggleClass( "label-success" );
                        $span.next( "span.label").removeClass( "label-danger" );
                    } else {
                        $span.toggleClass( "label-danger" );
                        $span.prev( "span.label").removeClass( "label-success" );
                    }
                });
            });
        });
    }
};