// webon_ui.js
//
// JavaScript objects for webon user interface elements
//
// Author: Knut Brobakken
//
// Copyright WebOn 2008
//

// ****************** wo_overlay ********************************************

   wo_overlay = {};
   
   document.observe('dom:loaded',function(){
   
     // Make sure overlay is in place
      
      var aOver = $$('.wo_overlay');
                
      if (aOver.length < 1) {
       wo_overlay = $(document.createElement('div'));
       wo_overlay.addClassName('wo_overlay');
       document.body.appendChild(wo_overlay);
      }
      
      else {
       wo_overlay = aOver[0];
      }
      
     // Make sure overlay is correctly resized and displayed on window resize
     
     	 Event.observe(window, 'resize', wo_overlay_setsize);			
 

    });
    
    function wo_overlay_setsize(e) {
     
        var oDim = document.viewport.getDimensions();
        var oScroll = document.viewport.getScrollOffsets();
        
        wo_overlay.setStyle({'height':oDim.height,'width':oDim.width,'top':oScroll.top,'left':oScroll.left});        
        
    }
    
    function wo_overlay_show(e) {

        wo_overlay_setsize();     
        wo_overlay.setStyle({'visibility':'visible'});        
     
    } 
    
    function wo_overlay_hide(e) {
     
     wo_overlay.setStyle({'visibility':'hidden'});
     
    } 
         
// ****************** wo_treemenu **********************************************************************

    document.observe('dom:loaded',function(){
        
      var treemenu = $$('.wo_treemenu')[0];
      
      if (! treemenu) {
       return true;
      }
      
      // Get and fix parameters
      
          var sRel = treemenu.readAttribute('rel');
       
          if (! sRel) { 
            oParams = {};
          }
          else {
          
            if (sRel.indexOf('{') == -1) {
             sRel = '{' + sRel;
            }
          
            if (sRel.indexOf('}') == -1) {
             sRel = sRel + '}';
            }

            oParams = sRel.evalJSON();
          }
                              
      // Fix images for last-children  (breaks IE7 LI behaviour, so disabled for the moment)
        
        /*treemenu.select('ul li:last-child').each(
        
         function(oLI) {
  
           var sClass = 'lastchild';       
  
           if (oLI.hasClassName('topen')) { sIMG = 'lastchild_open'; }
           if (oLI.hasClassName('tclosed')) { sIMG = 'lastchild_closed';}
                      
           oLI.addClassName(sClass);
                               
         }
        );*/

      // Set up observer for handling of expand/collapse nodes and navigation 
    
        var func_click = 'treemenu_click';
    
        if (oParams.func_click) {
         func_click = oParams.func_click;
        }
    
        if (func_click.length) {
         treemenu.observe('click',eval(func_click).bindAsEventListener(treemenu,oParams));
        } 
        
      // Set up observer for handling of rightclick  
      
        if (oParams.func_rightclick) {
         treemenu.observe('contextmenu',eval(oParams.func_rightclick).bindAsEventListener(treemenu,oParams));
        }       

      // Expand nodes if expanded parameter is given
      
        if (oParams.expanded) {
        
          $A(oParams.expanded.split(',')).each(
           function(sID) {
            var oLI = $(sID);
            if (oLI) {
             oLI.removeClassName('tclosed');
             oLI.addClassName('topen');
            }
           }
          );
        
        }        

            
    }); // End of dom:loaded
      
             
  function treemenu_click(e) {
    
    var treemenu = $(this);
    var oParams = arguments[1];
          
    // Find clicked element and corresponding LI

      var oElem = $(Event.element(e));
         
      var strNN = oElem.nodeName.toLowerCase(); 
    
      var oLI = $(oElem);
      
      if (strNN != 'li') { 
       oLI = oElem.up('li');
      }
      
      if (! oLI) { return true; }
      
      // If node is open and collapse is clicked, close the node
                        
        if (oLI.hasClassName('topen') && strNN=='li') {

          oLI.removeClassName('topen');
          oLI.addClassName('tclosed');
      
          if (oParams.func_close) {
           eval(oParams.func_close + '(treemenu,oParams,oLI)');
          }
          
         // If url for storing expanded elements is present, use it to store expanded nodes 
          
           if (oParams.func_exp) {
             eval(oParams.func_exp + '(treemenu)');         
           }
                              
          return true;
        }
      
      // If node is closed, open it 
      
        if (oLI.hasClassName('tclosed')) {
        
           // Check if we must fetch childnode info
        
           var aChildren = oLI.select('ul');
        
           if (aChildren.length < 1) { 
             if (oParams.func_getchildren) {
                eval(oParams.func_getchildren + '(treemenu,oParams,oLI)');
             } 
           }
           
          oLI.removeClassName('tclosed');
          oLI.addClassName('topen');

          if (oParams.func_open) {
           eval(oParams.func_open + '(treemenu,oParams,oLI)');
          } 
           
        } 
        
       // If url for storing expanded elements is present, use it to store expanded nodes 
        
         if (oParams.func_exp) {
           eval(oParams.func_exp + '(treemenu)');         
         }
        

       // If clicked element is anchor, call func_navigate

        if (strNN !='li' && oParams.func_navigate) {
                  
          eval(oParams.func_navigate + '(oLI,oElem);');
                
        }     
                   

   }


// ****************** wo_dialog ********************************************

   wo_dialog_active = {};
  
   document.observe('dom:loaded',function(){
   
     // Initialize message boxes
            
     $$('.wo_dialog').each(
     
      function(oDialog) {
        wo_dialog_init(oDialog);
      }
     );   

     $$('.wo_dialog_parent_close').each(
     
      function(oButton) {
       oButton.observe('click',wo_dialog_parent_close.bindAsEventListener(oButton,'cancel'));
      }
     );   

     // Make sure dialog box is repositioned/resized on window resize
     
     	 Event.observe(window, 'resize', function(e) {
     	 
     	   if (wo_dialog_active.params) {
     	     wo_dialog_setsize(wo_dialog_active);
     	     wo_dialog_setpos(wo_dialog_active);
     	   }
     	 
       });			
     
   
   });
   
   function wo_dialog_init(oDialog) {
                        
        // Get params
          var sRel = oDialog.readAttribute('rel');
       
          if (! sRel) { 
            oParams = {};
          }
          else {
          
            if (sRel.indexOf('{') == -1) {
             sRel = '{' + sRel;
            }
          
            if (sRel.indexOf('}') == -1) {
             sRel = sRel + '}';
            }

            oParams = sRel.evalJSON();
          }
          
         // Set modal/non-modal
         
          if (oParams.modal != 0) {
           oParams.modal = 1;
          } 
          
         // Get dialog box elements 

            var oMenu = oDialog.select('div')[0];
            var oTitle = oMenu.select('div')[0];
            var oClose = oMenu.select('span')[0];
            var oBody = oDialog.select('.wo_dialog_body')[0];
            
         // Make frame borderless if we use iframe as body   
                                                              
            if (oParams.iframe) {
     
              var oFrame = $(oParams.iframe);
              if (oFrame) {
               oFrame.writeAttribute('frameborder','0');
               oFrame.writeAttribute('border','0');
              }
              
            }  

        // Prepare triggers and funcs

          if (! oParams.funcs) {
           if (oParams.func) {
            oParams.funcs = oParams.func;
           }
          }
       
          if (! oParams.funcs) { 
            oParams.funcs="wo_dialog_show" 
          }
          
          else {
            oParams.funcs = oParams.funcs + ',wo_dialog_show';
          }
                                                        
          var aFuncs = $A(oParams.funcs.split(','));
        
          if (! oParams.triggers) {
           if (oParams.trigger) {
            oParams.triggers = oParams.trigger;
           }
          }
        
          oParams.triggers = oParams.triggers +'';
          
          aTriggers = $A(oParams.triggers.split(','));   
                    
          aTriggers.each(
           function(sID) {
             if ($(sID)) {
              aFuncs.each(
               function(sFunc) {
                  $(sID).observe('click',(eval(sFunc)).bindAsEventListener($(sID),oDialog,oParams));
               }
              );
             }
           }
          );
         
          if (oParams.trigger_class) {
          
            aClasses = $A(oParams.trigger_class.split(','));   
            
            aClasses.each(
            
              function(sClass) {
              
                aTriggers = $$('.'+sClass);
                                   
                aTriggers.each(
                 function(oBtn) {
                    aFuncs.each(
                     function(sFunc) {
                        $(oBtn).observe('click',(eval(sFunc)).bindAsEventListener($(oBtn),oDialog,oParams));
                     }
                    );
                 }
                );
                
             }   
           )     
          
          }
                    
       // Prepare close/cancel
    
          oDialog.select('.wo_dialog_close').each(
           function(oClose) {
             oClose.observe('click',wo_dialog_close.bindAsEventListener(oDialog,oParams,'close'));
           }
          );
          
          oDialog.select('.wo_dialog_cancel').each(
           function(oClose) {
             oClose.observe('click',wo_dialog_close.bindAsEventListener(oDialog,oParams,'cancel'));
           }
          );
          
       //Determine dragging

          if (oParams.draggable !=0) {
            new Draggable(oDialog,{handle:oTitle});
          }   
   
   }
   
   function wo_dialog_show(e) {
   
     var oButton = $(this);
     var oDialog = arguments[1];
     var oParams = arguments[2];

     if (! oParams) {
 
        // Get params from rel attribute of dialog
          var sRel = oDialog.readAttribute('rel');
       
          if (! sRel) { 
            oParams = {};
          }
          else {
          
            if (sRel.indexOf('{') == -1) {
             sRel = '{' + sRel;
            }
          
            if (sRel.indexOf('}') == -1) {
             sRel = sRel + '}';
            }
  
            oParams = sRel.evalJSON();
          }
           
     }      
     
     // Determine size
     
       wo_dialog_setsize(oDialog,oParams)
     
     // Determine position
     
       wo_dialog_setpos(oDialog,Event.pointerX(e)-20,Event.pointerY(e)-20,oParams);
     
     // If we have an active dialog, hide this
     
      if (wo_dialog_active.params) {
       wo_dialog_active.setStyle({'display':'none'});
      }
      
      // If we use iframe as body, set src

        if (oParams.iframe) {
         
          var oFrame = $(oParams.iframe);
          if (oFrame) {
                    
           if (oParams.iframe_src) {
            oFrame.writeAttribute('src',oParams.iframe_src);
           }
          }
         
         }  
     
     // Show dialog (with overlay, if modal)

        if (oParams.modal ==1) {
         wo_overlay_show();
        }
        else {
         wo_overlay_hide();
        }
     
        oDialog.setStyle({'display':'block'});

     // Set current dialog to active
     
       wo_dialog_active = oDialog;
       wo_dialog_active.params = oParams;
   
   
   }
  
   function wo_dialog_setsize(oDialog,oParams) {
 
       if (! oParams) {
   
          // Get params
            var sRel = oDialog.readAttribute('rel');
         
            if (! sRel) { 
              oParams = {};
            }
            else {
            
              if (sRel.indexOf('{') == -1) {
               sRel = '{' + sRel;
              }
            
              if (sRel.indexOf('}') == -1) {
               sRel = sRel + '}';
              }
    
              oParams = sRel.evalJSON();
            }
             
       }      
       
        var oDim = document.viewport.getDimensions(); 
            
        var vWidth = oParams.width + '';
        var vHeight = oParams.height + '';
        
        if (! vWidth.length) { vWidth = oDialog.getStyle('width') }
        if (! vHeight.length) { vHeight = oDialog.getStyle('height') }          
        
        if (vWidth.indexOf('%') != -1) {
          iPercent = parseInt(vWidth);
          vWidth = parseInt((oDim.width * iPercent) / 100);
        }
            
        else {
          vWidth = parseInt(vWidth);
          if (isNaN(vWidth)) { vWidth = 200; }
        }
        
                            
        if (vHeight.indexOf('%') != -1) {
          iPercent = parseInt(vHeight);
          vHeight = parseInt((oDim.height * iPercent) / 100);
        }
        
        else {
          vHeight = parseInt(vHeight);
          if (isNaN(vHeight)) { vHeight = 175; }
        }
                  
        if (oParams.fullscreen==1) {
                    
          if (vWidth < 1) {
            vWidth = oDim.width + (vWidth /2);
          }
          
          else {
            vWidth = oDim.width;
          }
        
          if (vHeight < 1) {            
            vHeight = oDim.height + (vHeight / 2);
          }  
          else {
            vHeight = oDim.height;
          }
        }          
        
       // Make sure dialog is within viewport
       
        if (vWidth > oDim.width) { vWidth = oDim.width -15 } 
        if (vHeight > oDim.height) { vHeight = oDim.height -20 } 
              
       var oStyle = {'width':vWidth+'px','height':vHeight+'px'};
       
       oDialog.setStyle(oStyle);

      // If we use iframe as body, set size for this as well
      
         if (oParams.iframe) {
                  
           var oFrame = $(oParams.iframe);
           
           if (oFrame) {
                      
            if (navigator.userAgent.toLowerCase().indexOf('firefox') != -1) {
              vHeight = vHeight-24;
            }

            oFrame.setStyle({'width':vWidth+'px','height':vHeight+'px'});
           }
         
         } 

                    
   }
   
   function wo_dialog_setpos(oDialog,currentX,currentY,oParams) {
   
        var oDim = document.viewport.getDimensions();
        var oScroll = document.viewport.getScrollOffsets();
                
       if (! currentX) { currentX = oScroll.left;}
       if (! currentY) { currentY = oScroll.top;}
 
       if (! oParams) {
   
          // Get params
            var sRel = oDialog.readAttribute('rel');
         
            if (! sRel) { 
              oParams = {};
            }
            else {
            
              if (sRel.indexOf('{') == -1) {
               sRel = '{' + sRel;
              }
            
              if (sRel.indexOf('}') == -1) {
               sRel = sRel + '}';
              }
    
              oParams = sRel.evalJSON();
            }
             
       } 
       
       // Default: use currentX, currentY
       
        var xPos = currentX;
        var yPos = currentY;
        
        var sHeight = oDialog.getStyle('height');
        var sWidth = oDialog.getStyle('width');

        if (sWidth.indexOf('%') != -1) {
          iPercent = parseInt(sWidth);
          sWidth = parseInt((oDim.width * iPercent) / 100);
        }

        if (sHeight.indexOf('%') != -1) {
          iPercent = parseInt(sHeight);
          sHeight = parseInt((oDim.width * iPercent) / 100);
        }

        var iHeight = parseInt(sHeight);
        var iWidth = parseInt(sWidth);
            
        if (oParams.top) {
         yPos = oParams.top  + oScroll.top;
        }
        
        if (oParams.left) {
         xPos = oParams.left  + oScroll.left;
        }
        
        if (oParams.fullscreen == 1) {
              
          if (! oParams.top) {
            // Center dialog vertically
            yPos = oScroll.top + ((oDim.height - iHeight) / 2);
          }
          
          else {
            yPos = oParams.top;
          }
        
          if (! oParams.left) {
            // Center dialog horizontally
            xPos = oScroll.left + ((oDim.width - iWidth) / 2);
          }
          
          else {
           xPos = oParams.left;
          }
    
        }
        
        if (xPos < 0) { xPos = 0; }
        if (yPos < 0) { yPos = 0; }
        
        var max_y = (oDim.height + oScroll.top) - (iHeight + 30);
        var max_x = (oDim.width + oScroll.left) - (iWidth + 30);
                    
        if (xPos > max_x) { xPos = max_x; }
        if (yPos > max_y) { yPos = max_y; }
        
        var min_y = oScroll.top + 5;
        var min_x = oScroll.left + 5;

        if (xPos < min_x) { xPos = min_x; }
        if (yPos < min_y) { yPos = min_y; }
        
        oDialog.setStyle({'top':yPos,'left':xPos});
       
   }         

  
   function wo_dialog_close(e) {
    
    var oDialog = $(this);
    var oParams  = arguments[1];
    var sCloseType = arguments[2];
                    
    oDialog.setStyle({'display':'none'});
    
    wo_overlay_hide();        
    
    wo_dialog_active = {};
    
    if (sCloseType == 'close') {
    
      if (oParams.func_close) {
       eval(oParams.func_close + '(oDialog,oParams);');
      }
          
    }

    if (sCloseType == 'cancel') {
    
      if (oParams.func_cancel) {
       eval(oParams.func_cancel + '(oDialog,oParams);');
      }
          
    }

                 
   }
   
   function wo_dialog_parent_close(e) {
    
    var oButton = $(this);
    var oDialog = arguments[1];
    var oParams = arguments[2];
    
    if (parent.wo_dialog_active) {
     parent.wo_dialog_active.setStyle({'display':'none'});
    } 
    
    parent.wo_overlay_hide();           
    parent.wo_dialog_active = {};
    
    var sRel = oButton.readAttribute('rel');
    
    var oParams = {};
    
    if (! sRel) { 
      oParams = {};
    }
    else {
    
      if (sRel.indexOf('{') == -1) {
       sRel = '{' + sRel;
      }
    
      if (sRel.indexOf('}') == -1) {
       sRel = sRel + '}';
      }

      oParams = sRel.evalJSON();
    }
    
    if (oParams.func) {
       eval('parent.' + oParams.func + '(oButton.id);');
    }
    
    
   }


// ****************** wo_rcmenu **********************************************************************
        
   document.observe('dom:loaded',function(){

     $$('div.woui_rcmenu ul li').each(
      function(oChoice) {
       alert(oChoice);
       if (! oChoice.hasClassName('woui_rcmenu_hr')) {
        oChoice.observe('mouseover',function(e){ oChoice=$(this);oChoice.addClassName('woui_rcmenu_hover')}.bindAsEventListener(oChoice));
        oChoice.observe('mouseout',function(e){ oChoice=$(this);oChoice.removeClassName('woui_rcmenu_hover')}.bindAsEventListener(oChoice));
       }
      }
     );
     
     $$('.rcmenu_close').each(
      function(oElem) {
       oElem.observe('click',function(e){ var oElem = $(this);var oTitle=oElem.up('div'); var oMenu=oTitle.up('div'); oMenu.hide(); }.bindAsEventListener(oElem));
      }
     );
     
   });  
