(function ($) {
    AWAL = {};
    AWAL.Log = function(msg) {
        if (typeof(console) != "undefined") {
            console.log(msg);
        }
    };
    AWAL.Constants = {
        DELETE_MESSAGE: 'Deletes cannot be undone. Are you sure you want to continue?',
        INVALID_AUDIO_MESSAGE: 'Sorry, you cannot upload that file.\n\nPlease select a WAV file.',
        ALLOWED_AUDIO: {
            '.WAV': 1,
            '.wav': 1
        },
        DATE_IN_PAST_MESSAGE: 'You selected a date in the past!',
        DJANGO_ADMIN_WARNING_MESSAGE: "You can really cause some damage with the Django Admin. Please make sure you know what you're doing.\n\nAre you sure you want to continue?",
        DUPLICATE_UPC_ACTION: 'There is a duplicate of this UPC in the platform.\n\nAre you sure you want to perform this action?'
    };
    AWAL.Globals = {
        isCtrl: false,
        isAlt: false
    };
    
    AWAL.Utils = {};
    AWAL.Utils.getDateString = function(d_obj) {
        /* Return yyyy-mm-dd string representation of a date object. */
        var month = (d_obj.getMonth() + 1).toString();
        var day = d_obj.getDate().toString();
        month = (month.length == 1) ? '0' + month : month;
        day = (day.length == 1) ? '0' + day : day;
        return d_obj.getFullYear().toString() + '-' + month + '-' + day;
    };

    AWAL.Main = function(params) {
        /* This function is for things that happen on many pages. */

        /* Search fields - submit on Enter key. */
        $("#id_term").keyup(function(event){
            if(event.keyCode == 13){
                $("form:first").submit();
            }
        });

        /* Delete button confirm. */
        $('.action_delete,.delete').click(function() {
            return confirm(AWAL.Constants.DELETE_MESSAGE);
        });

        /* Show date picker for date fields. */
        $("input[name$='date'],input[type=date]").datepicker({ dateFormat: 'yy-mm-dd' });

        /* Initialist fancybox */
        $(".fancybox_image").fancybox({
            'hideOnContentClick': true,
            'type' : 'image',
            'cyclic': true
        });

        /* Django admin link warning. */
        $('.django_admin_link').click(function() {
            return confirm(AWAL.Constants.DJANGO_ADMIN_WARNING_MESSAGE);
        });

        /* Confirmation box when delivering/exporting/queuing products with duplicate UPCs. */
        $('a.duplicate_upc').click(function() {
            return confirm(AWAL.Constants.DUPLICATE_UPC_ACTION);
        });
    };

    AWAL.SetupGridToggling = function () {
        $(document).keyup(function(e) {
            if (e.keyCode == 17) {
                AWAL.Globals.isCtrl = false;
            }
            if (e.keyCode == 18) {
                AWAL.Globals.isAlt = false;
            }
        });
        $(document).keydown(function(e) {
            if (e.keyCode == 17) {
                AWAL.Globals.isCtrl = true;
            }
            if (e.keyCode == 18) {
                AWAL.Globals.isAlt = true;
            }
            if (e.keyCode == 71 && AWAL.Globals.isAlt) {
                var g = $("#design-grid");
                if (g.css("display") == "none") {
                    g.css("display", "block");
                    g.css("height", $("body").height() + "px");
                } else {
                    g.css("display", "none");
                }
            }
        });
    };

    AWAL.SetupSlideshow = function(selector) {
        $(selector).cycle({
            fx: 'fade',
            timeout: 7000,
            speed: 2000
        });
    };

    AWAL.CheckExtension = function(selector) {
        var self = this;

        this.init = function(selector) {
            /* Bind extension check to field change. */
            $(selector).each(function(i, el) {
                $(el).bind('change', function(){
                    if (!self.doCheck($(el).val())) {
                        $(el).val("");
                        var small = $(el).closest("div").find('small')[0];
                        $(small).text('');
                        alert(AWAL.Constants.INVALID_AUDIO_MESSAGE);
                    }
                });
            });
        };

        this.doCheck = function (filename) {
            var ext = filename.slice(filename.lastIndexOf('.'));
            if (AWAL.Constants.ALLOWED_AUDIO[ext]) {
                return true;
            } else {
                return false;
            }
        };

        self.init(selector);
    };

    AWAL.DistributionPage = function(params) {
        /*
         * Required parameters:
            is_world: boolean
            is_africa: boolean
            is_asia: boolean
            is_americas: boolean
            is_europe: boolean
            is_oceania: boolean
            sales_start_date: jQuery element - text input
            world: jQuery element - checkbox input
         */

        var self = this;
        var continents = Array(); /* Array of continent checkboxes. */

        this.init = function(params) {
            /* Create array of continent check boxes. */
            $.each(['africa', 'americas', 'asia', 'europe', 'oceania'], function(index, value) {
                continents.push($("#id_continent_" + value));
            });

            /* If is_world then check world, continent and all country checkboxes,
             * otherwise; check continent boxes if appropriate.
             */
            if (params.is_world) {
                self.checkAll();
            } else {
                if (params.is_africa) {
                    $("#id_continent_africa").attr('checked', 'checked');
                }
                if (params.is_asia) {
                    $("#id_continent_asia").attr('checked', 'checked');
                }
                if (params.is_americas) {
                    $("#id_continent_americas").attr('checked', 'checked');
                }
                if (params.is_europe) {
                    $("#id_continent_europe").attr('checked', 'checked');
                }
                if (params.is_oceania) {
                    $("#id_continent_oceania").attr('checked', 'checked');
                }
            }

            /* Add territories-list class to territories and hide continent listing. */
            $.each(['africa', 'americas', 'asia', 'europe', 'oceania'], function(index, value) {
                var div = $('#' + value);
                div.find('ul:eq(1)').addClass('territories-list');
            });
            $('.continents').hide();

            /* Continent [de]select all. */
            $.each(continents, function(index, continent) {
                var countries = continent.parent().parent().parent().siblings().find("input");

                /* Mass [de]select countries in a continent. */
                continent.bind('click', function() {
                    countries.each(function() {
                        $(this).attr('checked', continent.attr('checked'));
                    });
                    var all = true;
                    $.each(continents, function(index, continent_i) {
                        if(!continent_i.attr('checked')) {
                            all = false;
                        }
                    });
                    params.world.attr('checked', all);
                });

                /* Deal with reselecting continent and world checkboxes when appropriate. */
                countries.each(function() {
                    var country = $(this);
                    country.bind('click', function(){
                        if (!country.attr('checked')){
                            continent.attr('checked', false);
                            params.world.attr('checked', false);
                        } else {
                            var all_continent = true;
                            countries.each(function() {
                                if (!$(this).attr('checked')) {
                                    all_continent = false;
                                }

                                /* Reselect continent checkbox if appropriate. */
                                continent.attr('checked', all_continent);
                                /* Check if we should reselect world. */
                                var all = true;
                                $.each(continents, function(index, continent_i) {
                                    if(!continent_i.attr('checked')) {
                                        all = false;
                                    }
                                });
                                params.world.attr('checked', all);
                            });
                        }
                    });
                });
            });

            self.handleShowHideCountries();
            self.handleWorldCheckboxClick();
            self.validateStartDate();
        };

        this.checkAll = function() {
            $(params.world).attr('checked', 'checked');
            $.each(continents, function(index, continent) {
                continent.attr('checked', 'checked');
                var countries = continent.parent().parent().parent().siblings().find("input");
                countries.each(function() {
                    $(this).attr('checked', 'checked');
                });
            });
        };

        this.handleShowHideCountries = function() {
            $('#show-countries-link').bind('click', function(e) {
                $('.continents').slideToggle(function()
                {
                    if ($('.continents').is(":visible")) {
                        $('#show-countries-link').text('Hide countries');
                    } else {
                        $('#show-countries-link').text('Show all countries');
                    }
                });
                e.preventDefault();
            });
        };

        this.handleWorldCheckboxClick = function() {
            params.world.bind('click', function() {
                var new_state = params.world.attr('checked');
                $.each(continents, function(index, continent) {
                    continent.attr('checked', new_state);
                    var countries = continent.parent().parent().parent().siblings().find("input");
                    countries.each(function() {
                        $(this).attr('checked', new_state);
                    });
                });
            });
        };

        this.validateStartDate = function() {
            $(params.sales_start_date).bind('change', function() {
                /* Check date isn't(/is) in the past. */
                var today = new Date();
                today = AWAL.Utils.getDateString(today);
                if ($(params.sales_start_date).val() < today) {
                    alert(AWAL.Constants.DATE_IN_PAST_MESSAGE);
                }
            });
        };

        self.init(params);
    };

    AWAL.TrackSorting = function(params) {
        /*
         * Parameters parameters:
            items - jQuery selector, e.g. 'tr', 'tr:gt(0)'
            containment - set if required
         */

        var self = this;
        var p = params;

        this.init = function() {
            if ($('.volumetracks.ui-sortable').length) {
                $('.volumetracks.ui-sortable.reorder').css('cursor','move');
                $('.volumetracks.ui-sortable').sortable({
                    opacity: 0.7,
                    placeholder: 'highlight',
                    items: p.items,
                    handle: '.reorder',
                    containment: p.containment,
                    axis: 'y',
                    connectWith: $('.volumetracks.ui-sortable'),
                    forceHelperSize: true,
                    forcePlaceholderSize: true,
                    tolerance: 'pointer',
                    stop: function(e, ui) {
                        self.postTrackNumbers();
                    },
                    change: function(e, ui) {
                        $(".highlight").html("<td colspan='100%'>&nbsp;</td>");
                    },
                    helper: function(e, ui) {
                        ui.children().each(function() {
                            $(this).width($(this).width());
                        });
                        return ui;
                    },
                    deactivate: function(e, ui) {
                        $(ui.item).parent().find('tr.empty').remove();

                        $('.volumetracks.ui-sortable').each(function() {
                            if($(this).find('tr').length == 0) {
                                var empty_row = '<tr class="empty"><td>Disc empty</td></tr>';
                                $(this).find('tbody').append(empty_row);
                            }
                        });
                    }
                });
                $(".volumetracks.ui-sortable").disableSelection();
                self.postTrackNumbers();
            }
        };

        this.getSerializedTrackNumbers = function() {
            var volumes = [];
            $('.volumetracks').each(function() {
                volumes.push("volume="+$(this).sortable('toArray').join());
            });
            return volumes.join('&');
        };

        this.prepareTrackNumbers = function() {
            $('.volumetracks.ui-sortable').each(function(){
                var track_number = 1;
                $(this).find(p.items).not('.empty').each(function() {
                    $(this).find('td:first').text(track_number++)
                });

                /* Add even and odd classes that can be used for styling. */
                $(this).find('tr:even').each(function() {
                    $(this).removeClass('even').addClass('odd');
                });
                $(this).find('tr:odd').each(function() {
                    $(this).removeClass('odd').addClass('even');
                });
            });
        };

        this.postTrackNumbers = function() {
            self.prepareTrackNumbers();
            var data = self.getSerializedTrackNumbers();
            $.post("reorder/", data);
        };

        self.init();
    };
    
    AWAL.BriefSubmissionSorting = function() {
        var self = this;

        this.init = function() {
            if ($('.tracksubmissions.ui-sortable').length) {
                $('.tracksubmissions.ui-sortable.reorder').css('cursor','move');
                $('.tracksubmissions').each(function() {
                    $(this).find('tr:first').height('10px');
                });
                $(".tracksubmissions.ui-sortable").sortable({
                    opacity: 0.7,
                    placeholder: 'highlight',
                    items: 'tr:gt(0)',
                    handle: '.reorder',
                    axis: 'y',
                    connectWith: $('.tracksubmissions.ui-sortable'),
                    forceHelperSize: true,
                    forcePlaceholderSize: true,
                    tolerance: 'pointer',
                    stop: function() {
                        self.postSubmissionOrdering();
                    },
                    change: function(e, ui) {
                        $(".highlight").html("<td colspan='100%'>&nbsp;</td>");
                    },
                    helper: function(e, ui) {
                        ui.children().each(function() {
                            $(this).width($(this).width());
                        });
                        return ui;
                    }
                });
                self.postSubmissionOrdering();
            }
        };

        this.getSerializedSubmissionOrdering = function () {
            var ordering = 'ordering=';
            $('.tracksubmissions').each(function() {
                ordering += $(this).sortable('toArray').join();
            });
            return ordering;
        };

        this.prepareSubmissionOrdering = function () {
            $('.tracksubmissions.ui-sortable').each(function(){
                var track_number = 1;
                $(this).find('tr:gt(0)').each(function() {
                    $(this).find('td:first').text(track_number++)
                });

                $(this).find('tr:even').each(function() {
                    $(this).removeClass('even').addClass('odd');
                });
                $(this).find('tr:odd').each(function() {
                    $(this).removeClass('odd').addClass('even');
                });
            });
        };

        this.postSubmissionOrdering = function() {
            self.prepareSubmissionOrdering();
            var data = self.getSerializedSubmissionOrdering();
            $.post("reorder/", data);
        };

        self.init();
    };

    AWAL.AdminSubmissionFavourites = function(params) {
        /*
         * Example parameters:
            favourite_class: 'action_favourite',
            favourite_text: 'Favourite'
            unfavourite_class: 'action_unfavourite'
            unfavourite_text: 'Unfavourite'
         */

        var self = this;

        this.setupClick = function(current_class, new_class, current_text, new_text) {
            $('.' + current_class + ',.' + new_class).bind('click', function(event) {
                var link = $(this);
                var action_url = $(this).attr('href');
                $.ajax({
                    url: action_url,
                    success: function(url) {
                        link.toggleClass(current_class);
                        link.toggleClass(new_class);
                        link.attr('href', url);
                        link.attr('title',
                            link.attr('title') == current_text ? new_text : current_text
                        );
                        link.text(link.attr('title'));
                    }
                });
                return event.preventDefault();
            });
        };

        this.setupClick(params.favourite_class, params.unfavourite_class, params.favourite_text, params.unfavourite_text);
    };
})(jQuery);

$(function () {
    AWAL.Main();
});

