//Constructor
RPCI.flyout = function(props){

    //get params
    for(var i in props){
        if(i != 'colorHandler'){
            this[i] = props[i];
         }else if(gettype(props[i]) == 'function'){
            this[i] = props[i];            
         }
    }
    
    //base must be an element
    props.base = s$(props.base);       
    this.base = props.base || null; 
    
    if( (this.base) && (gettype(this.base) == 'element')){  
        //needs an ID
        if(!this.base.id)return;
        
        //????
        sc.objects.copyProps(props,this);
        
        //set group name        
        this.group = this.base.id + '_flyclass'; 
    
    this.base = s$(this.base);
    
    //roll over color and color
   // this.color = (props.color.trim() != '')?this.getColor(props.color):'#336699';  //Roswell Blue is the default
    
    //refreces
    this.base.flyout = this;
    
    //href refrence
    if(this.base.firstChild.nodeName == 'A')this.link = s$(this.base.firstChild);
    
    //server connection
    this.comm = new ajax;   
    this.comm.fly = this;
    
    //attach class names and events
    this.attachClassNames(this.base); 
    this.attachEvents();
    
    
    
    //flyout collection
    RPCI.flyout.list[this.base.id] = this;  
    
  } 
  
}


//Class Level
RPCI.flyout.list = [];
RPCI.flyout.siteRoot = 'http://www.roswellpark.org';

//Instance Level
RPCI.flyout.prototype = {

    //properties with defaults
    offx : 0, offy : 0, Boffx : 0, Boffy: 0, panel : null, base : {}, group: '',  debug : false, index  : 0,
    rawPanel : null, server: '/Applications/SurebertFlyout/default.asp', async : false, showBridge : false, 
     indicator : '',
       
    //methods    
    attachClassNames : function(item){
    
        //add to base
        this.addGroup(item);             
        
        //add to all base children        
        if(item.hasChildNodes()){
            for(var i in item.childNodes){
                var ele = item.childNodes[i];                               
               if(gettype(ele) == 'element'){
                ele = s$(ele); this.attachClassNames(ele);
               }
            }
        }
    },
    
    addGroup : function(item){
            if(!item.hasClassName(this.group))item.addClassName(this.group);
            if(!item.group)item.group = this.group;
            
    },
        
    attachEvents : function(){
    var t = this;
    
        this.base.event('mouseover', t.Over);        
        this.base.event('mouseover', t.colorHandler);
        this.base.event('mouseout', t.Out);    
        this.base.event('mouseout', t.colorHandler);    
    },   
    
    colorHandler : function(args){        
        //default handler  ...twiddle yer thumbs
    },
    
    getColor : function(sColor){
        sColor = sColor || '#336699';        
         
         //HMTL value      
        if(sb.colors.html[sColor]){
            this.color = sb.colors.html[sColor];
            return;
        }
        
        //RGB Value
        sc.colors
        
        
                
    },
        
    Over : function(e){
     var fly = this.flyout;      
      if(!fly)return;  
      //sc.consol.dump(this.flyout.panel);        
      
      
      if(!fly.panel)fly.makePanel();
      fly.showPanel(); 
      //fly.colorHandler({type : 'mouseover' , flip : 'on'});
    },
    
    Out : function(e){
     var fly = this.flyout; 
     //var targ = s$((e.toElement)?e.toElement:e.relatedTarget); 
     var targ = sb.events.relatedTarget(e);
     var why = new String();
     
        try{
        if(!targ.group){
            fly.hidePanel(); 
            why = "no group";
        }else if(targ.group != fly.group){
            fly.hidePanel(); why = "bad group";
        }
        }catch(e){}
        
        //TO: Dunno why
        //document.title = targ.nodeName + ' ' + targ.id + ' ' + why ;
    },
    
     makePanel : function(){
     
     //gather data from the server
        this.comm.extend({
            handler:this.getData, url:this.server, fly: this, 
            debug:this.debug, data: 'i=' + this.base.id.replace(/\_/, '')
        });   
        this.comm.fetch();  
      
    },
    
    getData : function(data){   
      // sc.consol.dump(this);
       this.fly.rawPanel = eval(data); 
       this.fly.processPanel();
    },
    
    processPanel : function(){
    
        if(!this.rawPanel)return;
        
        var t = this;
        var sGroup = this.group;
        var oPanel = new sb.element({nodeName : 'DIV', id : 'panel_' + this.base.id, group : sGroup, className : 'panel ' + this.panelClass});
        var oHead = new sb.element({ nodeName : 'DIV', className: 'panel_head', id : '', group : sGroup}).appendTo(oPanel);
        var oGutz = new sb.element({ nodeName : 'DIV', className: '', id : 'panel_gutz', group : sGroup}).appendTo(oPanel);
        var oFoot = new sb.element({ nodeName : 'DIV', className: '', id : 'panel_foot', group : sGroup}).appendTo(oPanel);
        var nMax, nCount = new Number();
        
        oHead.css('z-index', 1000);
        oGutz.css('z-index', 1000);
        oFoot.css('z-index', 1000);
        
       
        //determine if this has kids
        if(this.rawPanel[0].e){
			if(!this.base.hasClassName('end'))this.base.addClassName('end'); return;
		}else{
			this.base.addClassName('kids');
			    this.base.innerHTML +=  this.indicator ;
		}
		
        
        
        oPanel.flyout = t; 
        oPanel.getBounds();
        oPanel.css('top', this.base[this.xside] + this.offx ); 
        oPanel.css('left', this.base[this.yside] + this.offy );
        oPanel.css('z-index', 1000);
        oPanel.event('mouseout', this.Out);
        oPanel.event('mouseout', this.colorHandler);
        
        
        oHead.event('mouseout', this.Out);
        oGutz.event('mouseout', this.Out);
        oFoot.event('mouseout', this.Out);
        
        oHead.event('mouseout', this.colorHandler);
        oGutz.event('mouseout', this.colorHandler);
        oFoot.event('mouseout', this.colorHandler);
        
        if(this.showBridge){        
            var oBridge = new sc.element({ nodeName : 'BRIDGE', id : '', group : sGroup}).appendTo($('body'));
            oBridge.getBounds(); oBridge.css('z-index', 999);    
            oBridge.css('height', 20 ); oBridge.css('width', 20 );  
            oBridge.css('left', this.base[this.yside] + this.offy - 20 ); oBridge.css('top', this.base[this.xside] + this.offx);
        }
        
        
        nMax = new Number(this.itemMax);
        nCount = 0;
        this.rawPanel.forEach(function(v,k,a){
          if(nCount++ >= nMax)return;
          //var oClass = (v.c)?'kids':'end';
          var oClass;
          var oA = new sc.element({nodeName: 'A', href : RPCI.flyout.siteRoot + v.h, className: oClass, kids: v.c, id: v.i, innerHTML : v.t, group : sGroup, flyout: t});
              oA.appendTo(oGutz);
                          
        });
        
        //add the more link
        var sItemz = (nCount >= nMax)?'More Items':'More Item';
        if(nCount > nMax){
            var oA = new sc.element({                        
                nodeName: 'A',              
                href : this.base.firstChild.href, //KLUDGEY: What if the first child isn't an anchor?
                id: 'moreitems_' + this.base.id , 
                innerHTML : '(' + (nCount - nMax) + ') ' + sItemz , 
                group : sGroup, 
                flyout: t
            }).appendTo(oGutz);
           
        }
        
        this.panel = oPanel; this.rawPanel = null;
        this.bridge = oBridge;
        oPanel.appendTo($('body'));
        
    },
    
    showPanel  : function(sIndex){     
        
        if(this.panel){
            this.base.getBounds();
            this.panel.css('top', this.base[this.xside] + this.offx ); 
            this.panel.css('left', this.base[this.yside] + this.offy );
            this.panel.css('z-index', 1000);
            this.panel.css('display', 'block');
            if(this.showBridge){
                this.bridge.css('left', this.base[this.yside] + this.offy - 20 );
                this.bridge.css('top', this.base[this.xside] + this.offx);
                this.bridge.css('display', 'block');
              }
          }
    },
    
    hidePanel : function(){
        if(this.panel){
            this.panel.css('display', 'none');
            if(this.showBridge)this.bridge.css('display', 'none');
        }
    }, 
    
    preLoad : function(){
        this.makePanel();
        // this.hidePanel();
    }, 
    
    subOver : function(){
       if(!this.flyout.panel[this.id])this.flyout.makeSubPanel(this);
    },  
    
    makeSubPanel : function(Item){
        this.comm.extend({
            handler:this.getSubData, url:this.server, fly: Item, 
            debug:this.debug, data: 'i=' + Item.id
        });   
        this.comm.fetch();  
    },
    
    getSubData : function(data){		
        this.fly.rawPanel = eval(data);
		this.fly.processPanel();
    },
    
    SubPanel : function(){
    
         this.event('mouseover', this.flyout.subOver);  
         
         this.event('mouseout', function(){
            var t = this.flyout;
            
         });       
   
    }
    
}


//Flyout: Automatic Initializer
RPCI.flyout.init = function(){
   var sMainNavBin = '#mainnav', sSecNavBin = '#subnavlinks'; aReturn = [];
   var settings = {
    colorHandler : null, showBridge : false, bWidth : 20, bHeight : 20, itemMax : 15, index : 10,
    server: '/Applications/SurebertFlyout/default.asp', color: '#0379C2', panelClass : '',
    offx : (sc.browser.agent == 'ie')?1:0 ,  xside: 'bottom',    
    offy: 0, yside: 'left'};
   var debug = new String();
   
   //Gather LI's
   try{ var aMainNav = $(sMainNavBin, 'LI'); }catch(e){}
   try{ var aSecNav = $(sSecNavBin, 'LI'); }catch(e){}
     
   //Main Navigation
   if(aMainNav){
    aMainNav.forEach(function(v,k,a){ settings.base = v;  aReturn.push(new RPCI.flyout(settings)); });
   } 
    
   
   //Side Navigation
   function sideColor(e){
     var fly = this.flyout; 
     var targ = s$((e.toElement)?e.toElement:e.relatedTarget);    
     var grp = (targ.group)?targ.group:undefined;
    
         //firefox kludge
         //if(fly.base.parentNode == targ)grp = targ.group;
         
         try{
         if(grp && (grp == fly.group)){
            fly.link.css('color', fly.color);
            fly.link.css('border-color', fly.color);
          }else{
            fly.link.css('color', '#FFFFFF');
            fly.link.css('border-color', '#FFFFFF');            
          }
         }catch(e){}
     
     
   }  
     
   if(aSecNav){aSecNav.forEach(function(v,k,a){
	settings.offx = 0; settings.offy = -5; settings.itemMax = 7; settings.panelClass = 'rp_side'; settings.showBridge = false;
	settings.xside = 'top'; settings.yside = 'right'; settings.base = v; settings.colorHandler = sideColor; 
	settings.indicator = '<span class="rp_flymore" title="hover to see sub links" >&nbsp;&raquo;</span>';	
    aReturn.push(new RPCI.flyout(settings));
    });    
   }   
   
   s$('body').css('z-index', 1);
   //Preload the panels
   aReturn.forEach(function(v){ v.preLoad(); });
  
   return aReturn;   
}