(function($) {
    menuVisible = false;

    window.Classifieds = function() {

        this.constructor = function() {

            this.categoriesMenu = $('.mainMenu .categories');
            
    //        this.categoriesMenuPosition = dojo.coords(this.categoriesMenu);

            // Set up categories dropdown event
            $('#displayCategories').bind('click', 
                $.proxy(this.toggleCategoriesMenu, this));

            $("body").bind('click',
                $.proxy(this.closeCategoriesMenu, this));

            var sortingSelect = $('form.sorting select')[0];
            if (sortingSelect) {
                $(sortingSelect).bind('change',
                    $.proxy(function(evt) {
                        evt.target.form.submit();
                    }, this));
            }

            //dojo.connect(dojo.byId('displayCategories'), 'onmouseout', 
            //    dojo.hitch(this, this.toggleCategoriesMenu));
            //dojo.connect(this.categoriesMenu, 'onmouseout', 
            //    dojo.hitch(this, this.toggleCategoriesMenu));
                /*
            dojo.connect(this.categoriesMenu, 'onmouseover', 
                dojo.hitch(this, this.toggleCategoriesMenu));*/

            /*dojo.connect(dojo.query('.categories')[0], 'onmouseout',
                dojo.hitch(this, this.toggleCategoriesMenu));*/

            /* Hide the submit button in the adBrowser when using javascript */
            if ($('#sortSubmit').length)
                $("#sortSubmit").hide();
        };

        /**
         *  Closes the CategoriesMenu while clicking anywere on the page but the CategoriesMenu and the 'kategorier' button.
         *  This allows the user to just click anywhere on the page to close the Menu.
         */
        this.closeCategoriesMenu = function(evt) {
                body = $('body')[0];
                displayButton = $('#displayCategories')[0];
                displayCategories = $('div.mainMenu ul.categories')[0];

                currentDom = evt.target;
                closeMenu = true;
                loop = true;

                /**
                 * Ensures that the Menu won't close when the user opens it, or when the user is clicking on the menu.
                 * To do this the While loop goes throught all the parrent DomObjects of the targeted object, to insure that none 
                 * of them are the Menu or the 'kategorier' button.
                 */
                while (loop) {
                    if (currentDom == null)
                        break;

                    if (currentDom.parentNode == displayCategories || currentDom == displayCategories || 
                    currentDom == displayButton || currentDom.parentNode == displayButton) {
                        closeMenu = false;
                        loop = false;
                    }

                    if (currentDom.parentNode == body || currentDom == body) {
                       loop = false; 
                    }

                    currentDom = currentDom.parentNode;
                }

                if (closeMenu) {
                    this.categoriesMenu.fadeOut(500, function() {
                        $(this).hide();
                        $("#classifieds .mainMenu #displayCategories .select").removeClass("selected");
                    });

                    menuVisible = false;
                }
        };

        /**
         * Renders the CategoriesMenu visible or not visible by clicking the 'Kategorier' button.
         * Be aware of the diference between this function and the 'closeCategoriesMenu' function.
         */
        this.toggleCategoriesMenu = function(evt) {
            evt.preventDefault();

            if (!menuVisible) {
                this.categoriesMenu.css('opacity', 1);
                this.categoriesMenu.fadeIn(500, function() {
                    $(this).show();
                    $('#classifieds .mainMenu #displayCategories .select').addClass("selected");
                });

                menuVisible = true;
            }
            else {
                // Set display to none and change the direction of the arrow after the fadeOut is done
                this.categoriesMenu.fadeOut(500, function() {
                    $(this).hide();
                    $("#classifieds .mainMenu #displayCategories .select").removeClass("selected");
                });

                menuVisible = false;

            }
        };
        this.constructor();
    };



    /**
     * Init upload boxes!
     */
    function initUploadBoxes() {
        var file = $('#uploadImageBox');
        if (file.length) {
            file.one("change", createNewUploadBox);
        }
    }

    function createNewUploadBox(ev) {
        // Create element
        if ($(ev.target).closest('ul').children().length < 8) {
            var url = document.createElement('input');
            var li = document.createElement('li');
            url.setAttribute('type', ev.target.getAttribute('type'));
            url.setAttribute('id', ev.target.getAttribute('id'));
            url.setAttribute('name', ev.target.getAttribute('name'));
            ev.target.setAttribute('id', '');
            doox.dom.getFirstAncestorByTag(ev.target, 'ul').appendChild(li).appendChild(url);
            $(url).one('change', createNewUploadBox);
            url.focus();
        }
    }

    $(document).ready(initUploadBoxes);
    $(document).ready(function() { new Classifieds(); });
})(jQuery);

