/* -*- js2 -*-
 *
 * $Id$
 */

function FancyMenu(target, type) {

    var arrowOpacity = 0.15;

    var theMenu = jQuery(target);
    var $ = jQuery;
    var that = this;
    var destHeight = 0;
    var animWidth = 180;
    var toBold = new Array(); // bold ids - current and parents

    this.menu = new Array();
    this.items = new Array();
    this.linkid = 0;

    function populateMenu(theMenu, linkid) {
        var html = "<ul>";
        if (that.items[linkid]) {
            var children = that.items[linkid].children;
            if (children.length == 0) {
                linkid = that.items[linkid]._parent;
                var children = that.items[linkid].children;
            }
            for(i in children) {
                var item = that.items[children[i]];
                html += '<li class="sectionmenu_position">'
                    + '<a id="ajaxmenu_link_'+ item._link +'" '
                    + 'href="'+item.url+'">'
                    + item.title
                    + '</a>'
                    + ((item.children.length == 0) ? "" : "&nbsp;&raquo;")
                    + '</li>';
            }
            html += "</ul>";

            // assign all in one go
            theMenu.html(html);

            // but attach events...
            theMenu.find('li a').click(levelDown);
            // and bolden current items
            theMenu.find(toBold.join(',')).css('font-weight', 'bold');

            that.linkid = linkid;
            return true;
        }
        else {
            return false;
        };
    }

    function populateAndAnimate(div, id, left) {
        if (populateMenu(div, id)) {
            destHeight = div.height()+11; // arrow height
            showArrow(); // will know what to do.
            var destLeft;
            var otherDiv;
            if (left) {
                destLeft = '-='+animWidth; // move both divs 180px to left
                otherDiv = '#nextLevel';
            }
            else {
                destLeft = '+='+animWidth; // both divs 180px right
                otherDiv = '#prevLevel';
            }
            theMenu.find(otherDiv + ',#currentLevel').animate({'left': destLeft});
            theMenu.animate({'height': div.height()}, function() {
                                theMenu.find('#currentLevel').remove();
                                div.attr('id', 'currentLevel');
                                div.css('position', 'absolute');
                            });
        };
    }

    function levelDown(ev) {
        var id = parseInt(/\d+/.exec($(ev.target).attr("id"))[0]);

        if (that.items[id].children && that.items[id].children.length > 0) {
            theMenu.append('<div id="nextLevel" />');
            var div = theMenu.find('#nextLevel');
            var cur = theMenu.find('#currentLevel');
            populateAndAnimate(div, id, true);
            return false; // do not navigate
        };
        // else - let it click
    }

    function levelUp(ev) {
        theMenu.append('<div id="prevLevel" />');
        var div = theMenu.find('#prevLevel');
        ev.target.blur();
        populateAndAnimate(div, that.items[that.linkid]._parent, false);

        return false; // do not navigate
    }

    function hideArrow() {
        that.upLink.stop().animate({'opacity': 0, 'height' : (jQuery.browser.msie && jQuery.browser.version < 7) ? destHeight-3 : '100%'});
    }
    function showArrow() {
        if (!isTopLevel()) {
            that.upLink.stop().animate({'opacity': arrowOpacity, 'height' : ((jQuery.browser.msie && jQuery.browser.version < 7) ? destHeight-3 : '100%')});
        } else {
            hideArrow();
        }
    }
    function isTopLevel() {
        return (that.items[that.linkid]._parent == that.rootItem._parent);
    }

    function setupUpLink() {
        that.upLink = theMenu.parent().find('#levelUpLink');
        destHeight = theMenu.find('#currentLevel').height()+11;
        that.upLink.css({'height': destHeight});
        if (!isTopLevel()) {
            that.upLink.css('opacity', arrowOpacity).delay(2000).animate({'opacity': 0});
        } else {
            that.upLink.css('opacity', 0);
        }

        theMenu.hover(function () {
                          arrowOpacity = 0.15;
                          showArrow();
                      }, hideArrow);
        that.upLink.hover(function() {
                              arrowOpacity = 0.3;
                              showArrow();
                          }, hideArrow);
    }

    // init
    function onMenuDownloaded(json) {
        for (i in json) {
            that.items[json[i]._link] = json[i];
            that.items[json[i]._link].children = new Array();
        }

        for (i in json) {
            if (that.items[json[i]._parent] == undefined) {
                // missing menu root ...
                that.rootItem = {
                    _link: json[i]._parent,
                    _parent: 0,
                    children: [],
                    title: "Sklep",
                    url: "/"
                };
                that.items[json[i]._parent] = that.rootItem;
                // we can be outside the shop part now,
                // if so, we'll set the linkid to root
                if (that.items[that.linkid] == undefined) {
                    that.linkid = json[i]._parent;
                };
            }
            that.items[json[i]._parent].children.push(json[i]._link);
        }

        var link = that.linkid;
        do {
            toBold.push('#ajaxmenu_link_'+link);
            link = that.items[link]._parent;
        } while (link != 0);

        theMenu.before('<a href="#" title="Kategoria nadrzędna" id="levelUpLink">&nbsp;</a>');
        theMenu.parent().css({'overflow': 'hidden', 'position': 'relative'}).find('#levelUpLink').click(levelUp);
        theMenu.html('<div id="currentLevel"></div>');
        var div = theMenu.find('#currentLevel');
        populateMenu(div, that.linkid);
        //animWidth = div.outerWidth(true); wanted to be auto, but oh well.
        theMenu.css('height', div.height()+11);
        div.css('position', 'absolute'); // set free
        setupUpLink();
    }

    that.linkid = $('#pagelink').val();
    var data = {
        component: 'cContextMenu',
        method: 'getMenu',
        placement: type
    };
    $.getJSON('/_json/', data, onMenuDownloaded);
}

jQuery(document).ready(function () {
    FancyMenu('#sectionmenu', 'shop');
});
