// $Id: jquery_x.js 35 2010-02-22 17:14:56Z Ian.H $

$(function() {
    // Flash header image
    $('#flash-header').flash({
        src:    '_assets/flash/header.swf',
        width:  928,
        height: 292,
        wmode: 'transparent'
    });

    // Recognised school seaerch
    $('form#frm-search-rs').submit(function() {
        var searchSchool = false;

        // Check for empty search fields
        if ($('#school').val() != '') {
            $.ajax({
                url:            '/p_rs-search.php?option=school&school=' + $('#school').val() + '&ajax=0'
//                success:        function(data) {
//                    $('#search-results').html(data);
//                    $('#search-results').show();
//                }
            });

            searchSchool = true;
            return true;
        }

        if (!searchSchool) {
            if (($('#postcode').val() != '') && ($('#distance').val() != '')) {
                $.ajax({
                    url:            '/p_rs-search.php?option=postcode&postcode=' + $('#postcode').val() + '&distance=' + $('#distance').val()
    //                success:        function(data) {
    //                    $('#search-results').html(data);
    //                    $('#search-results').show();
    //                }
                });

                return true;
            }
        }

        return false;
    });

    // Member login
    $('#btn-member-login').click(function() {
        // Check for empty fields
        if (($('#username').val() == '') || ($('#passwd').val() == '')) {
            showAjaxError('Please enter your username and password.');

            if ($('#username').val() == '') {
                $('#username').focus();
            } else if ($('#passwd').val() == '') {
                $('#passwd').focus();
            }

            return false;
        } else {
            // Proceed to login
            var user = $('#username').val();
            var pass = $('#passwd').val();

            $.post('/p_login.php',
                {
                    ajax:           1,
                    username:       user,
                    passwd:         pass
                },
                function(data) {
                    if (data == '1') {
                        window.location = '/mcp/';
                    } else {
                        $('div.ajax-error-msg').html('Invalid credentials.');
                        $('div.ajax-error-msg').show();
                    }
                }
            );
        }
    });

    $('div.ajax-error-msg').click(function() {
        $(this).hide();
        $(this).empty();
    });

    $('.logout').click(function(e) {
        if (!confirm('Do you really want to logout?')) {
            e.preventDefault();
        }
    });

    // Member change passwd
    $('#btn-member-changepasswd').click(function() {
        if (($('#current-passwd').val() == '') || ($('#new-passwd').val() == '') || ($('#confirm-passwd') == '')) {
            showAjaxError('Please complete all fields.');

            if ($('#current-passwd').val() == '') {
                $('#current-passwd').focus();
            } else if ($('#new-passwd').val() == '') {
                $('#new-passwd').focus();
            } else if ($('#confirm-passwd').val() == '') {
                $('#confirm-passwd').focus();
            }

            return false;
        } else {
            // Check if new passwds match
            if ($('#new-passwd').val() != $('#confirm-passwd').val()) {
                showAjaxError('Your new passwords do not match.');
                return false;
            }

            // All good, check if current passwd matches
            $.post('/mcp/check-current-passwd.php',
                {
                    passwd:         $('#current-passwd').val()
                },
                function(data) {
                    if (data != '1') {
                        // Password doesn't match
                        showAjaxError('Your current password is incorrect.');
                    } else {
                        $.post('/mcp/p_change-passwd.php',
                            {
                                ajax:           1,
                                passwd:         $('#current-passwd').val(),
                                new_passwd:     $('#new-passwd').val(),
                                confirm_passwd: $('#confirm-passwd').val()
                            },
                            function(cpData) {
                                if (cpData == '1') {
                                    showAjaxError('Password updated successfully');

                                    $('#current-passwd').val('');
                                    $('#new-passwd').val('');
                                    $('#confirm-passwd').val('');
                                } else {
                                    showAjaxError('Password update failed.');
                                }

                                return false;
                            }
                        );
                    }

                    return false;
                }
            );
        }

        return false;
    });

    // Edit record
    $('.icon-edit').click(function() {
        var dataBits = $(this).attr('rel').split('|');

        if ($('tr#edit-' + dataBits[0] + '-' + dataBits[1]).length < 1) {
            if ($('tr.edit-row').length > 0) {
                closeEditRows();
                closeNewForms();
            }

            var script;

//            if (dataBits[0] == 'schools') {
//                script = 'ajax.edit-form';
//            } else {
//                script = 'ajax.edit-form-news';
//            }

            $.ajax({
                url:            '/mcp/ajax.edit-form.php?data=' + dataBits[0] + '&id=' + dataBits[1] + '&type=edit',
                success:        function(form) {
                    $('tr#' + dataBits[0] + '-' + dataBits[1]).after(form);
                }
            });
        }

        return false;
    });

    // Delete record
    $('.icon-delete').live('click', function() {
        var dataBits = $(this).attr('rel').split('|');

        if (confirm('Really delete this record?')) {
            $.ajax({
                url:            '/mcp/p_delete-record.php?data=' + dataBits[0] + '&id=' + dataBits[1],
                success:        function(data) {
                    if (data == '1') {
                        // Record deleted
                        if ($('tr#edit-' + dataBits[0] + '-' + dataBits[1]).length > 0) {
                            $('tr#edit-' + dataBits[0] + '-' + dataBits[1]).remove();
                        }

                        $('tr#' + dataBits[0] + '-' + dataBits[1]).remove();

                        alert('Record deleted');
                    } else {
                        alert('Record not deleted');
                    }
                }
            });
        }

        return false;
    });

    // Cancel edit record
    $('.icon-cancel').live('click', function() {
        var dataBits = $(this).attr('rel').split('|');

        if (dataBits[0] == 'school') {
            if (dataBits[1] == '') {
                // Resources
                if ($('.new-school-form').html() != '') {
                    $('.new-school-form').empty();
                }
            } else {
                $('tr#edit-' + dataBits[0] + '-' + dataBits[1]).remove();
            }
        } else if (dataBits[0] == 'notices') {
            $('div#notice-edit-' + dataBits[1]).hide();
            $('div#notice-edit-' + dataBits[1]).empty();
        } else if (dataBits[0] == 'news') {
            if (dataBits[1] == '') {
                // News
                if ($('.new-article-form').html() != '') {
                    $('.new-article-form').empty();
                }
            } else {
                $('tr#edit-news-' + dataBits[1]).remove();
            }
        } else if (dataBits[0] == 'res') {
            if (dataBits[1] == '') {
                // Resources
                if ($('.new-res-form').html() != '') {
                    $('.new-res-form').empty();
                }
            } else {
                $('tr#edit-' + dataBits[0] + '-' + dataBits[1]).remove();
            }
        }
        return false;
    });

    // Accept edit
    $('.icon-accept').live('click', function() {
        var dataBits = $(this).attr('rel').split('|');
        var formData = $('form#frm-edit-' + dataBits[0]).serialize();

        if (dataBits[0] == 'school') {
            $.post('/mcp/p_edit-schools.php',
                {
                    ajax:               1,
                    id:                 dataBits[1],
                    name:               $('#name').val(),
                    first_name:         $('#first-name').val(),
                    last_name:          $('#last-name').val(),
                    address:            $('#address').val(),
                    city:               $('#city').val(),
                    postcode:           $('#postcode').val(),
                    county:             $('#county').val(),
                    phone:              $('#phone').val(),
                    email:              $('#email').val(),
                    membership_status:  $('#membership-status').val(),
                    qualifications:     $('#qualifications').val()
                },
                function(data) {
                    if (data == '1') {
                        //$('div.form-edit-' + dataBits[0]).html('<div class="msgbox">Record updated.</div>');
                        setTimeout("showAjaxInlineMsgBox(dataBits[0], 'Record updated.')", 5000);
                        $('tr.edit-row').remove();

                        // Update table
                        $.ajax({
                            url:            '/mcp/ajax.list-schools.php',
                            success:        function(html) {
                                $('div#tbl-school').html(html);
                                alert('Record added');
                            }
                        });
                    } else {
                        setTimeout("showAjaxInlineMsgBox(dataBits[0], 'Record not updated.')", 1000);
                        $('tr.edit-row').remove();
                    }

                    return false;
                }
            );
        } else if (dataBits[0] == 'notices') {
            var fields = new Array(
                'action',
                'artformid',
                'title',
                'summary',
                'description',
                'name',
                'organisation',
                'address',
                'phone',
                'fax',
                'mobile',
                'url',
                'id'
            );
            var reqFields = new Array(
                'artformid',
                'title',
                'summary',
                'description',
                'name'
            );

            // Check for required fields
            for (var i = 0; i < reqFields.length; i++) {
                if ($('#' + reqFields[i]).val() == '') {
                    showAjaxError('Please complete all required fields.');
                    alert('Missing field: ' + reqFields[i]);
                    return false;
                }
            }

            $.post('/mcp/p_edit-notices.php',
                {
                    action:             $('#action').val(),
                    artformid:          $('#artformid').val(),
                    title:              $('#title').val(),
                    summary:            $('#summary').val(),
                    description:        $('#description').val(),
                    posted_by:          $('#posted-by').val(),
                    organisation:       $('#organisation').val(),
                    address:            $('#address').val(),
                    phone:              $('#phone').val(),
                    fax:                $('#fax').val(),
                    mobile:             $('#mobile').val(),
                    url:                $('#url').val(),
                    id:                 $('#id').val()
                },
                function(data) {
                    if (data == '1') {
                        // Update HTML data
//                        $('li.notice-title-' + dataBits[1]).html(($('#title').val() != '') ? $('#title').val() : '-');
                        $('li.notice-organisation-' + dataBits[1]).html('Organisation: ' + (($('#organisation').val() != '') ? $('#organisation').val() : '-'));
                        $('li.notice-address-' + dataBits[1]).html('Address: ' + (($('#address').val() != '') ? $('#address').val() : ''));
                        $('span.notice-phone-' + dataBits[1]).html('Tel: ' + (($('#phone').val() != '') ? $('#phone').val() + '&nbsp;&nbsp;' : '-'));
                        $('span.notice-fax-' + dataBits[1]).html('Fax: ' + (($('#fax').val() != '') ? $('#fax').val() + '&nbsp;&nbsp;' : '-'));
                        $('span.notice-mobile-' + dataBits[1]).html('Mobile: ' + (($('#mobile').val() != '') ? $('#mobile').val() + '&nbsp;&nbsp;' : '-'));
                        $('li.notice-email-' + dataBits[1]).html('Email: ' + (($('#email').val() != '') ? $('#email').val() : '-'));
                        $('li.notice-url-' + dataBits[1]).html('Web: ' + (($('#url').val() != '') ? $('#url').val() : '-'));
                        $('li.notice-description-' + dataBits[1]).html(($('#description').val() != '') ? $('#description').val() : '-');

                        $('div#notice-edit-' + dataBits[1]).hide();
                        $('div#notice-edit-' + dataBits[1]).empty();
                    } else {
                        showAjaxError('Record not changed.');
                        return false;
                    }
                }
            );
        } else if (dataBits[0] == 'notices-new') {
            var fields = new Array(
                'artformid',
                'title',
                'summary',
                'description',
                'name',
                'organisation',
                'address',
                'phone',
                'fax',
                'mobile',
                'url'
            );
            var reqFields = new Array(
                'artformid',
                'title',
                'summary',
                'description',
                'name'
            );

            // Check for required fields
            for (var i = 0; i < reqFields.length; i++) {
                if ($('#' + reqFields[i]).val() == '') {
                    showAjaxError('Please complete all required fields.');
                    return false;
                }
            }

            $.post('/p_new-notice.php',
                {
                    action:             $('#action').val(),
                    artformid:          $('#artformid').val(),
                    title:              $('#title').val(),
                    summary:            $('#summary').val(),
                    description:        $('#description').val(),
                    posted_by:          $('#posted-by').val(),
                    organisation:       $('#organisation').val(),
                    address:            $('#address').val(),
                    phone:              $('#phone').val(),
                    fax:                $('#fax').val(),
                    mobile:             $('#mobile').val(),
                    url:                $('#url').val()
                },
                function(data) {
                    if (data == '1') {
                        alert('Your notice has been submitted and is awaiting admin moderation.');
                        window.location.href = '../noticeboard/';
                    } else {
                        alert('Your notice failed to post!');
                    }
                }
            );
        } else if (dataBits[0] == 'news') {
            $.post('/mcp/p_edit-news.php',
                {
                    id:                 $('#id').val(),
                    cat_id:             $('#cat-id').val(),
                    subject:            $('#subject').val(),
                    body:               $('#body').val(),
                    archived:           ($('#archived:checked').val() == '1') ? 1 : 0,
                    auto_archive:       ($('#auto-archive:checked').val() == '1') ? 1 : 0,
                    action:             $('#action').val()
                },
                function(data) {
                    if ($('#action').val() == 'edit') {
                        if (data == '1') {
                            $('tr#news-' + dataBits[1] + ' td.col-auto').html($('#subject').val());
                            $('tr.edit-row').remove();
                        }
                    } else if ($('#action').val() == 'new') {
                        data = parseInt(data);

                        if (data > 0) {
                            $('div.new-article-form').empty();
                            window.location.href = '../news/' + data;
                        }
                    }
                }
            );

            return false;
        } else if (dataBits[0] == 'res') {
            $('#frm-edit-res').submit();
        }
    });

    // Notices
    $('.notice-link').live('click', function() {
        var id = $(this).attr('rel');

//        if (($('tr.notice-details').length > 0) && ($('tr#notice-details-' + id).length == 0)) {
//            closeNoticeDetails();
//        }

        if ($('tr#notice-details-' + id).length == 0) {
            loadNoticeDetails(id);
        } else {
            closeNoticeDetails(id);
        }

        return false;
    });

    // Icon clicks
    $('.icon-click').live('click', function() {
        var dataBits = $(this).attr('rel').split('|');

        // Noticeboard
        if (dataBits[0] == 'notices') {
            if (dataBits[1] == 'approve') {
                // Toggle approval status
                $.ajax({
                    url:            '/mcp/ajax.noticeboard.php?action=' + dataBits[1] + '&id=' + dataBits[2],
                    success:        function(data) {
                        if (data == '1') {
                            // Notice approved
                            $('img#notice-icon-' + dataBits[2]).attr('src', '/_images/icons/icon_note_yellow.png');
                        } else {
                            $('img#notice-icon-' + dataBits[2]).attr('src', '/_images/icons/icon_note_red.png');
                        }
                    }
                });
            } else if (dataBits[1] == 'delete') {
                // Delete notice
                if (confirm('Really delete this notice?')) {
                    $.ajax({
                        url:        '/mcp/ajax.noticeboard.php?action=' + dataBits[1] + '&id=' + dataBits[2],
                        success:    function(data) {
                            if (data == '1') {
                                // Record deleted
                                $('tr#notice-details-' + dataBits[2]).remove();
                                $('tr#notice-' + dataBits[2]).remove();

//                                $('table.messageboard tbody tr:odd').addClass('tr.row-odd');
//                                $('table.messageboard tbody tr:even').addClass('tr.row-even');
                            } else {
                                alert('Record not deleted.');
                            }
                        }
                    });
                }
            } else if (dataBits[1] == 'edit') {
                // Edit notice
                $.ajax({
                    url:            '/mcp/ajax.edit-form-notices.php?action=edit&id=' + dataBits[2],
                    success:        function(html) {
                        $('div.notice-edit').html(html);

                        $('#action').val('edit');
                        $('#id').val(dataBits[2]);

                        $('div.notice-edit').show();
                    }
                });
            }
        }
    });

    $('ul.dir-selector li a').click(function() {
        var dataBits = $(this).attr('rel').split('|');
        var selector = $(this);

        if (dataBits[0] == 'teachers') {
            if (dataBits[1] == '#') {
                dataBits[1] = '0';
            }

            $.ajax({
                url:            '/ajax.get-dance-teachers.php?selector=' + dataBits[1],
                success:        function(html) {
                    $('ul.list-addresses').html(html);

                    // Clear selected selector
                    $('ul.dir-selector li a').each(function() {
                        $(this).removeClass('dir-selector-selected');

                        if ($(this).attr('rel') == selector.attr('rel')) {
                            $(this).addClass('dir-selector-selected');
                        }
                    });


                }
            });
        }

        return false;
    });

    // New records
    $('.icon-new').click(function() {
        var section = $(this).attr('rel');

        if (section == 'school') {
            if ($('div.form-edit-school').length < 1) {
                $.ajax({
                    url:            '/mcp/ajax.edit-form.php?data=' + section + '&type=new',
                    success:        function(form) {
                        $('div.new-school-form').html(form);
                    }
                });
            }
        } else if (section == 'news') {
            if ($('div.form-edit-news').length < 1) {
                $.ajax({
                    url:            '/mcp/ajax.edit-form.php?data=' + section + '&type=new',
                    success:        function(form) {
                        $('div.new-article-form').html(form);
                    }
                });
            }
        } else if (section == 'res') {
            if ($('div.form-edit-res').length < 1) {
                $.ajax({
                    url:            '/mcp/ajax.edit-form.php?data=' + section + '&type=new',
                    success:        function(form) {
                        $('div.new-res-form').html(form);
                    }
                });
            }
        }

        return false;
    });

    // Request a guide form
    $('form#frm-request-uk-guide').submit(function() {
        // Required fields
        var reqFields = new Array(
            'name',
            'address',
            'postcode',
            'qty'
        );

        for (var i = 0; i < reqFields.length; i++) {
            if ($('#' + reqFields[i]).val() == '') {
                showAjaxError('Please complete all required fields.');
                return false;
            }
        }

        // Send data
        $.post('/p_request-a-uk-guide.php',
            {
                name:               $('#name').val(),
                address:            $('#address').val(),
                postcode:           $('#postcode').val(),
                qty:                $('#qty').val()
            },
            function(data) {
                if (parseInt(data) == 1) {
                    hideAjaxError();

                    $('div.form-container').html('<p>Thank you for submitting your request. This will be handled as soon as possible.</p>');
                } else {
                    showAjaxError('An error occurred. Please try again.');
                }

                return false;
            }
        );

        return false;
    });

    // News category
    $('form#frm-edit-news select#cat-id').live('change', function() {
        if ($(this).val() == '[NEW]') {
            $('#news-cat-new').show();
        } else {
            $('#news-cat-new').hide();
            $('#cat-new').val('');
        }
    });
});

// Display form error message
function showAjaxError(msg) {
    $('div.ajax-error-msg').html(msg);
    $('div.ajax-error-msg').show();
}

// Hide ajax error msg
function hideAjaxError() {
    $('div.ajax-error-msg').hide();
    $('div.ajax-error-msg').empty();
}

function closeEditRows() {
    $('tr.edit-row').each(function() {
        $(this).remove();
    });
}

function closeNewForms() {
    if ($('.new-article-form').html() != '') {
        $('.new-article-form').empty();
    }
}

function showAjaxInlineMsgBox(section, msg) {
    $('div.form-edit-' + section).html('<div class="msgbox">Record updated.</div>');
    $('tr.edit-row').remove();
}

function closeNoticeDetails(id) {
    if ($('tr.notice-details').length > 0) {

        if (id > 0) {
            $('tr#notice-details-' + id).remove();
        } else {
            $('tr.notice-details').each(function() {
                $(this).remove();
            });
        }
    }
}

function loadNoticeDetails(id) {
    $.ajax({
        url:                '/ajax.get-notice-details.php?id=' + id,
        success:            function(html) {
            $('tr#notice-' + id).after(html);
        }
    });
}
