
var head,
    body
;

function roundNum(Number, DecimalPlaces) {
    return Math.round(parseFloat(Number) * Math.pow(10, DecimalPlaces)) / Math.pow(10, DecimalPlaces);
}

function roundFixed(Number, DecimalPlaces) {
    return roundNum(Number, DecimalPlaces).toFixed(DecimalPlaces);
}

(function ($, window, document, undefined) {

    if (typeof $ === 'undefined') {
        //  jQuery isn't available - abort!
        return;
    }

    //  --  Instantiate just ONE jQuery object, use this to find other elements
    //      rather than creating a new jQuery object for each selector
    $.root = new $.prototype.init(document);

    //  --  Make Rocket Go Now
    $.root.ready(function () {

        //  --  Define head and body elements
        head = $.root.find('head');
        body = $.root.find('body');

        //  --  Add "js" class to body for styling
        body.addClass('js');

        //  --  Invoke plugins, yo - body.find('#element').pluginName()
        body.find('.alloc_drop').allocationDropdown();
        body.find('.donation_form').donationForm();
        body.find('.filter_map').filterMap();
        body.find('.requests li').requests();
        body.find('.messages_delete').selectAll();

    });



    //  --  Custom Plugins
    (function () {

        $.prototype.allocationDropdown = function () {

            return this.each(function () {
                var trigger   = $(this),
                    arrow     = false,
                    breakdown = trigger.parent().next()
                ;

                breakdown.find('li:odd').addClass('alt');

                trigger.append('<span />');

                arrow = trigger.find('span');

                trigger.bind('click', function () {
                    if (arrow.hasClass('open')) {
                        arrow.removeClass('open');
                        breakdown.slideUp('250');
                    }
                    else {
                        arrow.addClass('open');
                        breakdown.slideDown('250');
                    }
                });
            });

        };



        $.prototype.donationForm = function () {

            return this.each(function () {
                var form       = $(this),
                    fieldset   = form.find('fieldset'),
                    ajax_input = fieldset.find('input[name=ajax]'),
                    top_login  = body.find('.top_login')
                ;

                if (ajax_input.length === 0) {
                    fieldset.append('<input type="hidden" name="ajax" value="true" />');
                }

                form.submit(function () {
                    var button      = form.find('button'),
                        amount      = form.find('input[name=amount]').val(),
                        values      = form.closest('div.request_info').siblings('p.needs'),
                        target_val  = parseFloat(values.find('strong.target_val').text().substring(1)),
                        current_val = parseFloat(values.find('strong.current_val').text().substring(1)),
                        max_val     = isNaN(current_val) ? target_val : target_val - current_val,
                        error       = false
                    ;

                    button.attr('disabled', 'disabled');
                    max_val = roundNum(max_val, 2);

                    if (amount) {
                        if (isNaN(amount)) {
                            error = 'Your donation must be a number';
                        }
                        else if (amount === 0) {
                            error = 'Your donation must be more than &pound;0';
                        }
                        else if (amount > max_val) {
                            error = "Your donation can't exceed &pound;" + max_val;
                        }
                    }
                    else {
                        error = 'Your donation amount was empty!';
                    }

                    amount = parseFloat(amount);

                    if (error === false) {
                        $.ajax({
                            type: 'POST',
                            url: form.attr('action'),
                            data: form.serialize(),
                            dataType: 'text',
                            complete: function (response) {
                                var top_current,
                                    top_new,
                                    current_val,
                                    new_val,
                                    pledged_cur,
                                    pledged_new
                                ;

                                if (response) {
                                    fieldset.animate({ opacity : 0 }, 250, 'linear').end();

                                    form.closest('.donation_form_wrapper').html('<p class="confirm"><span>Your donation has been added to your giving basket</span> <a href="/gift-basket/">View Gift Basket &raquo;</a></p>');
                                    form.remove();

                                    //	Insert HTML where necessary
                                    if (!top_login.find('.big_link')[0]) {
                                        top_login.find('p').append(' | Total pledged: <strong>&pound;0</strong> | <a class="big_link" href="/gift-basket/">View Gift Basket</a>');
                                    }

                                    if (!values.find('.pledged_val')[0]) {
                                        values.append(' | <strong class="pledged_val">&pound;0</strong> in your <a href="/gift-basket/">Gift Basket</a>');
                                    }

                                    top_current = top_login.find('strong').text().substr(1);
                                    top_new     = parseFloat(top_current) + amount;
                                    top_new     = roundFixed(top_new, 2);

                                    top_login.find('strong').html('&pound;' + top_new).effect('highlight', { color : '#fff' });

                                    current_val = values.find('.current_val').text().substr(1);
                                    new_val     = isNaN(current_val) ? amount : parseFloat(current_val) + amount;
                                    new_val     = roundFixed(new_val, 2);

                                    values.find('.current_val').html('&pound;' + new_val).effect('highlight');

                                    pledged_cur = values.find('.pledged_val').text().substr(1);
                                    pledged_new = isNaN(pledged_cur) ? amount : parseFloat(pledged_cur) + amount;
                                    pledged_new = roundFixed(pledged_new, 2);

                                    values.find('.pledged_val').html('&pound;' + pledged_new).effect('highlight');
                                }
                                else {
                                    error = "There was an error! Please try again!";
                                }
                            }
                        });
                    }
                    else {
                        form.find('label').html(error).addClass('error').effect('pulsate', { times : 2 });
                        button.removeAttr('disabled');
                    }

                    return false;
                });
            });

        };



        $.prototype.filterMap = function () {

            return this.each(function () {
                var map            = $(this),
                    map_img        = map.find('img'),
                    locations      = body.find('.filter_locations'),
                    bg_pos         = '',
                    current_region = map.attr('id').split('_')[1],
                    map_src        = '/img/design/map/js/' + current_region + '.png'
                ;

                function map_highlight(region) {
                    switch (region) {
                    case 'north-east':
                        bg_pos = '-280px  center';
                        break;
                    case 'north-west':
                        bg_pos = '-560px  center';
                        break;
                    case 'yorkshire-humber':
                        bg_pos = '-840px  center';
                        break;
                    case 'west-midlands':
                        bg_pos = '-1120px center';
                        break;
                    case 'east-midlands':
                        bg_pos = '-1400px center';
                        break;
                    case 'south-west':
                        bg_pos = '-1680px center';
                        break;
                    case 'south-east':
                        bg_pos = '-1960px center';
                        break;
                    case 'london':
                        bg_pos = '-2240px center';
                        break;
                    case 'east':
                        bg_pos = '-2520px center';
                        break;
                    case 'all-regions':
                        bg_pos = '-2800px center';
                        break;

                    default:
                        bg_pos = 'left center';
                        break;
                    }

                    map_img.css({ backgroundPosition : bg_pos });

                    locations.find('ul li a').removeClass('hover');

                    if (region !== 'default') {
                        locations.find('ul li.' + region + ' a').addClass('hover');
                    }
                }

                $('<img />')
                    .attr('src', map_src)
                    .load(function () {
                        map_img
                            .attr('src', '/img/design/map/trans.png')
                            .css({
                                backgroundImage: 'url(' + map_src + ')',
                                backgroundPosition: 'left center',
                                backgroundRepeat: 'no-repeat'
                            });

                        $('map#locations area, .filter_locations ul li').bind({
                            mouseenter: function () {
                                map_highlight($(this).attr('class'));
                            },
                            mouseleave: function () {
                                map_highlight('default');
                            }
                        });
                    });
            });

        };



        $.prototype.requests = function () {

            return this.each(function () {
                var request_li   = $(this),
                    learn_link   = request_li.find('.learn_more'),
                    request_info = request_li.find('.request_info'),
                    label        = request_info.find('label'),
                    input        = request_info.find('input'),
                    close_link   = $('<div class="close_this"><a href="#">Close</a></div>').appendTo(request_li).find('a').hide()
                ;

                learn_link.find('a').bind('click', function () {
                    request_li.addClass('active');
                    request_info.slideDown();
                    learn_link.fadeOut();
                    close_link.fadeIn();

                    return false;
                });

                close_link.bind('click', function () {
                    close_link.fadeOut();
                    request_li.removeClass('active');
                    request_info.slideUp(500, function () {
                        label.text('How much would you like to donate?').removeClass('error');
                        input.val('');
                        learn_link.fadeIn();
                    });

                    return false;
                });
            });

        };



        $.prototype.selectAll = function () {

            return this.each(function () {
                var form       = $(this),
                    select_all = form.find('a#checkboxall'),
                    checkboxes = form.find(':checkbox[name^=delete]')
                ;

                select_all.bind('click', function () {
                    if (select_all.hasClass('active')) {
                        select_all
                            .removeClass('active')
                            .text('Select All');

                        checkboxes.attr('checked', false);
                    }
                    else {
                        select_all
                            .addClass('active')
                            .text('Deselect All');

                        checkboxes.attr('checked', true);
                    }
                });
            });

        };

    }());
    //  --  Custom Plugins DONE, yeah?

}(jQuery, this, this.document));
//  --  Good.. Can you say it faster?

