// Prerequisites: Google Analytics / TinyMCE etc

if (typeof tinyMCE !== 'undefined') {
    tinyMCE.init({
        // General options
        mode : "specific_textareas",
        editor_selector : "DUMMmceEditor",
        theme : "advanced",
        plugins : "safari,pagebreak,style,layer,save,advimage,advlink,emotions,inlinepopups,preview,media,print,contextmenu,paste,fullscreen,noneditable,nonbreaking,xhtmlxtras,template",

        // Theme options
  //    theme_advanced_buttons1 : "pastetext,pasteword,|,bold,italic,underline,strikethrough,|,hr,|,bullist,blockquote,|,undo,redo,link,unlink,emotions,fullscreen",
        theme_advanced_buttons1 : "pastetext,pasteword,bold,italic,underline,strikethrough,hr,bullist,blockquote,undo,redo,link,unlink,emotions,fullscreen",
        theme_advanced_buttons2 : "",
        theme_advanced_buttons3 : "",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "none",
        theme_advanced_resizing : false,
        width: "100%",
        convert_urls: false,

        // Drop lists for link/image/media/template dialogs
        template_external_list_url : "lists/template_list.js",
        external_link_list_url : "lists/link_list.js",
        external_image_list_url : "lists/image_list.js",
        media_external_list_url : "lists/media_list.js"
    });
}

var gaJsHost = (("https:" === document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
try
{
    var pageTracker = _gat._getTracker("UA-10409115-1");
    pageTracker._trackPageview();
} catch (err) {}


// global json object containing current config and settings
var page_params = {
    ajax_allow_queued_requests: false,
    mystuff_colour: '#dd1b19',
    club_colour: '#20b355',
    pro_colour: '#aaaaaa',
    ajax_queue_sequence: 0,
    ajax_errors: 0,
    max_list_scroll: 3,
    follow_hyperlink: true,
    request_in_progress: false,
    rich_text_editor_class: 'mceEditor',
    debug: false
};

window.alert = function (msg, title) {
    if ($('form.answers input[type=button]').length === 0) {
        if (typeof(title) !== 'string') {
            title = 'MyClubLink.com';
        }
        Boxy.alert(msg, null, {title: title});
    }
    return true;
};

function debug(msg) {
    if (debug) {
        if (typeof(console) !== "undefined" && typeof(console.log) === "function") {
            console.log(msg);
        }
        else {
//            alert(msg, 'debug');
        }
    }
}

function basename(file) {
    var tmp = file.split('\\');
    tmp = tmp[tmp.length - 1].split('/');
    return tmp[tmp.length - 1];
}

function enableRichTextEditor() {
    if (typeof tinyMCE !== 'undefined') {
        tinyMCE.init({
            mode : "textareas",
            editor_selector : page_params.rich_text_editor_class,
            theme : "advanced",
            //plugins : "safari,pagebreak,style,layer,save,advimage,advlink,emotions,inlinepopups,preview,media,print,contextmenu,paste,fullscreen,noneditable,nonbreaking,xhtmlxtras,template",
            plugins : "safari,pagebreak,style,save,advimage,advlink,inlinepopups,media,print,paste,fullscreen,noneditable,nonbreaking,xhtmlxtras,template",

            // Theme options
            //theme_advanced_buttons1 : "pastetext,pasteword,bold,italic,underline,strikethrough,hr,bullist,blockquote,undo,redo,link,unlink,emotions,fullscreen",
            theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,hr,bullist,blockquote,|,justifyleft,justifycenter,justifyright,justifyfull,|,link,unlink,|,undo,redo",
//            theme_advanced_buttons2 : "bullist,numlist,|,outdent,indent,blockquote,|,undo,redo",
            theme_advanced_buttons2 : "",
            theme_advanced_buttons3 : "",
            theme_advanced_toolbar_location : "top",
            theme_advanced_toolbar_align : "left",
            theme_advanced_statusbar_location : "none",
            theme_advanced_resizing : false,
            width: "100%",
            convert_urls: false,

            // Drop lists for link/image/media/template dialogs
            template_external_list_url : "lists/template_list.js",
            external_link_list_url : "lists/link_list.js",
            external_image_list_url : "lists/image_list.js",
            media_external_list_url : "lists/media_list.js"
        });
    }
}

function enableDatepicker() {
    if ($('#start_date').length) {
        $start_date = $('#start_date');
        $end_date = $('#end_date');

        if (!$start_date.data('datepicker_bound')) {
            $start_date.data('datepicker_bound', true);

            $start_date.datepicker({showOn: 'focus', dateFormat: 'dd/mm/yy'});
            $start_date.bind(
                'dpClosed',
                function (e, selectedDates)
                {
                    var d = selectedDates[0];
                    if (d) {
                        d = new Date(d);
                        $('#end_date').dpSetStartDate(d.addDays(1).asString());
                    }
                }
            );

            $end_date.datepicker({showOn: 'focus', dateFormat: 'dd/mm/yy'});
            $end_date.bind(
                'dpClosed',
                function (e, selectedDates)
                {
                    var d = selectedDates[0];
                    if (d) {
                        d = new Date(d);
                        $('#start_date').dpSetEndDate(d.addDays(-1).asString());
                    }
                }
            );
        }
    }
}

function enableColorPicker() {
    $('#color-picker').ColorPicker({
        color: '#0000ff',
        onShow: function (colpkr) {
            $(colpkr).fadeIn(500);
            return false;
        },
        onHide: function (colpkr) {
            $(colpkr).fadeOut(500);
            return false;
        },
        onChange: function (hsb, hex, rgb) {
            $('#color-picker div,img.avatar.preview').css('backgroundColor', '#' + hex);
            $('input[name=stock_image_rgb]').val(hex);
        }
    });
}

function getCurrentPage($el) {
    return $el.find('input.current-pager-row').val();
}

function getMessageFolder() {
    return $('#large-mail .panel-tabs .selected').text().toLowerCase();
}

function setSpinner($panel)
{
    if (typeof($panel) === 'string') {
        $panel = $($panel);
    }
    
    if ($panel && !$panel.hasClass('panel-container')) {
        $panel = $panel.closest('.panel-container');
    }

    if ($panel && $panel.hasClass('transitional') && !$panel.hasClass('working')) {
        $panel.addClass('working');
    }
}

function removeSpinner($panel)
{
    if (typeof($panel) === 'string') {
        $panel = $($panel);
    }

    if ($panel && !$panel.hasClass('panel-container')) {
        $panel = $panel.closest('.panel-container');
    }

    if ($panel && $panel.hasClass('transitional') && $panel.hasClass('working')) {        
        $panel.removeClass('working');
    }

    if (!$panel || !$panel.length) {
        $('.working').removeClass('working');
    }
}

function enableAutocompleter($el) {
    if (typeof($el) === 'undefined') {
        $el = $('#column2');
    }

    var autocomplete_type = $el.find('input[name="autocomplete_type"]').val();
    var autocomplete_id = $el.find('input[name="autocomplete_id"]').val();

    if (autocomplete_type) {
        $el.find("#to_id").fcbkcomplete({
            json_url: base_url + 'js/fcbkcomplete/mcl-fetched.php?type=' + autocomplete_type + '&fid=' + autocomplete_id + '&dummy=dummy',
            json_cache: true,
            cache: true,
            onselect: "fcbkValidate",
            filter_case: false,
            filter_hide: true,
            filter_selected: true,
            firstselected: true,
            newel: true
        });
    }
}

function fcbkValidate(item) {
    var val = item._value;
    var $el = $('li.bit-box[rel="'+val+'"]');

    if ($el.length && val.length) {
        if ($el.text() == val) {
            Boxy.alert('You have entered an invalid message recipient', null, {title: 'Error'});
            $el.fadeOut('normal', function () {$el.remove();} );
        }
        else if (val[0] == 'c') {
            $el.addClass('club');
        }
        else if (val[0] == 'g' || val[0] == 't') {
            $el.addClass('group');
        }
        else if (val[0] == 'o') {
            $el.addClass('organisation');
        }
        else {
            $el.addClass('user');
        }
    }
}

function stripeAttachments() {
    var row = 0;
    $('ul.attachments li').each(function () {
        if ($(this).css('display') != 'none') {
            $(this).removeClass('even').removeClass('odd').addClass(row % 2 ? 'odd' : 'even');
            row++;
        }
    });
}
function stripeContacts() {
    var row = 0;
    $('#api-list ul li').each(function () {
       if ($(this).css('display') != 'none') {
            $(this).removeClass('even').removeClass('odd').addClass(row % 2 ? 'odd' : 'even');
            row++;
       }
    });
    $('#invite-area li').each(function () {
       if ($(this).css('display') != 'none') {
            $(this).removeClass('even').removeClass('odd').addClass(row % 2 ? 'odd' : 'even');
            row++;
       }   
    });
}


// main code

$(document).ready( function () {
// allow global class to influence CSS when scripting is available
    $('body').removeClass('no-js').addClass('js');

// implement ESC as a generic cancel button on dialogs and ajax events
// and ENTER as a generic confirm button on dialogs
    $(document).keyup(function (event) {
        switch(event.which) {
            case 27:
                if ($('.panel-container.working')) {
                    $('.panel-container.working').removeClass('working');
                    page_params.ajax_queue_sequence++; // invalidate ajax request if it ever returns
                }

                $answers = $('form.answers input[type=button]');

                if ($answers.length == 1) {
                    $answers.click();
                }
                else if ($answers.length == 2) {
                    $answers.each(function () {
                        if ($(this).val().toLowerCase() == 'no' || $(this).val().toLowerCase() == 'cancel') {
                            $(this).click();
                        }
                    });
                }
                else if ($('td.boxy-inner div.title-bar a.close').length) {
                    $('td.boxy-inner div.title-bar a.close').click();
                }

                break;

            case 13:
                $answers = $('form.answers input[type=button]');

                if ($answers.length == 1) {
                    $answers.click();
                }
                else if ($answers.length == 2) {
                    $answers.each(function () {
                        if ($(this).val().toLowerCase() != 'no' && $(this).val().toLowerCase() != 'cancel') {
                            $(this).click();
                        }
                    });
                }
               break;

            default:
                break;
        }
    });


// add filter fields to any lists in panels which ask for them
    $('.panel-filter input').live('keyup', function (e) {
        if (e.keyCode == 27) {
            $(this).val('');
        }

        var needle = $(this).val().toLowerCase();
        var shown = 0;
        var total = 0;
        $(this).closest('.panel-container').find('.panel-content ul li,.feed_item,.filterable,tbody tr').each(function () {
            if (!$(this).parent().closest('.filterable').length) {  // exclude li elements inside filterable divs
                total++;
                var haystack = $(this).text().toLowerCase();
                // hack to make it work on club results lists
                if ($(this).find('ul.club-preview-text').length) {
                    haystack = $(this).find('li.title').text().toLowerCase();
                }

                if ($(this).find('li.user-li').length) {
                    haystack = $(this).find('input:checkbox').attr('title').toLowerCase();
                }                

                if (needle.length && haystack.indexOf(needle) == -1) {
                    $(this).hide();
                }
                else {
                    $(this).show();
                    shown++;
                }
            }
        });

        $(this).closest('.panel-container').find('p.showing').html('Showing <span id="filter-count">' + shown + '</span> of ' + total);
    });


// enable automatic input prompts
    $('input[type="text"]').each(function () {
        if (!$(this).val().length || $(this).val() == $(this).attr('alt')) {
            $(this).val($(this).attr('alt')).addClass('prompt');
        }

        $(this).focus(function () {
            if ($(this).val() == $(this).attr('alt')) {
                $(this).val('').removeClass('prompt');
            }
        });

        $(this).blur(function () {
            if (!$(this).val().length) {
                $(this).val($(this).attr('alt')).addClass('prompt');
            }
        });
    });
    
// error message handling
    if (typeof(flash_alert) != "undefined" && flash_alert) {
        alert(flash_alert);
    }

// date pickers
    enableDatepicker();

// two-pane select boxes
     $('.select-transfer button[name="add"]').live('click', function () {
         var $fieldset = $(this).closest('fieldset');
         var $from = $fieldset.find('.from');
         var $to = $fieldset.find('.to');

         $from.find('option:selected').appendTo($to.find('select'));
         return false;
     });

     $('.select-transfer button[name="remove"]').live('click',function () {
         var $fieldset = $(this).closest('fieldset');
         var $from = $fieldset.find('.from');
         var $to = $fieldset.find('.to');

         $to.find('option:selected').appendTo($from.find('select'));
         return false;
     });

     $('.filter-to,.filter-from').live('keypress', function () {
         var filter = $(this).val();

         $(this).closest('div').find('option').each(function () {
             if (!filter.length) {
                 $(this).show();
             }
             else {
                 var re = new RegExp(filter);

                 if (re.test($(this).text())) {
                     $(this).show();
                 }
                 else {
                     $(this).hide();
                 }
             }
         });
     });

// all elements in SELECT boxes must be active when form is submitted
    $('input[type="submit"]').live('click', function () {
        $(this).closest('form').find('.select-transfer option').each( function () {
            $(this).attr("selected", "selected");
        });
        return true;
    });

// automate "select-all" checkboxes
    $('input.select-all').live('mouseover', function () {
       if ($(this).attr('title') == '') {
           $(this).attr('title', 'select all');
       }
    });

    $('input.select-all').live('click', function () {
        var state = $(this).attr('checked');
        var name = $(this).val();
        $('input[name="'+name+'"], input[name="'+name+'[]"]').each(function () {
            if (!$(this).attr('disabled')) {
                $(this).attr('checked', state);
            }
        });
    });

// whole-box mouse clicks

// this binding is mostly vanity - but it does mean that people will still see
// the url in their status bar as if it was a real link.
    $('.follow-hyperlink').live('mouseover', function () {
        window.status = $(this).find('a').attr('href');
    });

    $('.follow-hyperlink').live('mouseout', function () {
        window.status = '';
    });

// intercept checkboxes - we don't want the event to keep bubbling
    $('.follow-hyperlink input,.follow-hyperlink select,.follow-hyperlink button').live('click', function () {
        page_params.follow_hyperlink = false;
    });

    $('.follow-hyperlink').live('click', function () {
        if (page_params.follow_hyperlink) {
            var $anchor = $(this).find('a');
            if ($anchor.length) {
                var url = $anchor.attr('href');
                if ($anchor.attr('target').toLowerCase() == '_blank' || $anchor.hasClass('new-window')) {
                    window.open(url);
                }
                else {
                    window.location = url;
                }
            }
        }
        else {
            page_params.follow_hyperlink = true;
        }
    });

$('#diary-cost-toggle').live('click', function() {
    var $el = $('#diary-cost');
    $el.toggleClass('disabled');
    $el.find('select,input').attr('disabled', $el.hasClass('disabled'));
});

$('#reminder').live('click', function() {
    var $el = $('#diary-reminder');
    $el.toggleClass('disabled');
    $el.find('select,input').attr('disabled', $el.hasClass('disabled'));
});

$('#add-comment-toggle').live('click', function () {
    $(this).slideUp();
    $('#add-comment-wrapper').slideDown();
    return false;
});

$('#add-comment input[type=submit]').live('click', function () {
    if ($('textarea[name="content"]').val().length) {
        setSpinner($(this).closest('.panel-container'));
        doJsonUpdate(
            $(this).closest('form').attr('action'),
            {
                owner_type: $('input[name="owner_type"]').val(),
                owner_id:   $('input[name="owner_id"]').val(),
                referrer:   $('input[name="referrer"]').val(),
                row_start:  $('input[name="row_start"]').val(),
                content:    $('textarea[name="content"]').val()
            }
        );
    }
    else {
        alert('You must enter some text for your comment!');
    }
    return false;
});

$('a.delete-comment').live('click', function () {
    $anchor = $(this);
    Boxy.confirm('Are you sure you want to delete this comment?',
        function () {
            setSpinner($anchor.closest('.panel-container'));
            doJsonUpdate($anchor, {});
        },
        {title: 'Confirmation Required'}
    );
    return false;
});

$('#add-attendees').live('click', function () {
        var $anchor = $(this);

        var data = {
                event: 'edit_group'
        };

        setSpinner($('#large-diary'));
        doJsonUpdate($anchor, data);        
        return false;
    });

// force all external links to open in a new window
    $("a[href^='http:']:not([href*='"+window.location.host+"']),a.popup-help").live('click', function () {
        window.open($(this).attr('href'));
        return false;
    });

    $('#submit-payment').live('click', function () {
        var ok = true;
        $('input[type=text].required:visible').each(function () {
            if (!$(this).val().length) {
                ok = false;
            }
        });
        if (!ok) {
            alert('a required field is missing');
            return false;
        }
        if ($('#paypal_email').val() !== ($('#paypal_confirm')).val()) {
            alert('paypal username does not match confirmation');
            return false;
        }
        return true;
    });

// message recipient autocomplete
    enableAutocompleter($('body'));

    enableRichTextEditor();

// enable progressbars
    if ($("div#setup-progressbar").length) {
        var el = $("div#setup-progressbar");
        var percent = el.text();
        el.empty();
        el.progressbar({value: percent});
    }

// convert all links under ".ajax" classes to ajax requests

    function doJsonUpdate($anchor, data) {
        if (page_params.request_in_progress) {
            page_params.ajax_errors++;
            debug('AJAX error #'+page_params.ajax_errors+': request already in progress, skipping subsequent requests');
            return false;
        }

        page_params.ajax_queue_sequence++;
        data['ajax_queue_sequence'] = page_params.ajax_queue_sequence;
        data['ajax_request'] = true;
        data['body_class'] = $('body').attr('class').replace(' js', '');

        var url = typeof($anchor) == 'string' ? $anchor : $anchor.attr('href');

        $.post(url, data, function (json) {
            if (typeof(json.ajax_queue_sequence) != "string") {
                page_params.ajax_errors++;
                debug('AJAX error #'+page_params.ajax_errors+': request did not return in expected JSON format');
                return;
            }

            if (page_params.allow_queued_requests == false && json.ajax_queue_sequence != page_params.ajax_queue_sequence) {
                page_params.ajax_errors++;
                debug('AJAX error #'+page_params.ajax_errors+': request returned out of sequence: got '+json.ajax_queue_sequence+', expected '+page_params.ajax_queue_sequence);
                return;
            }

            if (typeof(json.redirect) != 'undefined') {
                window.location = json.redirect;
                return;
            }

            if (typeof(console) != "undefined" && typeof(console.log) == "function" && page_params.debug) {
                $.each(json.debug, function (key, val) {
                    if (val == '') {
                        console.log(key);
                    }
                    else {
                        console.log(key+': '+val);
                    }
                });
            }

            $.each(json.vars, function (var_name, val) {
                page_params[''+var_name] = val;
            });

            var richText = false;
            $.each(json.dom_replace, function (selector, val) {
                if ($(selector).length) {
                    $(selector).before(val).remove();
                }
                else {
                    $('#column1').append(val);
                    debug('missing replace selector - appending to #column1 (coz sometimes now actions panel');
                }

                if ($(selector).find('.'+page_params.rich_text_editor_class)) {
                    richText = true;
                }
            });

            enableAutocompleter();
            
            if (richText) {
                enableRichTextEditor();
            }

            $.each(json.dom_append, function (selector, val) {
                $(selector).append(val);
            });

            $.each(json.dom_remove, function (selector, val) {
                $(selector).slideUp('slow', function () {
                    $(this).remove();
                });
            });

            if (typeof(json.alert.message) != 'undefined') {
                alert(json.alert.message, json.alert.title);
            }

            if (typeof(json.focus) != 'undefined') {
                $(json.focus).focus();
            }
            else {
                $('#column2 input[type=text]').first().focus();
            }

            page_params.request_in_progress = false;
            
            rebind();
            removeSpinner(false);
        }, 'json');

        return true;
    }

    function get_invoice_net() {
        var net = 0.0;
        $('.invoice-cost input').each(function() {
            net += parseFloat($(this).val())
        });

        if (!net) {
            net = 0.0
        }
        $('#invoice-net-total input').val(net);
        return net;
    }

    function get_invoice_fee() {
        var fee_percent = 1.0;
        var fee_minimum = 1.0;

        var fee = get_invoice_net() * fee_percent / 100.0;

        if (fee < fee_minimum) {
            fee = fee_minimum;
        }
        $('#invoice-commission input').val(fee);
        return fee;
    }

    function get_invoice_vat() {
        var vat_percent = 17.5;

        var vat = (get_invoice_net() + get_invoice_fee()) * vat_percent / 100.0;

        $('#invoice-vat input').val(vat);
        return vat;
    }

    function get_invoice_gross() {
        var gross = get_invoice_net() + get_invoice_vat() + get_invoice_fee();
        
        $('#invoice-gross-total input').val(gross);
        return gross;
    }

    $('#invoice-preview').live('click', function() {
        var title = 'Invoice Preview';
        var data = {};

        var valid = true;
        $('#edit-invoice-form input[type=text],#edit-invoice-form input[type=hidden]').each(function() {
            if (!$(this).val().length) {
                valid = false;
            }
            data[$(this).attr('name')] = $(this).val();
        });

        if (!valid) {
            alert('Preview not available until all fields are filled in');
            return false;
        }

        var $div = $('#ajax_dialog');
        if (!$div.length) {
            $div = $('<div id="ajax_dialog"></div>');
        }

        $div.empty();

        $.post($(this).attr('href'), data, function(result) {
            $div
            .html('<img style="margin: 140px 0px 0px 284px" src="cssimages/v2/ajax-loader.gif" alt="Please wait..." />')
            .dialog({
                autoOpen: false,
                title: title,
                height: 500,
                width: 573,
                resizable: false,
                draggable: false,
                modal: true,
                dialogClass :'clear'
            })
            .dialog('open')
            .dialog('option', 'title', title)
            .dialog('option','width', 573)
            .dialog('option','height', 500)
            .dialog('option','position', 'center')
            .addClass('cms_popup')
            .html(result);
        });

        return false;
    });

    $('#edit-invoice input').live('keyup', get_invoice_gross);

    $('#invoice-add-item').live('click', function () {
        var $el = $('#edit-invoice');
        var i = $el.data('row-index');
        if (!i) {
            i = 1000;
        }

        i++;
        $el.data('row-index', i);

        $('<tr><td class="invoice-name"><input name="name[' + i + ']" maxlen="50" /></td><td class="invoice-cost"><input name="cost[' + i + ']" maxlen="7" /></td><td class="invoice-controls"><img title="delete item" class="invoice-remove-item js" src="cssimages/icons/icon-cross.png" alt="delete item" /></td></tr>').appendTo($el.find('tbody'));

        return false;
    });


    $('.invoice-remove-item').live('click', function () {
        $(this).closest('tr').remove();
        return false;
    });

    $('#welcome .panel-close-control').live('click', function () {
        Boxy.confirm('These tips and many more can be found in our Help section, which can be accessed from the top right hand corner.<br />Are you sure you want to remove this component?',
            function () {
                setSpinner($('#welcome'));
                $.post('index.php/wizard/disable_tips', {}, function () {
                    $('#welcome').slideUp();
                });
            },
            {title: 'Confirmation Required'}
        );
        return false;
    });

    $('#action-change-payment-status').live('click', function () {
        var tmp = $(this).text().toLowerCase().split(' ');
        var href = $(this).attr('href');

        Boxy.confirm("Are you sure you want to change this invoice to '" + tmp[2] + "'?",
            function () {
                window.location = href;
            },
            {title: 'Confirmation Required'}
        );
        return false;
    });

    $('#action-change-image').live('click', function () {
        var $anchor = $(this);

        var data = {
            pager_row: getCurrentPage($('#image-panel'))
        };
        setSpinner($('#image-panel'));
        doJsonUpdate($anchor, data);

        return false;
    });

    $('.action-change-title').live('click', function () {

        var url = $(this).closest('form').attr('action');
        var $item_title = $('#column2 input[id="title"]');
        var data = {
            pager_row: getCurrentPage($('#image-panel')),
            title: $item_title.val()
        };

        $(this).closest('').animate({
            opacity:0.25
        });

        setSpinner($('#image-panel'));
        doJsonUpdate(url, data);
            
       return false;
    });

    $('#action-delete-images').live('click', function () {
        var message = 'Are you sure you want to delete these items?';
        var $checkboxes = $('#column2 input[type="checkbox"][checked!="false"]');
        var $anchor = $(this);

        if ($checkboxes.length == 0) {
            alert('You have not selected any items to delete.');
        }
        else {
            if ($checkboxes.length == 1) {
                message = 'Are you sure you want to delete this item?';
            }

            var data = {
                pager_row: getCurrentPage($('#album-display')),
                image_list: []
            };

            $checkboxes.each(function () {
                data['image_list'].push($(this).val());
            });

            Boxy.confirm(message,
                function () {
                    setSpinner($('#album-display'));
                    doJsonUpdate($anchor, data);
                },
                {title: 'Confirmation Required'}
            );
        }
        return false;
    });

        $('#action-delete-activity').live('click', function () {
        var message = 'Are you sure you want to remove these activities?';
        var $checkboxes = $('#column2 input[type="checkbox"][checked!="false"]');
        var $anchor = $(this);

        if ($checkboxes.length == 0) {
            alert('You have not selected any activities to remove.');
        }
        else {
            if ($checkboxes.length == 1) {
                message = 'Are you sure you want to delete this activity?';
            }

            var data = {
                pager_row: getCurrentPage($('#activity-panel')),
                activity_list: []
            };

            $checkboxes.each(function () {
                data['activity_list'].push($(this).val());
            });

            Boxy.confirm(message,
                function () {
                    setSpinner($('#activity-panel'));
                    doJsonUpdate($anchor, data);
                },
                {title: 'Confirmation Required'}
            );
        }
        return false;
    });

    $('#action-edit-activity').live('click', function () {
        var $checkboxes = $('#column2 input[type="checkbox"][checked!="false"]');
        var $anchor = $(this);

        if ($checkboxes.length == 0) {
            alert('You have not selected an activity to edit.');
        }
        else if ($checkboxes.length == 1) {
            
            var data = {
                pager_row: getCurrentPage($('#activity-panel')),
                activity_list: []
            };

            $checkboxes.each(function () {
                data['activity_list'].push($(this).val());
            });

            setSpinner($('#activity-panel'));
            doJsonUpdate($anchor, data);

        }else{
            alert('You can only edit one activity at a time');
        }
        return false;
    });

    $('#action-leave-club').live('click', function () {
        return confirmWrapper($(this), 'Are you sure you want to leave this club?');
    });

// help popups
    $('.popup-help').each(function () {
        $(this).click(function () {
            window.open(
                $(this).attr('href'),
                'popup',
                'width=980,height=700,scrollbars=yes,resizable=no,toolbar=no,directories=no,location=no,menubar=no,status=no,left=0,top=0'
            );
            return false;
        });
    });

    $('.remove-upload-input').live('click', function () {
        $(this).closest('li').remove();
        return false;

    });

    $('.add-youtube-input').live('click', function () {
        $("#div-input").append("<li><input type='input' class='add-youtube-input' name='youtube[]' id='youtube[]'/><a href='#' class='remove-upload-input'>Remove</a></li>");
    });

    $('#edit-event-form input[type="submit"]').live('click', function () {
        var err = '';

        if ($('select[name="event_type"]').val() == 0) {
            err += 'You must choose an event type<br />';
        }

        if (!$('#title').val().length) {
            err += 'Event Name is a required field<br />';
        }

        if (!$('input[name="all_day"]:checked').length) {
            $('.datepicker').each(function () {
                if (!$(this).val().length) {
                    err = 'Start and end date are required fields<br />';
                }
            });           

            var startTime = new Date($("#start_date").val());
            var endTime = new Date($("#end_date").val());

            start_add = 0;
            end_add = 0;

            if ($("select[name='start_meridian']").val() == 'pm' && $("select[name='start_hour']").val() != 12) start_add = 12;
            if ($("select[name='end_meridian']").val() == 'pm' && $("select[name='end_hour']").val() != 12) end_add = 12;
            
            startTime.setHours(+$("select[name='start_hour']").val() + start_add);
            startTime.setMinutes($("select[name='start_minute']").val());

            endTime.setHours(+$("select[name='end_hour']").val() + end_add);
            endTime.setMinutes($("select[name='end_minute']").val());

//            console.log($("select[name='start_meridian']").val());
//            console.log(+$("select[name='start_hour']").val() + start_add);
//            console.log(startTime);
//            console.log(endTime);

            if (endTime < startTime) err += "Please review the Start and End times - This event appears to finish before it starts.<br />";
        }
        else
        {
            var startTime = new Date($("#start_date").val());
            var endTime = new Date($("#end_date").val());

            if (endTime < startTime) err += "Please review the Start and End dates - This event appears to finish before it starts.<br />";
        }

        if ($('#saved_location').val() == 0 && $('#loc_label').val() == 'Location Name') {
            err += 'When adding a new location, you must provide a location name.<br />';
        }

        if (err.length) {
            alert('Please correct the following errors:<br /><br />'+err, 'Edit Event');
            return false;
        }
        
        return true;
    });


// attachments

// initialise them (stops screwups if they press F5 in some browsers)
    $('ul.attachments input[type="checkbox"]').each(function () {
        $(this).attr('checked', false);
    });

    $('#manage-video-album .add-attachment').live('click', function () {
        var max_attachments = $('input#max-attachments').val();

        var current_attachments = $('input[name="youtube[]"]').length
            + $('input[name="delete_file[]"][checked!="true"]').length;

        if (current_attachments < max_attachments) {
            var $new_bit = $('<li><input type="input" name="youtube[]" /></li>');
            $(this).closest('fieldset').find('ul').append($new_bit);
            $new_bit.find('input').change(function () {
                if (!$(this).data('started')) {
                    $(this).data('started', true);
                    if ($(this).val().length) {
                        var filename = basename($(this).val());
                        $(this).before('<a href="#'+filename+'" onclick="return false;">'+filename+'</a><button class="remove-attachment">&nbsp;</button>').hide();
                        stripeAttachments();
                    }
                }
            });
        }
        else {
            alert('You may not add more than '+max_attachments+' '+$(this).text().split('add ')[1]+'s');
        }
        return false;
    });

    $('.add-attachment').live('click', function () {
        var max_attachments = $('input#max-attachments').val();

        var current_attachments = $('input[name="user_file[]"]').length
            + $('input[name="delete_file[]"][checked!="true"]').length;

        debug('current_attachments: '+current_attachments);

        if (current_attachments < max_attachments) {
            var $new_bit = $('<li><input type="file" name="user_file[]" /></li>');
            $(this).closest('fieldset').find('ul').append($new_bit);
            $new_bit.find('input').change(function () {
                if (!$(this).data('started')) {
                    $(this).data('started', true);
                    if ($(this).val().length) {
                        var filename = basename($(this).val());
                        $(this).before('<a href="#'+filename+'" onclick="return false;">'+filename+'</a><button class="remove-attachment">&nbsp;</button>').hide();
                        stripeAttachments();
                    }
                }
            });
        }
        else {
            alert('You may not add more than '+max_attachments+' attachments');
        }
        return false;
    });

    $('.add-qualification').live('click', function () {
       $('#add-activity-selects ul').append($('#add-activity-selects li:first-child').clone());
       $('#add-activity-selects li:last-child').append('<a href="#" class="js remove-qualification">remove qualification</a>');
       return false;
    });

    $('.remove-qualification').live('click', function () {
       $(this).parent().remove();
       return false;
    });

    $('button.remove-attachment').live('click', function () {
        $(this).closest('li').remove();
        stripeAttachments();
        return false;
    });

    $('button.remove-existing-attachment').live('click', function () {
        $li = $(this).closest('li');
        $li.find('input[type="checkbox"]').attr('checked', true);
        $li.fadeOut('fast', function () {
            $li.hide();
            stripeAttachments();
        });
        
        return false;
    });

    $('input[name="all_day"]').live('click', function () {
        if ($(this).attr('checked')) {
            $('span.time,select.time').fadeOut();
        }
        else {
            $('span.time,select.time').fadeIn();
        }
    });

    



// messages

    $('#action-delete-messages').live('click', function () {
        var message = 'Are you sure you want to delete these messages?';
        var $checkboxes = $('#column2 input[type="checkbox"][checked!="false"]');
        var $anchor = $(this);

        if ($checkboxes.length == 0) {
            alert('You have not selected any messages to delete.');
        }
        else {
            if ($checkboxes.length == 1) {
                message = 'Are you sure you want to delete this message?';
            }

            var data = {
                mbox: getMessageFolder(),
                pager_row: getCurrentPage($('#large-mail')),
                message_list: []
            };

            $checkboxes.each(function () {
                data['message_list'].push($(this).val());
            });

            Boxy.confirm(message,
                function () {
                    setSpinner($('#large-mail'));
                    doJsonUpdate($anchor, data);
                },
                {title: 'Confirmation Required'}
            );
        }

        return false;
    });

    $('#action-reply-to-all-message').live('click', function () {

        var $checkboxes = $('#column2 input[type="checkbox"][checked!="false"]');
        var $anchor = $(this);

        if ($checkboxes.length == 0) alert('You have not selected a message to reply to.');
        else if ($checkboxes.length > 1) alert('You can only reply to one message at a time.');
        else {
            var data = {
                mbox: getMessageFolder(),
                pager_row: getCurrentPage($('#large-mail')),
                message_list: []
            };

            $checkboxes.each(function () {
                data['message_list'].push($(this).val());
            });

            setSpinner($('#large-mail'));
            doJsonUpdate($anchor, data);
        }
        return false;
    });

    $('#action-reply-message').live('click', function () {

        var $checkboxes = $('#column2 input[type="checkbox"][checked!="false"]');
        var $anchor = $(this);

        if ($checkboxes.length == 0) alert('You have not selected a message to reply to.');
        else if ($checkboxes.length > 1) alert('You can only reply to one message at a time.');
        else {
            var data = {
                mbox: getMessageFolder(),
                pager_row: getCurrentPage($('#large-mail')),
                message_list: []
            };

            $checkboxes.each(function () {
                data['message_list'].push($(this).val());
            });

            setSpinner($('#large-mail'));
            doJsonUpdate($anchor, data);
        }
        return false;
    });

    $('#action-forward-message').live('click', function () {

        var $checkboxes = $('#column2 input[type="checkbox"][checked!="false"]');
        var $anchor = $(this);

        if ($checkboxes.length == 0) alert('You have not selected a message to forward.');
        else if ($checkboxes.length > 1) alert('Please select only 1 message to forward.');
        else {
            var data = {
                mbox: getMessageFolder(),
                pager_row: getCurrentPage($('#large-mail')),
                message_list: []
            };

            $checkboxes.each(function () {
                data['message_list'].push($(this).val());
            });
            
            setSpinner($('#large-mail'));
            doJsonUpdate($anchor, data);

        }

        return false;
    });

    // Edit Role

    $('#action-edit-role').live('click', function () {
        var $checkboxes = $('#column2 input[type="checkbox"][checked!="false"]');
        var $anchor = $(this);

        if ($checkboxes.length == 0) {
            alert('Please select a role to edit.');
        }
        else if ($checkboxes.length > 1) {
            alert('Please select 1 role at a time to edit.');
        }
        else {
            var data = {
                role_id: '',
                event: 'edit_role'
            };

             $checkboxes.each(function () {
                data['role_id'] = $(this).val();
            });


            setSpinner($('#large-settings'));
            doJsonUpdate($anchor, data);
        }
        return false;
    });

    // Delete Role

    $('#action-delete-role').live('click', function () {
        var message = 'Are you sure you want to delete these roles?';
        var $checkboxes = $('#column2 input[type="checkbox"][checked!="false"]');
        var $anchor = $(this);

        if ($checkboxes.length == 0) {
            alert('Please select a role to delete.');
        }
        else {
            if ($checkboxes.length == 1) {
                message = 'Are you sure you want to delete this role?';
            }

            var data = {
                role_list: [],
                event: 'delete_role'
            };

             $checkboxes.each(function () {
                data['role_list'].push($(this).val());
            });

            Boxy.confirm(message,
                function () {
                    setSpinner($('#large-settings'));
                    doJsonUpdate($anchor, data);
                },
                {title: 'Confirmation Required'}
            );
        }
        return false;
    });

    $('#action-duplicate-role').live('click', function () {
        var $checkboxes = $('#column2 input[type="checkbox"][checked!="false"]');
        var $anchor = $(this);

        if ($checkboxes.length == 0) {
            alert('Please select a role to duplicate.');
        }
        else if ($checkboxes.length > 1) {
            alert('Please select 1 role at a time to duplicate.');
        }
        else {
            var data = {
                role_id: '',
                event: 'duplicate_role'
            };

             $checkboxes.each(function () {
                data['role_id'] = $(this).val();
            });


            setSpinner($('#large-settings'));
            doJsonUpdate($anchor, data);
        }
        return false;
    });

    // Assign Role popup

    $('#action-role-assignment').live('click', function () {
        var $checkboxes = $('#column2 input[type="checkbox"][checked!="false"]');        
        var $selector = $('.ajax-role-changer');
        var rolemappings = [];
        
        //alert($selector.html());
        if ($checkboxes.length == 0) {
            alert('Please select a member.');
        }
        else {            
             $checkboxes.each(function () {
                var tmp = $(this).attr('id').split('_');
                rolemappings.push(tmp[2]);
            });                        

            Boxy.confirmok('What role would you like to assign to these members?<br/><form id="rolechoice" action="wizard/update_role" method="POST"><input type="hidden" name="rolemaps" value="' + rolemappings + '" /><select name="role">' + $selector.html() + "</select></form>", function () {
                $('#rolechoice').submit();
            });
        }
        return false;
    });
    
    //Transfer Leadership

    $('#action-transfer-leader').live('click', function () {
        var $anchor = $(this);
        var $checkboxes = $('#column2 input[type="checkbox"][checked!="false"]');
        var newleader = [];        
        var leaderdetails = [];
        var targetname = "";
        var message = "";
        
        leaderdetails = $('.ajax-role-changer-leader').attr('id').split('_');

        if ($checkboxes.length == 0) {
            alert('Please select a member before transfering Club Leadership.');
        }
        else if ($checkboxes.length > 1) {
            alert('Please select 1 member only to transfer Club Leadership.');
        }
        else {                       

             $checkboxes.each(function () {
                newleader = $(this).attr('id').split('_');
                targetname = $('#mini-selected li').html();
            });

            var data = {
                lrm_id: leaderdetails[2],
                rm_id: newleader[2],
                club_id: current_club_id,
                event: 'transfer_leader'
            };

            message = "You are about to relinquish all control of this club and promote " + targetname + " to be the club's owner.<br/><br/>Are you sure you want to do this?";

            Boxy.confirm(message,
                function () {
                    setSpinner($('#large-settings'));
                    doJsonUpdate($anchor, data);
                    //return false;
                },
                {title: 'Confirmation Required'}
            );

        }
        return false;
    });


    // Edit Group

    $('#action-edit-group').live('click', function () {
        var $checkboxes = $('#column2 input[type="checkbox"][checked!="false"]');
        var $anchor = $(this);

        if ($checkboxes.length == 0) {
            alert('You have not selected a group to edit.');
        }
        else if ($checkboxes.length > 1) {
            alert('You can only edit one group at a time.');
        }
        else {            
            var data = {
                group_id: '75',
                event: 'edit_group'
            };

            
             $checkboxes.each(function () {
                data['group_id'] = $(this).val();
            });
             

            setSpinner($('#large-contacts'));
            doJsonUpdate($anchor, data);
        }
        return false;
    });

    // Delete Group

    $('#action-delete-group').live('click', function () {
        var message = 'Are you sure you want to delete these groups?';
        var $checkboxes = $('#column2 input[type="checkbox"][checked!="false"]');
        var $anchor = $(this);

        if ($checkboxes.length == 0) {
            alert('You have not selected a group to delete.');
        }
        else {
            if ($checkboxes.length == 1) {
                message = 'Are you sure you want to delete this group?';
            }

            var data = {
                group_list: [],
                event: 'delete_group'
            };

             $checkboxes.each(function () {
                data['group_list'].push($(this).val());
            });

            Boxy.confirm(message,
                function () {
                    setSpinner($('#large-contacts'));
                    doJsonUpdate($anchor, data);
                },
                {title: 'Confirmation Required'}
            );
        }
        return false;
    });

    $('#action-just-delete-group').live('click', function () {
        return confirmWrapper($(this), 'Are you sure you want to delete this group?');
    });

    $('#select_add').live('click', function () {
      return !$('#select1 option:selected').remove().appendTo('#select2');
     });
     
     $('#select_remove').live('click',function () {
      return !$('#select2 option:selected').remove().appendTo('#select1');
     });

     $("#create_group_form input[type='submit'],#event-details input[type='submit']").live('click', function () {
        $('select#select1 option').each( function () {
            $(this).attr("selected", "selected");
        });
        $('select#select2 option').each( function () {
            $(this).attr("selected", "selected");
        });
    });

     $("#event-details input[type='submit']").live('click', function () {
         var msg = '';

        if ($('input[name="title"]').val().length == 0) {
            msg += 'You must give the event a title<br />';
        }

        if ($('select#event_type').val() == 0) {
            msg += 'You must specify an event type<br />';
        }

        if ($('textarea[name="description"]').val().length == 0) {
            msg += 'You must give the event a description<br />';
        }

        var sDateString = $("input#start_date").val().split("/");
        var eDateString = $("input#end_date").val().split("/");

        var sDate = new Date(sDateString[1]+"/"+sDateString[0]+"/"+sDateString[2]);
        var eDate = new Date(eDateString[1]+"/"+eDateString[0]+"/"+eDateString[2]);

        if (eDate - sDate < 0) {
          msg += 'The event cannot end before it begins.<br />';
        }
        else if (eDate - sDate == 0 && !$('input[name="all_day"]').is(':checked')) {
            start = parseInt($('select[name="start_time_h"] option:selected').val(), 10) * 60 + parseInt($('select[name="start_time_m"] option:selected').val(), 10);
            end = parseInt($('select[name="end_time_h"] option:selected').val(), 10) * 60 + parseInt($('select[name="end_time_m"] option:selected').val(), 10);
            if (start > end) {
               msg += 'The event cannot end before it begins.<br />';
            }
        }

        if (msg.length) {
            alert('The event contains the following errors:<br /><br />'+msg);
            return false;
        }

        return true;
    });

    $('#action-prefill-create-group').live('click', function () {
        var $checkboxes = $('#column2 input[type="checkbox"][checked!="false"]');
        var $anchor = $(this);

        var data = {
                user_list: []
            };

       $checkboxes.each(function () {
            data['user_list'].push($(this).val());
            });

        setSpinner($('#large-contacts'));
        doJsonUpdate($anchor, data);

        return false;
    });

    $('#action-prefill-send').live('click', function () {
        var $checkboxes = $('#column2 input[type="checkbox"][checked!="false"]');
        var $anchor = $(this);

        var data = {
                users: []
            };

       $checkboxes.each(function () {
            data['users'].push($(this).val());
            });

        setSpinner($('#large-contacts'));
        doJsonUpdate($anchor, data);

        return false;
    });

    $('#action-remove-member').live('click', function () {
        var message = "Are you sure you want to revoke these users' membership to the club?";
        var $checkboxes = $('#column2 input[type="checkbox"][checked!="false"]');
        var $anchor = $(this);

        if ($checkboxes.length == 0) {
            alert('You have not selected a member.');
        }
        else {

            if ($checkboxes.length == 1) {
                message = "Are you sure you want to revoke this user's membership?";
            }

            var data = {
                users: [],
                event: 'remove_members'
            };

            $checkboxes.each(function () {
                data['users'].push($(this).val());
            });

            Boxy.confirm(message,
                function () {
                    setSpinner($('#large-contacts'));
                    doJsonUpdate($anchor, data);
                },
                {title: 'Confirmation Required'}
            );
        }
        return false;
    });

    $('#action-remove-member-settings').live('click', function () {
        var message = "Are you sure you want to revoke these users' membership to the club?";
        var $checkboxes = $('#column2 input[type="checkbox"][checked!="false"]');
        var $anchor = $(this);

        if ($checkboxes.length == 0) {
            alert('You have not selected a member.');
        }
        else {

            if ($checkboxes.length == 1) {
                message = "Are you sure you want to revoke this user's membership?";
            }

            var data = {
                users: [],
                event: 'remove_members'
            };

            $checkboxes.each(function () {
                data['users'].push($(this).val());
            });

            Boxy.confirm(message,
                function () {
                    setSpinner($('#large-settings'));
                    doJsonUpdate($anchor, data);
                },
                {title: 'Confirmation Required'}
            );
        }
        return false;
    });

    $('#action-delete-location').live('click', function () {
        var message = 'Are you sure you want to delete these locations?';
        var $checkboxes = $('#column2 input[type="checkbox"][checked!="false"]');
        var $anchor = $(this);

        if ($checkboxes.length == 0) {
            alert('You have not selected a location to delete.');
        }
        else {
            if ($checkboxes.length == 1) {
                message = 'Are you sure you want to delete this location?';
            }

            var data = {
                location_list: [],
                event: 'delete_location'
            };

             $checkboxes.each(function () {
                data['location_list'].push($(this).val());
            });

            Boxy.confirm(message,
                function () {
                    setSpinner($('#large-diary'));
                    doJsonUpdate($anchor, data);
                },
                {title: 'Confirmation Required'}
            );
        }
        return false;
    });

    $('#action-edit-location').live('click', function () {
        var $checkboxes = $('#column2 input[type="checkbox"][checked!="false"]');
        var $anchor = $(this);

        if ($checkboxes.length == 0) {
            alert('You have not selected a location to edit.');
        }
        else if ($checkboxes.length > 1) {
            alert('You can only edit 1 location at a time.');
        }
        else {

            var data = {
                event: 'edit_location'
            };

             $checkboxes.each(function () {
                data['location'] = ($(this).val());
            });
            
            setSpinner($('#large-diary'));
            doJsonUpdate($anchor, data);                            
        }
        return false;
    });


    $('#referral-controls a').click(function () {
        if ($(this).hasClass('yes')) {
            $(this).closest('div').html('<span class="pseudo-button">Pending</span>');
        }
        else {
            $(this).closest('div').html('<span class="pseudo-button">Ignored</span>');
            return false;
        }
        
        return true;
    });

    $('#action-remove-friend').live('click', function () {
        var message = "Are you sure you want to remove these contacts?";
        var $checkboxes = $('#column2 input[type="checkbox"][checked!="false"]');
        var $anchor = $(this);

        if ($checkboxes.length == 0) {
            alert('You have not selected a contact to remove.');
        }
        else {

            if ($checkboxes.length == 1) {
                message = "Are you sure you want to remove this contact?";
            }

            var data = {
                users: [],
                event: 'remove_friend'
            };

            $checkboxes.each(function () {
                data['users'].push($(this).val());
            });

            Boxy.confirm(message,
                function () {
                    setSpinner($('#large-contacts'));
                    doJsonUpdate($anchor, data);
                },
                {title: 'Confirmation Required'}
            );
        }
        return false;
    });


    // diary

    $('#small-diary a').live('click', function () {
        setSpinner($('#large-diary'));
    });


// login form validation
    $('div#current-user-info form').live('submit', function () {
        if (!$('#username').val().length) {
            alert('You must enter your username to log in.<br />Your username is the email address you used to sign up for myClubLink.com', 'Help with logging in');
            return false;
        }
        if (!$('#password').val().length) {
            alert('You must enter your password to log in.', 'Help with logging in');
            return false;
        }
        return true;
    });

    $('.ajax a, a.ajax').live('click', function () {
        if ($(this).hasClass('no-ajax')) {
            return true;
        }

        var data = {
            panel_id: '#'+$(this).closest('.panel-container').attr('id'),
            ajax_parent_id: '#'+$(this).closest('.ajax').attr('id'),
            anchor_id: '#'+$(this).attr('id')
        }

        setSpinner($(this));

        // if launched from action panel and there's only one large panel, spin it
        if ($(this).closest('.action-panel')) {
            $el = $('#column2 .panel-container');
            if ($el.length == 1) {
                setSpinner($el);
            }
        }
        doJsonUpdate($(this), data);

        return false;
    });


    // add datepicker to user registration form
    if ($("#date_of_birth").length) {
        $('#date_of_birth').datepicker({
            changeMonth: true,
            changeYear: true,
            minDate: '-109Y',            
            showOtherMonths: true,           
            dateFormat: 'dd/mm/yy',
            yearRange: '-75:+1'
        });
    }

    /* edit-in-place stuff */

    if ($("#user_status").length) {
        $("#user_status").editInPlace({
            url: "user/update_my_status/user",
            params: "ajax=yes",
            bg_over: "#ccc",
            default_text: "Got a status update?",
            show_buttons: true,
            on_blur: "save"
        });
    }

    if ($(".club_status").length) {
        var id = $(".club_status").attr('id').split('_');
        var club_id = id[2];
        $(".club_status").editInPlace({
            url: "user/update_my_status/club/" + club_id,
            params: "ajax=yes",
            bg_over: "#ccc",
            default_text: "Add a headline to the club noticeboard...",
            show_buttons: true,
            on_blur: "save"
        });
    }

    /* Wizard popups etc */

    $("a.ajax_wizard").click( function () {
        var thetitle = $(this).attr('title');
        $("#ajax_dialog")
        .empty()
        .html('<img style="margin: 140px 0px 0px 284px" src="cssimages/v2/ajax-loader.gif" alt="Please wait..." />')
        .dialog({
            autoOpen: false,
            title: thetitle,
            height: 450,
            width: 573,
            resizable: false,
            draggable: false,
            modal: true,
            dialogClass :'clear'
        })
        .dialog('open')
        .dialog('option', 'title', thetitle)
        .dialog('option','width', 573)
        .dialog('option','height', 450)
        .dialog('option','position', 'center')
        .addClass('cms_popup')
        .show()
        .load($(this).attr("href")+'/ajax_ok', rebind);
        return false;
    });

    $('a.internal_invite').click(componentPopup);


    /* AJAX POPUPS FROM FOOTER */
    $('a.ajax_cms').live('click', componentPopup);
    $('a.report_abuse').click(componentPopup);
    $('a.contact_us').click(componentPopup);
    $('a#wizard_close').live('click', function () {
        return ajax_close();
    });

    $('a#invite-facebook').click(function () {
        var title = $(this).attr('title');
        $('#facebook-inviter-dialog').dialog({
            autoOpen: false,
            title: title,
            height: 500,
            width: 573,
            resizable: false,
            draggable: false,
            modal: true,
            dialogClass :'clear'
        })
        .dialog('open')
        .dialog('option', 'title', title)
        .dialog('option', 'width', 573)
        .dialog('option', 'height', 500)
        .dialog('option', 'position', 'center');
        return false;
    });

    $('a#invite-yahoo').click(function () {
        window.open(this.href, width=500, height=500, toolbar=0, resizable=0, scrollbars=0, status=0, center = 1, menubar=0);
        return false;
    });

    $('.inviter-pop').click(function(){
    //    var title = $(this).attr('title');

        $('#box-inviter-dialog')
        .empty()
        .html('<img style="margin: 140px 0px 0px 284px" src="cssimages/v2/ajax-loader.gif" alt="Please wait..." />')
        .dialog({
            autoOpen: false,
  //          title: title,
            height: 500,
            width: 573,
            resizable: false,
            draggable: false,
            modal: true,
            dialogClass :'clear'
        })
        .dialog('open')
        .dialog('option', 'title', title)
        .dialog('option', 'width', 573)
        .dialog('option', 'height', 500)
        .dialog('option', 'position', 'center')
        .show();
     //   .load($(this).attr("href"));//+'/ajax_ok');

        return false;
    });
});

function ajaxClose() {ajax_close()}

function ajax_close() {
    $("div#ajax_dialog").dialog('destroy');
    return false;
}

function componentPopup() {
/*
    Boxy.load($(this).attr('href'), {
        cache: true,
        closeable: true,
        modal: true,
        title: ''+$(this).attr('title')
    });
*/
    var title = $(this).attr('title');
        var $div = $('#ajax_dialog');
        if (!$div.length) {
            $div = $('<div id="ajax_dialog"></div>');
        }

        $div.empty()
        .html('<img style="margin: 140px 0px 0px 284px" src="cssimages/v2/ajax-loader.gif" alt="Please wait..." />')
        .dialog({
            autoOpen: false,
            title: title,
            height: 500,
            width: 573,
            resizable: false,
            draggable: false,
            modal: true,
            dialogClass :'clear'
        })
        .dialog('open')
        .dialog('option', 'title', title)
        .dialog('option','width', 573)
        .dialog('option','height', 500)
        .dialog('option','position', 'center')
        .addClass('cms_popup')
        .load($(this).attr("href"));

        return false;
}

// let's do confirmations please!

function confirmWrapper($el, message) {
    Boxy.confirm(message,
        function () {
            window.location = $el.attr('href');
        },
        {title: 'Confirmation Required'}
    );

    return false;
}

//$('#action-remove-contact').live('click', function () {
//    return confirmWrapper($(this), 'Are you sure you want to remove this person from your contacts?');
//});

$('#action-delete-event').live('click', function () {
    return confirmWrapper($(this), 'Are you sure you want to delete this event?');
});

$('#action-delete-notice').live('click', function () {
    return confirmWrapper($(this), 'Are you sure you want to delete this notice?');
});

$('#action-delete-single-message').live('click', function () {
    return confirmWrapper($(this), 'Are you sure you want to delete this message?');
});

$('#action-delete-single-image').live('click', function () {
    return confirmWrapper($(this), 'Are you sure you want to delete this image?');
});

$('#action-delete-single-video').live('click', function () {
    return confirmWrapper($(this), 'Are you sure you want to delete this video?');
});

$('#action-delete-album').live('click', function () {
    return confirmWrapper($(this), 'Are you sure you want to delete this album?');
});

$('.delete-submit').live('click', function () {
    return confirmWrapper($(this), 'Are you sure you want to remove this link?');
});

// list scroller */

var nav_scroll_pos = 0;
var nav_scroll_size = page_params.max_list_scroll;
var nav_scroll_total = 0;
var max_nav_pos = 0;

function updateListNav() {
    if (nav_scroll_total <= nav_scroll_size) {
        $('#list-nav a.scroll-up, #list-nav a.scroll-down').hide();
    }
    else {
        var pos = 0;
        $('#list-nav .panel-content li').each(function () {
            if (pos >= nav_scroll_pos && pos < (nav_scroll_pos + nav_scroll_size)) {
                $(this).show();
            }
            else {
                $(this).hide();
            }
            pos++;
        });

        $('#list-nav .panel-footer').html('<span class="summary">showing '+(nav_scroll_pos + 1)+'-'+(nav_scroll_pos + nav_scroll_size)+' of '+nav_scroll_total+'</span>');
    }

    if (nav_scroll_pos == 0) {
        $('#list-nav a.scroll-up').animate({opacity:0});
    }
    else {
        $('#list-nav a.scroll-up').css('visibility', 'visible').animate({opacity:1});
    }

    if (nav_scroll_pos == max_nav_pos) {
        $('#list-nav a.scroll-down').animate({opacity:0});
    }
    else {
        $('#list-nav a.scroll-down').css('visibility', 'visible').animate({opacity:1});
    }
}

$(document).ready(function () {
    nav_scroll_total = $('#list-nav .panel-content li').length;
    max_nav_pos = nav_scroll_total - nav_scroll_size;
    updateListNav();
});

$('#list-nav a.scroll-up').live('click', function () {
    nav_scroll_pos--;
    if (nav_scroll_pos < 0) {
        nav_scroll_pos = 0;
    }
    updateListNav();
    return false;
});

$('#list-nav a.scroll-down').live('click', function () {
    nav_scroll_pos++;
    if (nav_scroll_pos > max_nav_pos) {
        nav_scroll_pos = max_nav_pos;
    }
    updateListNav();
    return false;
});

function loadjscssfile(filename, filetype) {
 if (filetype=="js") { //if filename is a external JavaScript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
 }
 else if (filetype=="css") { //if filename is an external CSS file
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
 }
 if (typeof fileref!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref)
}

var filesadded="";

function checkloadjscssfile(filename, filetype) {
 if (filesadded.indexOf("["+filename+"]")==-1) {
  loadjscssfile(filename, filetype)
  filesadded+="["+filename+"]" //List of files added in the form "[filename1],[filename2],etc"
 }
 else {
  //alert("file already added!")
 }
}

//$('#mini-cal-next').live('click', function () {
//    alert('next clicked');
//    return false;
//});
//
//$('#mini-cal-prev').live('click', function () {
//    alert('next clicked');
//    return false;
//});

// function containing all bindings which can't use the jQuery live() binding
// and must be called whenever dynamic content loads
function rebind() {
    stripeAttachments();
    enableDatepicker();
    enableColorPicker();

    $('#invoice-disclaimer').submit(function() {
        if ($('#invoice-terms').length) {
            if (!$('#invoice-terms:checked').length) {
                alert('You must agree to the terms and conditions');
                return false;
            }
        }

        return true;
    });

    $('#edit-payment').submit(function () {
        if ($('#payment_terms').length) {
            if (!$('#payment_terms:checked').length) {
                alert('You must agree to the terms and conditions');
                return false;
            }
        }

        return true;
    });

    if ($('#subscription_active option:selected').length && $('#subscription_active option:selected').val() === 'No') {
        $('.subscription-toggle').fadeOut();
    }
    $('#subscription_active').change(function() {
        if ($(this).find('option:selected').val() === 'No') {
            $('.subscription-toggle').fadeOut();
        }
        else {
            $('.subscription-toggle').fadeIn();
        }
    });

    if ($('#vat_registered option:selected').length && $('#vat_registered option:selected').val() === 'No') {
        $('#vat-toggle').fadeOut();
    }
    $('#vat_registered').change(function() {
        if ($(this).find('option:selected').val() === 'No') {
            $('#vat-toggle').fadeOut();
        }
        else {
            $('#vat-toggle').fadeIn();
        }
    });

    if ($('#search-type option:selected').length && $('#search-type option:selected').val().toLowerCase() === 'organisation') {
        $('#search-activity-div').fadeOut(1);
    }
    $('#search-type').change(function () {
        if ($(this).find('option:selected').val().toLowerCase() === 'organisation') {
            $('#search-activity-div').fadeOut();
        }
        else {
            $('#search-activity-div').fadeIn();
        }
    });

    $('#print-page,.print-page').live('click', function () {
        window.print();
        return false;
    });

    $('#period').change(function () {
        if ($(this).find('option:selected').val() === 'none') {
            var $cost = $('#cost');
            $cost.data('old_val', $cost.val());
            $cost.attr('disabled', true).addClass('disabled').val('n/a');
        }
        else {
            var $cost = $('#cost');
            $cost.attr('disabled', false).removeClass('disabled').val($cost.data('old_val'));
        }
    });

    $('#activity-auto').change(function () {
        var activity_name = $('#activity-auto').val();
        if (activity_name != "") {
            $.post('activity/get_sub_activities', {activity: activity_name}, function (data) {
                $('#interests-overflow').html(data);
            });

            $.post('activity/get_qualifications', {activity: activity_name}, function (data) {
                $('#add-activity-qualifications').html(data);
            });
        }
    });

/*
$('#fb-sharer').click(function(){
    url = $(this).attr('href');
    window.open('http://www.facebook.com/sharer.php?u='+ url +'&t='+encodeURIComponent(document.title),'sharer','toolbar=0,status=0,width=626,height=436');
    return false;
});*/

    $('#fb-sharer').click(function(){
        var title = document.title;
        if ($(this).attr('title').length) {
            title = $(this).attr('title');
        }
        window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent($(this).attr('href'))+'&t='+encodeURIComponent(title),'sharer','toolbar=0,status=0,width=626,height=436');
        return false;
    });

    $('#twit-sharer').click(function(){
        url = $(this).attr('href');
        message = $('#tweet-message').val();
        $.post('user/twitter_share', {'url':url, 'message':message}, function (data){
            if(data.success){
                alert(data.success);
            }else{
                alert(data.failure);
            }
        },"json");

        return false;
    });

    $('#search-activity').change(function () {
        var activity_id = $('#search-activity :selected').val();
        var owner_type = $('#search-type').val();

        $.post('activity/ajax_advanced_search', {activity: activity_id, owner_type: owner_type}, function(data){
            $('#advanced-div').html(data);

            if($('#advanced-div').html() == ""){
                $('#search-advanced').hide();
            }else{
                $('#search-advanced').show();
            }
        });

        if($('#search-advanced').val() == 'hide'){
            $('#advanced-div').show();
        }else{
            $('#advanced-div').hide();
        }
        return false;
    });


    // this is so that without JS, they remain inactive
    //$('select.ajax-role-changer').each(function () {
    //        $(this).attr('disabled', false);
    //    });


    // Tooltips?

    $(".helptip").tooltip({
        track: true,
        delay: 0,
        showURL: false,
        showBody: " - ",
        extraClass: "pretty",
        fixPNG: true,
        opacity: 0.99,
        left: -120
    });

    // in IE, change events don't bubble, despite it being in the DOM spec since world war 2.
    
    $('select.ajax-role-changer').change(function () {
        var $element = $(this);
        var tmp = $(this).attr('id').split('_');
        var role_id = tmp[2];
        var role = $(this).val();
        $.post('index.php/wizard/update_role', {
                role_id: role_id,
                role: role
            },
            function () {
                var to_color = page_params.club_colour; // club colours
                $element.blur();
                $element.effect('highlight', {color: to_color}, 1500);
                alert('User permissions updated.');
            }
        );
    });

    $('div.panel-filter').each(function () {
        if ($(this).closest('.panel-container').find('.panel-content ul li,.feed_item,.filterable,tbody tr').length) {
            $(this).show();
            if ($(this).attr('alt')) {
                $(this).val($(this).attr('alt')).addClass('prompt');
            }
        }
    });

    if (typeof map == "undefined" && $("#loc_lat").length && $("#midi_map_canvas").length)
    {                
        //checkloadjscssfile("js/gmaps.js", "js");
        loadjscssfile("js/gmaps.js", "js") //dynamically load the gmaps.js file
    }
    else if (typeof map == "undefined" && $("#loc_lat").length && $("#mini_map_canvas").length)
    {                
        //checkloadjscssfile("js/small_gmaps.js", "js");
        loadjscssfile("js/small_gmaps.js", "js") //dynamically load the gmaps.js file
    }
  
     $('input[type="text"]').each(function () {
        if (!$(this).val().length || $(this).val() == $(this).attr('alt')) {
            $(this).val($(this).attr('alt')).addClass('prompt');
        }

        $(this).focus(function () {
            if ($(this).val() == $(this).attr('alt')) {
                $(this).val('').removeClass('prompt');
            }
        });

        $(this).blur(function () {
            if (!$(this).val().length) {
                $(this).val($(this).attr('alt')).addClass('prompt');
            }
        });
    });


    $(".ellipsis").each( function () {
        var el = $(this);
        var originalText = el.html();
        var w = el.width();

        var t = $(this.cloneNode(true)).css('position', 'absolute').hide().css('width', 'auto').css('overflow', 'visible');
        t.css('max-width', '10em');
        el.after(t);

        var text = originalText;
        while(text.length > 0 && t.width() > 70) {
            text = text.substr(0, text.length - 1);
            t.html(text + "&hellip;");
        }
        el.html(t.html());

        t.remove();
    });

    // AJAX'ed invite response
    $('input[name="status"]').change(function () {

        setSpinner($('#large-diary'));

        var chosen = $(this).val();

        var data = {
            event_id : $('#event_id').val(),
            token : $('#token').val(),
            user_id : current_user_id,
            status: $(this).val()
        };
        
        $.post(
            'index.php/wizard/update_attendee_status',
            data,
            function (json) {
                location.reload();
                //removeSpinner($('#large-diary'));
                //alert("You've RSVP'd with '" + chosen.capitalize() + "' to this event.");
            },
            "json"
        );
    });

    String.prototype.capitalize = function () {
        return this.replace( /(^|\s)([a-z])/g , function (m,p1,p2) { return p1+p2.toUpperCase(); } );
    };

    if ($(".media_title").length) {
        var tmp = $('.media_title').attr('id').split('_');
        var owner_type = tmp[0];
        var owner_id = tmp[1];
        var album_id = tmp[2];
        var image_id = tmp[3];
        $(".media_title").editInPlace({
            url: owner_type + "/change_media_title/" + owner_id + "/" + album_id + "/" + image_id,
            params: "ajax=yes",
            bg_over: "#ccc",
            default_text: "<i>Enter a title</i>",
            show_buttons: true,
            on_blur: "save"
        });
    }

    // this is so that without JS, they remain inactive
    $('select.ajax-status-changer').each(function () {
        $(this).attr('disabled', false);
    });

    $('select.ajax-status-changer').change(function () {
        var $element = $(this);
        var tmp = $(this).attr('id').split('_');
        var event_id = tmp[1];
        var status = $(this).val();
        $.post('index.php/wizard/update_event_status', {
                event_id: event_id,
                status: status
            },
            function () {
                var to_color = page_params.mystuff_colour; // default to user colours
                if ($('body').hasClass('club')) {
                    to_color = page_params.club_colour; // club colours
                }
                else if ($('body').hasClass('pro')) {
                    to_color = page_params.pro_colour; // club colours
                }
                $element.blur();
                $element.effect('highlight', {color: to_color}, 1500);
            }
        );
    });

    if ($('input[name="all_day"]').attr('checked')) {
        $('span.time,select.time').hide();
    }

    $('fieldset.stock-image select').change(function () {
        $('fieldset.stock-image img.preview').attr('src', $(this).find('option:selected').attr('title'));
    });

    $('#group_image').change(function () {
        var chosen = $('#group_image option:selected').val();
        var avatarimg = 'images/avatar/groups/' + chosen + '.png';
            
        $('.avatar').attr('src', avatarimg);
    });

    $('#role_image').change(function () {
        var chosen = $('#role_image option:selected').val();        
        var avatarimg = 'images/avatar/roles/' + chosen + '.png';

        $('.avatar').attr('src', avatarimg);
    });

    $('#invite-send').live('click', function () {

       var text = $('#email-area').val();
       var count = 0;
       var list = $('#invite-area').text().length;

       if (text != "") {
           alert("You still have emails to add!  Either add them or delete them from the 'Invite Friends by Email' box.");
           return false;
       }
       
       $('#invite-area input[type=checkbox]:checked').each(function () {
            count++;
        });

       if (count == 0) {
           alert("Please add some People to invite");
           return false;
       }
    });

    $('.invite-add').live('click', function () {
        var text = $('#email-area').val();
        
        if (text.indexOf(",") == -1)
            emails = text.split("\n");
        else
            emails = text.split(",");

        setSpinner($('#email-area'));
        $('#email-area').val("");
        processEmails(emails, 'manual');
        return false;
    });

    $('.file-add').live('click', function () {
        $('#box-inviter-dialog').text("");
        $('#box-inviter-dialog').append("<div id='csv-up'><p>Please browse to your CSV file</p><input id='csv' name='csv' type='file' class='input'/><button class='button api-cancel'>Cancel</button><button class='button' id='submit-csv'>Submit</button></div>");
        return false;
    });

    $('.vcard-add').live('click', function () {
        $('#box-inviter-dialog').text("");
        $('#box-inviter-dialog').append("<div id='csv-up'><p>Please browse to your vCard file</p><input id='vcard' name='vcard' type='file' class='input'/><button class='button api-cancel'>Cancel</button><button class='button' id='submit-vcard'>Submit</button></div>");
        return false;
    });

    $('.gmail-add').live('click', function(){
       $('#box-inviter-dialog').load("invite/display_gmail_pop");
    });

    $('a.accept-invite').click(function(){
        var url = $(this).attr('href');
        var $l = $(this);
        $.post(url, {},// {message: message},
        function (data) {
            $l.closest('span').html(data);
        });
        return false;
    });

    $('a.decline-invite').live('click', function () {
        $(this).closest('li').append("<b>No Connection Request Sent</b>");
        $(this).closest('span').remove();
        return false;
    });

}

$('update-streams').live('click', function(){
   return false;
});

$('#facebook-status-share').live('click', function(){
    status = $('.user_status').text();
    $.post('user/facebook_status', {'status':status}, function (data){
        if(data.success){
            alert(data.success);
        }else{
            alert(data.failure);
        }
    },"json");

    return false;
});

$('#twitter-status-share').live('click', function(){
    status = $('.user_status').text();
    $.post('user/twitter_status', {'status':status}, function (data){
        if(data.success){
            alert(data.success);
        }else{
            alert(data.failure);
        }
    },"json");

    return false;
});

$('#twitter-submit-status').live('click', function(){
    status = $('#twitter-status').val();
    $.post('user/twitter_status', {'status':status}, function (data){
        if(data.success){
            alert(data.success);
        }else{
            alert(data.failure);
        }
    },"json");

    return false;
});

$('#twitter-submit-club-status').live('click', function(){
   status = $('#twitter-status').val();
   owner_id = $('#twitter-id').val();
   $.post('club/twitter_status/' + owner_id, {'owner_id':owner_id, 'status':status, 'owner_type':'club'},
   function(data){
        if(data.success){
            alert(data.success);
        }else{
            alert(data.failure);
        }
   }, "json");
   return false;
});

    $('#submit-csv').live('click', function () {
        if ($('#csv').val().length) {
            uploadFile('invite/invite_csv_handle_js', 'csv');
        }else{
            alert("Please select a valid CSV file to upload");
        }
        return false;
    });

    $('#add-activity-send').live('click', function () {

    });

    $('#submit-vcard').live('click', function () {
        if ($('#vcard').val().length) {
        uploadFile('invite/invite_vcard_handle_js', 'vcard');
        }else{
            alert("Please select a valid vCard file to upload");
        }
        return false;
    });

    function uploadFile(sent_url, sent_fileElementId) {
        //starting setting some animation when the ajax starts and completes
        $("#loading")
        .ajaxStart(function () {
            $(this).show();
        })
        .ajaxComplete(function () {
            $(this).hide();
        });

        /*
            preparing ajax file upload
            url: the url of script file handling the uploaded files
            fileElementId: the file type of input element id and it will be the index of  $_FILES Array()
            dataType: it support json, xml
            secureuri:use secure protocol
            success: call back function when the ajax complete
            error: callback function when the ajax failed

                */
        $.ajaxFileUpload
        (
            {
                url: sent_url,
                secureuri:false,
                fileElementId: sent_fileElementId,
                dataType: 'json',
                success: function (data, status)
                {
                    if (typeof(data.error) != 'undefined')
                    {
                        if (data.error != '')
                        {
                            alert(data.error);
                        }else
                        {
                            switch (sent_fileElementId) {
                                case 'csv':
                                   var heading = 'Import CSV Contacts';
                                   break;
                                
                                case 'vcard':
                                   var heading = 'Import vCard Contacts';
                                   break;
                            }
                         //   alert(data.msg);
                      //      count = 0;
                      //      for (var i in data.emails) {
                      //          temp = data.emails[i];
                       //         temp = jQuery.trim(temp);
                       //         if (isValidEmailAddress(temp)) {
                       ///             count++;
                      //          }
                       //     }
                            
                            //if (count > 0) {
                              //  alert(data.emails.length);
                                $('#box-inviter-dialog').text("");

                                //    var title = $(this).attr('title');
                                //   .load($(this).attr("href"));//+'/ajax_ok');
                                $('#box-inviter-dialog').append("<div id='api-container'><h2>" +  heading  + "</h2><input type='checkbox' value='invite_list' id='select-all' class='select-all'/><label id='select-label' for='select-all'>Select/Unselect all</label><div id='api-list'><ul></ul></div><button class='button api-cancel'>Cancel</button><button class='button' id='add-api-emails'>Accept</button></div>");
                                process_api_emails(data.emails, sent_fileElementId);
                        //    }else{
                        //        alert('Please attach a Valid File containing E-mail Addresses');
                        //    }
                        }
                    }
                },
                error: function (data, status, e)
                {
                    alert(e);
                }
            }
        )
    }

    $('#gmail-login').live('click', function(){
        user = $('#google-user').val();
        pass = $('#google-pass').val();

        $.post('invite/gmail_contacts', {'user': user, 'pass': pass},  function(data) {
            
            if(data.error){
                $('#google-user').val("");
                $('#google-pass').val("");
                alert(data.error);
            }else{
                $('#box-inviter-dialog').text("");
                $('#box-inviter-dialog').append("<div id='api-container'><h2>" +  'Gmail'  + "</h2><input type='checkbox' value='invite_list' id='select-all' class='select-all'/><label id='select-label' for='select-all'>Select/Unselect all</label><div id='api-list'><ul></ul></div><button class='button api-cancel'>Cancel</button><button class='button' id='add-api-emails'>Accept</button></div>");
                process_api_emails(data.emails, 'gmail');
            }
        }, "json");
    });

function processEmails(emails, type){
    for (var i in emails){
        //if email is suitable add to
        emails[i] = jQuery.trim(emails[i]);
        if (isValidEmailAddress(emails[i])) {
            //check if email is already in the list, if not add it.
            validlist = $('#invite-list-scroll ul').text();
            if (validlist.indexOf(emails[i]) == -1)
                //$('#invite-list-scroll ul').append("<li><input type='checkbox' name='invite_list[]' checked='checked' value='" + emails[i] + "'/>" + "<span>" + emails[i] + "<input type='hidden' name='type[]' value=" + type + "/><img src='cssimages/" + type + ".jpg' height='10px' width='10px' alt='" + type + "'/></span><button class='remove-attachment'>&nbsp;</button></li>");
                $('#invite-list-scroll ul').append('<li><input type="checkbox" checked="checked" name="invite_list[]" value="' + '*' + emails[i] + '" /><span class="' + type + '">' + emails[i] + '</span></li>');
        }else{
            if (emails[i] != "")
                $('#email-area').val($('#email-area').val() + emails[i] + "\n");
        }
    }
    stripeContacts();
}

function process_api_emails(emails, type) {

    for (var i in emails){
        contact = emails[i];
        //if email is suitable add to
//alert("email:" + contact.email);
   //     contact.email = jQuery.trim(contact.email);

        if (isValidEmailAddress(contact.email)) {
            //check if email is already in the list, if not add it.
            validlist = $('#api-list ul').text();
            if (validlist.indexOf(contact.email) == -1)
                //$('#invite-list-scroll ul').append("<li><input type='checkbox' name='invite_list[]' checked='checked' value='" + emails[i] + "'/>" + "<span>" + emails[i] + "<input type='hidden' name='type[]' value=" + type + "/><img src='cssimages/" + type + ".jpg' height='10px' width='10px' alt='" + type + "'/></span><button class='remove-attachment'>&nbsp;</button></li>");
                $('#api-list ul').append('<li><input type="checkbox" class="api-check" name="invite_list[]" value="'+ contact.name + '*' + contact.email + '" /><span class="' + type + '">' + contact.name + ' (' + contact.email + ') ' + '</span></li>');
        }else{
            if (emails[i] != "") {}
           //     $('#email-area').val($('#email-area').val() + emails[i] + "\n");
        }
    }
    stripeContacts();
}

$('.api-cancel').live('click', function () {
    ajax_close();
    $('div#box-inviter-dialog').dialog('close');
    return false;
});

$('#add-api-emails').live('click', function () {
    var li_array = [];

    $('#api-list input[type=checkbox]:not(.select-all):checked').each(function () {
        li_array.push($(this).closest('li').html());
    });
   
    for (var r in li_array) {
        var row = '<li>' + li_array[r] + '</li>';
        var bar = $(row);
        bar.find(':checkbox').attr('checked', 'checked');

        $('#invite-list-scroll ul').append(bar);
    }
    $('div#box-inviter-dialog').dialog('close');
    
    stripeContacts();
    return false;
});

$('#send-internal-invite').live('click', function () {
    var li_array = [];

    $('#api-list input[type=checkbox]:not(.select-all):checked').each(function () {
        li_array.push($(this).val());
    });
        var club_id = $('input[name=club]').val();
        $.post('invite/multiple_internal_invite', {'invitees': li_array, 'club': club_id}, function (data) {

            $('#ajax_dialog').html(data);
        });
        return false;
});

$('#search-advanced').live('click', function () {
    if($(this).val() == 'advanced'){
        $('#advanced-div').slideDown('slow');
        $(this).val('hide');
    }else{
        $('#advanced-div').slideUp('slow');
        $(this).val('advanced');
    }
    
    return false;
});

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.) {2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
}

// call it once on page load
$(document).ready(function () {
    rebind();
});

// facebook shizzle

function FB_onLogout() {
    FB.Connect.logout(function () {
        window.location.href = 'user/logout/';
    });
}

function FB_onLogin() {
    FB.Connect.ifUserConnected('front/login/facebook/', null);
    return true;
}

function FB_onLink() {
    $('#social-media-settings').addClass('working');
    $.post('wizard/fb_link/', {}, function (data) {
        $('#social-media-settings').before(data).remove();
    });
    return true;
}

function FB_onUnLink() {
    Boxy.confirm('Unlinking your facebook account will also log you out of MyClubLink. Your other settings will not be affected.<br />Are you sure you want to unlink your account?',
        function () {
            $.post('wizard/fb_unlink/', {}, function () {
                FB_onLogout();
            });
        },
        {title: 'Confirmation Required'}
    );
    return false;
}

