dojo.require('doox.dom');
dojo.require('dijit.form.Button');
menuVisible = false;

dojo.declare('Classifieds', null, {

    constructor: function() {

        this.categoriesMenu = dojo.query('.mainMenu .categories')[0];
        
        // Get position of categories button, and place the categories menu
        // just below that
        var categoriesButtonPosition = 
            dojo.coords(dojo.byId('displayCategories'));
/*        alert(categoriesButtonPosition.t);
        alert(categoriesButtonPosition.l);*/
/*        this.categoriesMenu.style.left = categoriesButtonPosition.x + 'px';*/
//        this.categoriesMenu.style.top = 
//            (categoriesButtonPosition.y + dojo.byId('displayCategories').clientHeight) + 'px'; 
//        console.dir(dojo.byId('displayCategories'));
        this.categoriesMenuPosition = dojo.coords(this.categoriesMenu);

        // Set up categories dropdown events
        dojo.connect(dojo.byId('displayCategories'), 'onclick', 
            dojo.hitch(this, this.toggleCategoriesMenu));

        dojo.connect(dojo.query('body')[0], 'onclick',
            dojo.hitch(this, this.closeCategoriesMenu));

        var sortingSelect = dojo.query('form.sorting select')[0];
        if (sortingSelect) {
            dojo.connect(sortingSelect, 'onchange',
                dojo.hitch(this, function(evt) {
                    evt.target.form.submit();
                }));
        }

        //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 (dojo.byId('sortSubmit'))
            dojo.byId('sortSubmit').style.display = 'none';
    },

    /**
     *  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.
     */
    closeCategoriesMenu: function(evt) {
            body = dojo.query('body')[0];
            displayButton = dojo.byId('displayCategories');
            displayCategories = dojo.query('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.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) {
                categoriesMenuFadeOut = dojo.fadeOut({ node: this.categoriesMenu, duration: 500 });
                dojo.connect(categoriesMenuFadeOut, 'onEnd', function () {
                    dojo.query('.mainMenu .categories')[0].style.display = 'none';
                    dojo.removeClass(dojo.query('#classifieds .mainMenu #displayCategories .select')[0], "selected") 
                });

                categoriesMenuFadeOut.play();
                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.
     */
    toggleCategoriesMenu: function(evt) {
        evt.preventDefault();

        if (!menuVisible) {
            this.categoriesMenu.style.display = 'block';
            
            categoriesMenuFadeIn = dojo.fadeIn({ node: this.categoriesMenu, duration: 500 });
            dojo.connect(categoriesMenuFadeIn, 'onEnd', function() {
                dojo.addClass(dojo.query('#classifieds .mainMenu #displayCategories .select')[0], "selected")
            });

            categoriesMenuFadeIn.play();
            menuVisible = true;
        }
        else {
            // Set display to none and change the direction of the arrow after the fadeOut is done
            categoriesMenuFadeOut = dojo.fadeOut({ node: this.categoriesMenu, duration: 500 });
            dojo.connect(categoriesMenuFadeOut, 'onEnd', function () {
                dojo.query('.mainMenu .categories')[0].style.display = 'none';
                dojo.removeClass(dojo.query('#classifieds .mainMenu #displayCategories .select')[0], "selected") 
            });

            categoriesMenuFadeOut.play();
            menuVisible = false;
        }
    }

});



/**
 * Init upload boxes!
 */
function initUploadBoxes() {
    var file = dojo.byId('uploadImageBox');
    if (file) {
        dojo.connect(file, 'onchange', createNewUploadBox);
    }
}

function createNewUploadBox(ev) {
    // Create element
    if (doox.dom.getFirstAncestorByTag(ev.target, 'ul').childNodes.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);
        dojo.disconnect(ev.target);
        dojo.connect(url, 'onchange', createNewUploadBox);
        url.focus();
    }
}

function hideTextOnSelectCb(evt) {
    var elem = evt.target;
    var type = evt.type;

    if (type == 'blur') {
        if (elem.value == '')
            elem.value = elem.initialValue;
    }
    if (type == 'focus') {
        if (elem.value == elem.initialValue)
            elem.value = '';
    }
}

function hideTextOnSelect(elem) {
    elem.initialValue = elem.value;
    dojo.connect(elem, "onfocus", hideTextOnSelectCb);
    dojo.connect(elem, "onblur", hideTextOnSelectCb);
}

function addOnSelectTextEvent() {
    var user = dojo.byId("username");
    var password = dojo.byId("password");

    if (user)
        hideTextOnSelect(user);
    if (password)
        hideTextOnSelect(password);
}

dojo.addOnLoad(initUploadBoxes);
dojo.addOnLoad(addOnSelectTextEvent);
dojo.addOnLoad(function() { new Classifieds(); });
