/**
 *  jQuery Rotator Plugin
 *  @requires jQuery v1.2.6 or greater
 *  http://hernan.amiune.com/labs
 *
 *  Copyright (c)  Hernan Amiune (hernan.amiune.com)
 *  Licensed under MIT license:
 *  http://www.opensource.org/licenses/mit-license.php
 * 
 *  Version: 1.0
 */
 
(function ($) {
    $.fn.topmenu = function (options) {

        var defaults = {
            isLeft: false,
            isRight: false
        };

        var options = $.extend(defaults, options);

        return this.each(function (index) {

            var $this = $(this);

            var anc = $this.children("a");
            var liHeight = $this.height();
            var ancHeight = anc.height();
            if ((liHeight - ancHeight) > 0)
                anc.css("padding-top", ((liHeight - ancHeight) / 2) - 5 + "px");


            if (options.isLeft) {
                if ($this.hasClass("selected")) {
                    $(".first-child").toggleClass("first-child-selected");
                }
            }

            if (options.isRight) {
                if ($this.hasClass("selected")) {
                    $(".last-child").toggleClass("last-child-selected");
                }
            }
            var subnav = $this.children(".subnav-hover-wrapper");
            if ((($this.position().left + subnav.width())-120) > $this.parent().width()) {
                var newpos = $this.parent().width() - (subnav.width());
                newpos -= $this.position().left;
                subnav.css("margin-left", (newpos - 20) + "px");
            } else {
                subnav.css("margin-left", "-120px");
            }

            $this.mouseover(function () {
                var subnav = $this.children(".subnav-hover-wrapper");
                if (!$this.hasClass("selected")) {
                    subnav.show();
                }


                if (($this.position().left + subnav.width()) > $this.parent().width()) {
                    var newpos = $this.parent().width() - (subnav.width());
                    newpos -= subnav.position().left;
                    //subnav.css("margin-left", (newpos - 5) + "px");
                }

                if (options.isLeft) {
                    $(".first-child").toggleClass("first-child-hover");
                }
                if (options.isRight) {
                    $(".last-child").toggleClass("last-child-hover");
                }
            });

            $this.mouseout(function () {
                $this.children(".subnav-hover-wrapper").hide();
                if (options.isLeft) {
                    $(".first-child").toggleClass("first-child-hover");
                }
                if (options.isRight) {
                    $(".last-child").toggleClass("last-child-hover");
                }
            });

        });

        adjustHeight();
    }
})(jQuery);
