/**
 *
 * File Name 		: Menu.js handeling menu bar 
 * @author			: Hamidreza Bidgoli <bidgoli.wd@gmail.com>
 * @privicy      	: public class
 *
*/

(function(){
        
        Shadmehr.Menu = {
                Model:{
                        member_menu_items       : [],
                        child_menu_items        : [],
                        navigation_url		    : "",
                        new_page                : false,
                        navigation_item		    : {
                                                                                parent_title : '',
                                                                                parent_link  : '',
                                                                                child_title  : '',
                                                                                child_link   : ''	
                                                                                }
                },
                
                View:{
                        _getMemberMenuBar: function(member_items){
                                $V.showNavigationBar(member_items);
                                
                                var member_items_temp   = [];
                                var manu_container = $get("menu_container");
                                var div_body = $ce("div");
                                var ul = $ce("ul");
                                YAHOO.util.Dom.addClass(div_body, 'bd');
                                YAHOO.util.Dom.addClass(ul, 'first-of-type');
                                
                                for(var i=0; i<member_items.length; i++){
                                        var li = $ce("li");
										li.style.width = "90px";
										
                                        var link_container = $ce("a");
                                        var text_container = $ct(member_items[i].title);
                                        var url = $C._getRealUrl(member_items[i].link);
                                        YAHOO.util.Dom.addClass(li, 'yuimenubaritem');
                                        YAHOO.util.Dom.addClass(li, 'first-of-type');
                                        YAHOO.util.Dom.setStyle(li, 'float', floating);
                                        YAHOO.util.Dom.addClass(link_container, 'yuimenubaritemlabel');
                                        link_container.id = member_items[i].id; 
                                        link_container.href = url;
                                        li.appendChild(link_container);
                                        link_container.appendChild(text_container);
                                        ul.appendChild(li);
                                        $M.child_menu_items.push(member_items[i].subMenu);	
                                }
                                
                                div_body.appendChild(ul);
                                manu_container.appendChild(div_body);				
                                $E._onContentReadyMenu();
                        },
                        
                        /**
                         * showMenuBar public function
                         * @param type intteger, type of menu 
                         * return menu bar 
                         */
                        
                        showMenuBar: function(type){
                                $C._getMemberMenuItems(type);
                        },
                        
                        /**
                         * showNavigationBar public function
                         * @param member_items obj, member and submenu items of menu bar 
                         * return bread crumb  
                         */
                                showNavigationBar: function(member_items){
                                var navigation_bar = $C._getNavigationBar(member_items);
                                var navigation_container = $get('navigation_container');
                                
                                for(var i=0; i<navigation_bar.length; i++){
                                        var div_parent  = $ce('div');
                                        var link_parent = $ce('a');
                                        var title_parent = $ct(navigation_bar[i].parent_title);
                                        YAHOO.util.Dom.addClass(div_parent, 'navigatin_item');
                                        var url = $C._getRealUrl(navigation_bar[i].parent_link);
                                        link_parent.href = url;
                                        div_parent.appendChild(link_parent);
                                        navigation_container.appendChild(div_parent);
                                        if(navigation_bar[i].child_title.length>1){
                                                var div_child = $ce('div');
                                                var link_child = $ce('a');
                                                var title_child = $ct(navigation_bar[i].child_title);
                                                var arrow = $ce('span');
                                                arrow.innerHTML = '&laquo;&nbsp;&nbsp;';
                                                var url = $C._getRealUrl(navigation_bar[i].child_link);
                                                link_child.href = url;
                                                link_child.appendChild(title_child);
                                                div_child.appendChild(link_child);
                                                link_parent.innerHTML = '';
                                                link_parent.appendChild(arrow);
                                                link_parent.appendChild(title_parent);
                                                navigation_container.appendChild(div_child);
                                        }
                                }
                        }
                },
                
                Controller: {
                        _getMemberMenuItems: function(type){
                                $M.member_menu_items = [];
                                var type   = type || 2;
                                var query_string = "?c=ghandler&panel=menu&action=menubar&page=getmenubar&type="+type;
                                var requestPath = Shadmehr.Config.$basepath + query_string; 
                                YAHOO.util.Connect.asyncRequest('Get', requestPath, $C._callbackGetMemberMenuItems);
                                return $M.member_menu_items;
                        },
                        
                        _getChildMenuItems: function(member_items){
                                $M.child_menu_items = [];
                                for(var i=0; i<member_items.length; i++){
                                        var query_string = "?c=ghandler&panel=menu&action=menubar&page=getmenubar&type="+member_items[i].type+"&itemId="+member_items[i].id;
                                        var requestPath = Shadmehr.Config.$basepath + query_string; 
                                        YAHOO.util.Connect.asyncRequest('Get', requestPath, $C._callbackGetChildMenuItems);
                                }
                                return $M.child_menu_items;
                        },
                        
                        _handleSuccess: function(o){
                                var values = YAHOO.lang.JSON.parse(o.responseText);
                                if(values != null){
                                        for(var i=0; i<values.length; i++){
                                                obj = {code 	: values[i].SMU_CODE,	
                                                       id   	: values[i].SMU_ID,
                                                       link 	: values[i].SMU_LINK,   
                                                       seq  	: values[i].SMU_SEQ,
                                                       title	: values[i].SMU_TITLE,
                                                       type 	: values[i].SMU_TYPE, 
                                                       subMenu	: {parent:values[i].SMU_TITLE, parentLink: values[i].SMU_LINK, value:values[i].submenu}
                                                };
                                                $M.member_menu_items.push(obj);
                                        }
                                        $V._getMemberMenuBar($M.member_menu_items);
                                }
                        },
                        
                        _handleFailure: function(o){
                                
                        },
                        
                        _callbackGetMemberMenuItems: {
                                success: function(o){$C._handleSuccess(o)}, 
                            failure: function(o){$C._handleFailure(o)} 
                        },
                        
                        _callbackGetChildMenuItems : {
                                success: function(o){$C._handleSuccess(o)}, 
                            failure: function(o){$C._handleFailure(o)} 
                        },
                        
                        _getSubMenuData : function(){
                                
                                var aSubmenuData = [];
                                for(var i=0; i<$M.child_menu_items.length; i++){
                                        if($M.child_menu_items[i].value != "null"){
                                                var subMenu = YAHOO.lang.JSON.parse($M.child_menu_items[i].value);
                                                var itemData = [];
                                                for(var j=0; j<subMenu.length; j++){
                                                        var url = $C._getRealUrl(subMenu[j].SMU_LINK);
                                                        var itemDataObj = {text : subMenu[j].SMU_TITLE, url: url};
                                                        itemData.push(itemDataObj);
                                                }
                                                var subMenuObj  = {
                                                        id 	    : $M.child_menu_items[i].parent,
                                                        itemdata : itemData				  	
                                                };
                                                aSubmenuData.push(subMenuObj);			 		
                                        }else if($M.child_menu_items[i].value == "null"){
                                                var subMenuObj  = {
                                                                                   id 	    : $M.child_menu_items[i].parent,
                                                                                   itemdata : false				  	
                                                                                         };
                                                aSubmenuData.push(subMenuObj);
                                        }	
                                }
                                
                                return aSubmenuData;
                        },
                        
                        _getNavigationBar: function(member_items){
                                var navigation_items = [];
                                $M.navigation_url = window.location.search.substr( 1, window.location.search.length-1 );
                                for(var i=0; i<member_items.length; i++){
                                        if( $M.navigation_url == member_items[i].link ){
                                                $M.navigation_item.parent_title = member_items[i].title;
                                                $M.navigation_item.parent_link  = member_items[i].link; 
                                                navigation_items.push($M.navigation_item);
                                                return navigation_items;
                                        }else{
                                                var sub_menu = YAHOO.lang.JSON.parse(member_items[i].subMenu.value);
                                                if( sub_menu != null ){
                                                        for(var j=0; j<sub_menu.length; j++){
                                                                if( $M.navigation_url == sub_menu[j].SMU_LINK){
                                                                        $M.navigation_item.parent_title = member_items[i].subMenu.parent;
                                                                        $M.navigation_item.parent_link  = member_items[i].subMenu.parentLink;
                                                                        $M.navigation_item.child_title  = sub_menu[j].SMU_TITLE;
                                                                        $M.navigation_item.child_link   = sub_menu[j].SMU_LINK; 
                                                                        navigation_items.push($M.navigation_item);
                                                                        return navigation_items;
                                                                }
                                                        }
                                                }	
                                        }	
                                }
                                return navigation_items;
                        },
                        
                        _getRealUrl: function(url){
                                $THIS.new_page = false;
                                expression = url.substr(0, 1);
                                switch(expression){
                                        case '#':
                                                url = '#'
                                                break;
                                        case '@':
                                                url = url.substr(1, url.length-1);
                                                break;
                                                
                                        case '~':
                                                url = 'index.php?' + url.substr(1, url.length-1);
                                                $THIS.new_page = true;
                                                break;
                                                        
                                        default:
                                                url = 'index.php?' + url;				
                                }
                                return url;
                        }
                },
                
                Event: {
                        _onContentReadyMenu: function(){
                                YAHOO.util.Event.onContentReady("menu_container", function () {
                                        
                                    var oMenuBar = new YAHOO.widget.MenuBar("menu_container", { 
                                                                                autosubmenudisplay: true, 
                                                                                hidedelay: 750, 
                                                                                lazyload: true });
                                        
                                    var aSubmenuData = $C._getSubMenuData();
                                    var ua = YAHOO.env.ua,
                                     oAnim;  // Animation instance
                    function onSubmenuBeforeShow(p_sType, p_sArgs) {
                           
                             var oBody,
                                oElement,
                                oShadow,
                                oUL;
                                
                            if (this.parent) {
                                oElement = this.element;
                                /*
                                     Get a reference to the Menu's shadow element and 
                                     set its "height" property to "0px" to syncronize 
                                     it with the height of the Menu instance.
                                */
                                oShadow = oElement.lastChild;
                                oShadow.style.height = "0px";
                                /*
                                    Stop the Animation instance if it is currently 
                                    animating a Menu.
                                */ 
                            
                                if (oAnim && oAnim.isAnimated()) {
                                    oAnim.stop();
                                    oAnim = null;
                                }
                                /*
                                    Set the body element's "overflow" property to 
                                    "hidden" to clip the display of its negatively 
                                    positioned <ul> element.
                                */ 
                                
                                oBody = this.body;
                                
                                //  Check if the menu is a submenu of a submenu.
        
                                if (this.parent && 
                                    !(this.parent instanceof YAHOO.widget.MenuBarItem)) {
                            
                                    /*
                                        There is a bug in gecko-based browsers and Opera where 
                                        an element whose "position" property is set to 
                                        "absolute" and "overflow" property is set to 
                                        "hidden" will not render at the correct width when
                                        its offsetParent's "position" property is also 
                                        set to "absolute."  It is possible to work around 
                                        this bug by specifying a value for the width 
                                        property in addition to overflow.
                                    */
                                    
                                    if (ua.gecko || ua.opera) {
                                    
                                        oBody.style.width = oBody.clientWidth + "px";
                                    
                                    }
                        
                                    /*
                                        Set a width on the submenu to prevent its 
                                        width from growing when the animation 
                                        is complete.
                                    */
                                    
                                    if (ua.ie == 7) {
                                        oElement.style.width = oElement.clientWidth + "px";
                                    }
                                }
        
                                oBody.style.overflow = "hidden";
                                /*
                                    Set the <ul> element's "marginTop" property 
                                    to a negative value so that the Menu's height
                                    collapses.
                                */ 
                                oUL = oBody.getElementsByTagName("ul")[0];
                                oUL.style.marginTop = ("-" + oUL.offsetHeight + "px");
                            }
                        }	
                        
                        /*
                    "tween" event handler for the Anim instance, used to 
                    syncronize the size and position of the Menu instance's 
                    shadow and iframe shim (if it exists) with its 
                    changing height.
                        */
        
                        function onTween(p_sType, p_aArgs, p_oShadow) {
                            if (this.cfg.getProperty("iframe")) {
                                this.syncIframe();
                            }

                            if (p_oShadow) {
                                p_oShadow.style.height = this.element.offsetHeight + "px";
                            }
                        }
                        
                        /*
                    "complete" event handler for the Anim instance, used to 
                    remove style properties that were animated so that the 
                    Menu instance can be displayed at its final height.
                        */
        
                        function onAnimationComplete(p_sType, p_aArgs, p_oShadow) {
                            var oBody = this.body,
                                oUL = oBody.getElementsByTagName("ul")[0];
                            if (p_oShadow) {
                                p_oShadow.style.height = this.element.offsetHeight + "px";
                            }
        
                            oUL.style.marginTop = "";
                            oBody.style.overflow = "";
                            
                            //  Check if the menu is a submenu of a submenu.
                            if (this.parent && 
                                !(this.parent instanceof YAHOO.widget.MenuBarItem)) {

                                // Clear widths set by the "beforeshow" event handler
                                if (ua.gecko || ua.opera) {
                                    oBody.style.width = "";
                                }
                                
                                if (ua.ie == 7) {
                                    this.element.style.width = "";
                                }
                            } 
                        }
                        
                        /*
                     "show" event handler for each submenu of the MenuBar 
                     instance - used to kick off the animation of the 
                     <ul> element.
                        */
        
                        function onSubmenuShow(p_sType, p_sArgs) {
                                            
                            var oElement,
                                oShadow,
                                oUL;
                                
                            if (this.parent) {
                                oElement = this.element;
                                oShadow = oElement.lastChild;
                                oUL = this.body.getElementsByTagName("ul")[0];
                                /*
                                     Animate the <ul> element's "marginTop" style 
                                     property to a value of 0.
                                */
                                oAnim = new YAHOO.util.Anim(oUL, 
                                    { marginTop: { to: 0 } },
                                    .5, YAHOO.util.Easing.easeOut);
                                    
                                oAnim.onStart.subscribe(function () {
                                    oShadow.style.height = "100%";
                                });
        
                                oAnim.animate();
        
                                /*
                                    Subscribe to the Anim instance's "tween" event for 
                                    IE to syncronize the size and position of a 
                                    submenu's shadow and iframe shim (if it exists)  
                                    with its changing height.
                                */
            
                                if (YAHOO.env.ua.ie) {
                                    oShadow.style.height = oElement.offsetHeight + "px";
                                    /*
                                        Subscribe to the Anim instance's "tween"
                                        event, passing a reference Menu's shadow 
                                        element and making the scope of the event 
                                        listener the Menu instance.
                                    */
                                    oAnim.onTween.subscribe(onTween, oShadow, this);
                                }

                                /*
                                    Subscribe to the Anim instance's "complete" event,
                                    passing a reference Menu's shadow element and making 
                                    the scope of the event listener the Menu instance.
                                */
                                oAnim.onComplete.subscribe(onAnimationComplete, oShadow, this);
                            }
                        }	
                        
                        /*
                     Subscribe to the "beforerender" event, adding a submenu 
                     to each of the items in the MenuBar instance.
                        */

                        oMenuBar.subscribe("beforeRender", function () {
                            if (this.getRoot() == this) {
                                    for(var i=0; i<aSubmenuData.length; i++){
                                            if(aSubmenuData[i].itemdata){
                                                    this.getItem(i).cfg.setProperty("submenu", aSubmenuData[i]);
                                            }
                                    }
                            }
                        }); 
                        
                        /*
                     Subscribe to the "beforeShow" and "show" events for 
                     each submenu of the MenuBar instance.
                        */
                        oMenuBar.subscribe("beforeShow", onSubmenuBeforeShow);
                        oMenuBar.subscribe("show", onSubmenuShow);

                        /*
                             Call the "render" method with no arguments since the 
                             markup for this MenuBar instance is already exists in 
                             the page.
                        */
                        
                        oMenuBar.render();                                           
                            });
                        }
                }
        };
        var $THIS = Shadmehr.Menu;
        var $M    = $THIS.Model;
        var $V    = $THIS.View;
        var $C    = $THIS.Controller; 
        var $E	  = $THIS.Event;
        
        var handleOnAvailable = function(){
                $V.showMenuBar(2);
        }
        
        YAHOO.util.Event.onAvailable ('menu_container', handleOnAvailable);
})();

