
var lastParallel      = null;
var lastMediaParallel = null;
var buttons           = new Array();
var button_div_height = 0;
var submenus          = new Array();
var nav_indicators    = new Array();
var buttons_count     = 0;
var subwebsite        = false;

if(barColors == null) {
  var barColors = new Array('#0183b7', '#48bbda', '#92c3ad', '#1aa152');
}

function showLoader() {
	if($('ajax-loader'))
  	$('ajax-loader').show();
}

function hideLoader() {
	if($('ajax-loader'))	
  	$('ajax-loader').hide();
}

function stopParallelEffects(Paralleleffect) {
  if(Paralleleffect != null) {
    Paralleleffect.effects.each(function(e) {
      e.cancel();
    });
    Paralleleffect.cancel();
  }
}

function getButtonPosition(el) {
  var button_number = 1;      
  var button_found  = false;      
  buttons.each(function(i) {
    if(i != el.down() && !i.hasClassName('over')) {
      if(button_found == false) {
        button_number++;
      }
    } 
    if(i.id == el.down().id) {
      button_found = true;
    }
  });
  return button_number;      
}

function isButtonSelected() {
  val = false;
  buttons.each(function(i) {
    if(i.hasClassName('selected')) {
      val = i;
      throw $break;
    }
  });
  return val;
}

function ajaxUpdate(url) {
 showLoader();
  new Ajax.Request(url, {
    method: 'get', 
    onComplete: function() {
      hideLoader();
    /********** Events for the navigation of the photoalbum **************/
  
    $$('#photoalbumNav div.nav div.link').each(function(el) {
    el.observe('click', function click(event) {
      event.stop();
      if(el.down() && el.down().tagName == 'A') {
        var link = el.down().href;
        link = link.replace("view", "photo");
        ajaxUpdate(link);
      }
    });
  }); 
      
    },
    onSuccess: function(req) {
      var jsonObj;
//      alert("t: "+req);
      try {
        jsonObj = req.responseText.evalJSON();
      } catch(e) {
//       alert(e);
        $('article_content').insert(e);
      }
      
      var art       = jsonObj.article_content;
      var photo     = jsonObj.photo;              
      var js        = jsonObj.js;
      var fc        = jsonObj.floating_content;
      var photo_nav = jsonObj.photo_nav ? jsonObj.photo_nav : null ;
      var effects = new Array();      
    	
      if(!jsonObj.js && !jsonObj.photo) {
        $('media').addClassName('nomedia');
        $('media').setStyle({'background': "white url('http://www.heinenhopman.nl/public/images/site_layout/nomedia_background.jpg') repeat-x scroll top center" });
          stopParallelEffects(lastMediaParallel);      
          if($('photo'))
            $('photo').remove();
          if($('photo_temp'))
            $('photo_temp').remove();          
          if($('flash'))
            $('flash').remove();
          if(art) {          
            $('article_content').replace(art);      
            $('article_content').addClassName('nomedia');
          }
          $('media').stopObserving('mouseOver');
          $('site_band').stopObserving('mouseOver');        
      } else {
        $('media').removeClassName('nomedia');
        $('media').setStyle({'height': '289px', 'background': "white url('http://www.heinenhopman.nl/public/images/site_layout/background_media.jpg') repeat-x scroll bottom center"});

        if(art) {
          $('article_content').replace(art);            
        }                 
        if(js) {
          if(!$('flash_temp'))      
            $('media').insert("<div id='flash_temp'></div>");
          else
            $('flash_temp').setStyle({display: 'none'});
          js.evalScripts();
          effects.push(new Effect.Appear($('flash_temp'), { sync: true}));
          new Effect.Parallel(effects, {
            duration: 0.2, afterFinish: 
              function() { 
                $('flash').remove(); 
                $('flash_temp').id = 'flash'; 
              }
          });
        }

        if(photo) {
          stopParallelEffects(lastMediaParallel);
          
          if(!$('photo_temp')) {
            $('media').insert("<div id='photo_temp' style='display: none;'>"+photo+"</div>");
          } else {
            $('photo_temp').setStyle({display: 'none'});
            $('photo_temp').innerHTML="";
            $('photo_temp').insert(photo);          
          }
            
          effects.push(new Effect.Appear($('photo_temp'), {sync: true, from: 0.0, to: 1.0}));
          if($('photo'))
            effects.push(new Effect.Fade($('photo'), { sync: true, from: 1.0, to: 0.0}));

          lastMediaParallel = new Effect.Parallel(effects, {
            afterSetup: function() {
              if($('flash') && $('flash').getStyle('display') != 'none')
                $('flash').hide();
            },
            duration: 0.8, afterFinish: 
              function() {
                if($('photo'))
                  $('photo').remove();
                if($('photo_temp'))
                    $('photo_temp').id = 'photo';                 
              }
          });
        }
       
        if(photo_nav) {
          $('photoalbumNav').replace(photo_nav);
        }
      }
      
      if(fc) {
        if(!$('floating_content'))
          $('container').insert("<div id='floating_content'></div>");
        $('floating_content').replace(fc);
      } else {
        if($('floating_content'))
          $('floating_content').innerHTML='';
      }
        _gaq.push(['_trackPageview', url]);
    }
  }); 
}

  function clickOnListItem(el) {
        // If called from link in the bar, the menu is not open.
        // Open it and set the button selected
        var test    = el.up().up().up();
        var submenu = test.tagName == 'DIV' && test.hasClassName('submenu') ?
                      test : test.up();
                          
        if(submenu.previous())
          var button_number  = getButtonPosition(submenu.previous().down());
        else
        var button_number = null;
        var effectsInternTree = new Array();         

        if(submenu.getStyle('display') == 'none' || 
                                           submenu.getStyle('opacity') == 0.0) {
          effectsInternTree.push(new Effect.BlindDown(submenu, {sync: true}));

          // Special case: when a button that has no children is selected
          buttons.each(function(but) {
            if(but.hasClassName('selected')) {
              but.removeClassName('selected');
            }
          });
          submenu.previous().down().down().next().addClassName('selected');        
        }

        // Deselect the siblings and eventually 
        // close the open branch of the tree 
        el.up().siblings().each(function(siblingLi) {
          if(siblingLi.hasClassName('selected')) {
            siblingLi.removeClassName('selected');
            
            // Close the tree branch
            var closeEl = siblingLi.down().next();
            if(closeEl && closeEl.tagName == 'UL') {
              effectsInternTree.push(new Effect.BlindUp(closeEl, {sync: true}));
            }
          }
        });

        
        // If he is not selected
        if(!el.up().hasClassName('selected')) {
          // Set it as selected
          el.up().addClassName('selected');
        
          // Retrieve all the lists in the menu
          $$('.submenu ul').each( function(a) {
          
            // Find the root ul (it has no id)
            if(a.id == 'undefined' || a.id == '') {
            
              // Look for every child 
              a.descendants().each( function(listItem) {
                var foundAncestor = false;

                el.up().ancestors().each(function(ancestor) {
                  if(ancestor.hasClassName('selected')) {
                    foundAncestor = true;
                    throw $break;
                  }
                });
              
                if(listItem.hasClassName('selected') && 
                          listItem.id != el.up().id && foundAncestor == false) {
                    listItem.removeClassName('selected');
                }
              });
            }
          });
          if(el.next() ) {
            effectsInternTree.push(new Effect.BlindDown(el.next(), {sync: true}));
            effectsInternTree.push(new Effect.Opacity(el.next(), {sync: true, to: 1.0}));          
          }
        } 
        
        // Select the parent(s)
        el.ancestors().each(function(anEl) {
          if(anEl.id == 'undefined' || anEl.id == '') {
            throw $break;
          } else {
            if(anEl.tagName == 'LI') 
              anEl.addClassName('selected');
          }
        });        
        
    ajaxUpdate(el.href);
    if(button_number != null) {
      // Navigation indicators            
      var j = 0;
      nav_indicators.each(function(i) {
        j++;
        j == button_number ? effectsInternTree.push(new Effect.Opacity(i, 
                                                        {sync:true, to: 1.0})) :
            effectsInternTree.push(new Effect.Opacity(i, {sync:true, to: 0.0}));
      });                
    }
    if(effectsInternTree.length > 0)
      new Effect.Parallel(effectsInternTree, {duration: 0.4});   

    return false; 
  }

function updateBarText(firstLi) {
  var text = "<div id='barText' class='text'><ul>";
  var firstLiSiblings = firstLi.siblings();
  text += "<li><a id='"+firstLi.down().id+"_a' href='"+
    firstLi.down().href+"'>"+firstLi.down().innerHTML.toUpperCase()+"</a></li>";
  firstLiSiblings.each(function(s) {
    text += "<li><a id='"+s.down().id+"_a' href='"+
                s.down().href+"'>"+s.down().innerHTML.toUpperCase()+"</a></li>";
  });
  firstSiblings = null;
  $('barText').replace(text+"</ul></div>");

  /********* Events for the links in the moving bar *********/
  $$('#barText ul li a').each(function(el) {
    el.observe('click', function (event) {
      event.stop();
      var id = el.id.substr(0, el.id.length - 2);
      clickOnListItem($(""+id));
    // menuItemLink_12         function clickOnListItem(el) {
//      return false;      
    });
  });  
}

function restoreSubMenusHeight() {
  submenus.each(function(s) {
    s.setStyle({height: ""});  
  });
}

function hideSubMenusOptions() {
  submenus.each(function(s) {
    var firstLi  = s.down();
    if(firstLi && firstLi.down()) {
      var siblings = firstLi.down().siblings();
      siblings.push(firstLi.down());
      siblings.each(function(sib) {
        if(sib.hasClassName('selected')) {
          sib.removeClassName('selected');
          var nextUl = sib.down().next();
          if(nextUl && nextUl.tagName == 'UL' 
                                      && nextUl.getStyle('display') != 'none') {
            sib.down().descendants().each(function(d) {
              if(d.hasClassName('selected'))
                d.removeClassName('selected');
            });
            nextUl.setStyle({display: 'none'});
          }
        }
      });
    }
  });
}

function buttonOver(el) {
        stopParallelEffects(lastParallel);
        var effects        = new Array();
        var button_off     = el.down();
        var button_over    = button_off.next();
        var button_number  = getButtonPosition(el);
        var buttonSelected = isButtonSelected();
        var hasChildren    = true;
        
        // Determine if a selected button has children or not
        if(buttonSelected != false) {
          var submenu = buttonSelected.up().up().next();
          if(submenu && submenu.hasClassName('submenu')) {
            if(!submenu.down() || !submenu.down().down()) {
              hasChildren = false;
            }
          }
        }        
//        alert(el.id + " "+el.hasClassName("nietmooi"));
        // Show the bar when there is no option selected, or when the option
        // selected has no children, or when 'het is mooi'
        if(!el.hasClassName("nietmooi") && (buttonSelected == false || hasChildren == false)) {
          var submenu = el.up().next();
          if(submenu && submenu.hasClassName('submenu')) {
            var firstLi = null;
            if(submenu.down() && submenu.down().down())
              firstLi = submenu.down().down();          
            if(firstLi && subwebsite) {
              updateBarText(firstLi);
              effects.push(new Effect.Appear($('bar'), { sync: true, to: 1.0}));
              effects.push(new Effect.Move($('bar'), 
                                       { y: button_div_height*(button_number-1), 
                                                     x: 0, mode: 'absolute' }));        
              effects.push(new Effect.Morph($('bar').down(), 
                          {style: 'background: '+barColors[button_number-1]+';', 
                                                                   sync: true}));
            } else if(subwebsite) {
              effects.push(new Effect.Fade($('bar'), { sync: true, to: 0.0}));                
            }
          } 
        }

        effects.push(new Effect.Opacity(button_off, { sync: true, to: 0.0}));
        effects.push(new Effect.Opacity(button_over, { sync: true, to: 1.0}));

        buttons.each(function(i) {
          if(i != button_off) {
            if(i.hasClassName('off') && !i.next().hasClassName('selected')) {
              effects.push(new Effect.Opacity(i, { sync: true, to: 1.0}));
              effects.push(new Effect.Opacity(i.next(), { sync: true, to: 0.0}));                        
            } 
          }
        });
        lastParallel = new Effect.Parallel(effects, {duration: 0.2});
}

function buttonClick(el) {
      var effects        = new Array();
      var button_off     = el.down();
      var button_over    = button_off.next();
      var button_number  = getButtonPosition(el);  
      var same_button    = false;    
      var button_visited = 0;      
      var submenu        = el.up().next();
      
      buttons.each(function(i) {
        button_visited++;

        if(i.hasClassName('selected')) {
          // If is the same button and has no children, no action must be taken
          if(submenu && submenu.hasClassName('submenu')) {
            if(i == button_over && submenu.down() && !submenu.down().down()) {
              same_button = true;
              throw $break;
            }
          }

          if(i != button_over) {
            i.removeClassName('selected');
            effects.push(new Effect.Opacity(i, { sync: true, to: 0.0}));
            effects.push(new Effect.Opacity(i.previous(), { sync: true, to: 1.0}));            
            submenu = i.up().up().next();
                      
            if(submenu.hasClassName('submenu')) {
              effects.push(new Effect.BlindUp(submenu, {sync: true}));

              // Add shadow to the next button 
              var nextToSubmenu = submenu.next();
              if(nextToSubmenu && nextToSubmenu.hasClassName('button_background')) {
                var offset = parseInt((-button_div_height * button_visited/2));
                var s      = "url(http://www.heinenhopman.nl/public/images/site_layout/subsite_options/"+
                              buttons_count+"options-background.jpg) repeat-x scroll 0px "+ 
                              offset+"px;";            
                nextToSubmenu.setStyle("background: "+s);
              }
            }
                hideSubMenusOptions();  
          }
          
          // The trigger is the button self
          if(i == button_over) {
            same_button = true;
            // Show Bar if the option has children, move it and show it
            var firstLi = null;
            if(submenu.down() && submenu.down().down())
              firstLi = submenu.down().down();
            restoreSubMenusHeight();
            hideSubMenusOptions();
            throw $break;
          }
        }
      });
      
      // We should only return if the button is the same, but there is
      // one child selected.
      if(same_button == true) {
        var padLinks = $('ancestorsNav').childElements();
        var l = padLinks.length;
        var e = padLinks[l-1];
        if( !e.innerHTML.indexOf(el.down().alt) >= 0 ) {
          ajaxUpdate(el.href)
          return false;        
        }
      }
      
      // It is not a button that was already open, but other one
      button_over.addClassName('selected');
      effects.push(new Effect.Opacity(button_off, {sync: true, to: 0.0}));
      effects.push(new Effect.Opacity(button_over, {sync: true, to: 1.0}));
      if(subwebsite)
        effects.push(new Effect.Fade($('bar'), {sync: true, to: 0.0}));              

      // Has children?
      submenu = el.up().next();
      if(submenu && submenu.hasClassName('submenu')) {
        if(submenu.down() && submenu.down().down())
          effects.push(new Effect.BlindDown(submenu, {sync: true}));   
          
        // Navigation indicators            
        var j = 0;
        nav_indicators.each(function(i) {
          j++;
          j == button_number ? effects.push(new Effect.Opacity(i, {sync:true, to: 1.0})) :
                      effects.push(new Effect.Opacity(i, {sync:true, to: 0.0}));
        });            
            
        // Eliminate shadow of the next button
        nextsubmenu = el.up().next();
        if(nextsubmenu && nextsubmenu.next() && 
                         nextsubmenu.next().hasClassName('button_background')) {
          nextButtonContainer = nextsubmenu.next();
          var offset = parseInt((-button_div_height * button_number) - (button_div_height*buttons_count));
          var s      = "url(http://www.heinenhopman.nl/public/images/site_layout/subsite_options/"+
                        buttons_count+"options-background.jpg) repeat-x scroll 0px "+ 
                        offset+"px;";
          nextButtonContainer.setStyle("background: "+s);        
        }
      }
      new Effect.Parallel(effects, {duration: 0.3, 
                                               beforeStart: function() {
                                                ajaxUpdate(el.href);
                                                if($('secMenu')) {
                                                  $('secMenu').childElements().each(function(link) {
                                                    if(link.hasClassName('selected')) {
                                                      link.removeClassName('selected');
                                                      throw $break;                                                    
                                                    }
                                                  });
                                                }
                                                },
                                           afterFinish: restoreSubMenusHeight});
      return false;
}

function newsNav(event, move) {
  var list  = event.target.up().next().next();
  var items = list.childElements();
  var counter = 0;
  
  // find news that is showing, hide it and show the next or prev one
  // only when there is another news to show after or before 
  items.each(function(item) {
    counter++;
    if(!item.hasClassName('hidden')) {
      if(move == 'next') {
        // Check there are more news
        if(item.next() && item.next().hasClassName('newsItem')) {
          item.hide();
          item.addClassName('hidden');
          item.next().appear({duration: 0.4});
          item.next().removeClassName('hidden');
          $('newsCounter').innerHTML = (counter+1)+" ";
          event.target.up().down().removeClassName('disabled');          
          if(counter + 1 == items.size())
            event.target.addClassName('disabled');            
        } 
        throw $break;
      } else if(move == 'prev') {
        // Check there are news before
        if(item.previous() && item.previous().hasClassName('newsItem')) {
          item.hide();
          item.addClassName('hidden');          
          item.previous().appear({duration: 0.4});
          item.previous().removeClassName('hidden');          
          $('newsCounter').innerHTML = (counter-1) + " ";
          event.target.next().next().next().next().removeClassName('disabled');          
          if($('newsCounter').innerHTML == 1) {
            event.target.addClassName('disabled');
          }                  
        } 

      } else {
        return;
      }
    }
  });
}

function articlesNav(event, move) {
  var items  = event.target.up().up().siblings();
  var selectedItemFound = false;

  items.each(function(item) {
    if(item.hasClassName('selected')) {
    selectedItemFound = true;
      if(move == 'next') {
        var nextItem = item.next();
        if(nextItem && nextItem.tagName == "LI" && 
                                           !nextItem.hasClassName('nextPrev')) {
          ajaxUpdate(nextItem.down().href);
          item.removeClassName('selected');
          nextItem.addClassName('selected');
          event.target.up().previous().down().removeClassName('disabled');
          event.target.up().previous().down().addClassName('enabled');                                        
          nextItem = nextItem.next();   
          
          if(!(nextItem && nextItem.tagName == "LI" && 
                                           !nextItem.hasClassName('nextPrev'))) {
            event.target.addClassName('disabled');
            event.target.removeClassName('enabled');
          }
          throw $break;
        } 
      } else if(move == 'prev') {
        var prevItem = item.previous();
        if(prevItem && prevItem.tagName == "LI") {
          ajaxUpdate(prevItem.down().href);
          item.removeClassName('selected');
          prevItem.addClassName('selected');
          event.target.up().next().down().removeClassName('disabled');
          event.target.up().next().down().addClassName('enabled');                              
          prevItem = prevItem.previous();
          if(!(prevItem && prevItem.tagName == "LI")) {
            event.target.addClassName('disabled');
            event.target.removeClassName('enabled');
          }          
          
          throw $break;
        } 
      } else {
        return;
      }
    }
  });
  if(!selectedItemFound) {
    items[0].addClassName('selected');
    ajaxUpdate(items[0].down().href);    
  }
}

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

  // Populate buttons and submenus arrays    
  $$('#navigation div.button_background a.link_subsite img.button_image').each(
  function(img) {
    if(img.hasClassName('over'))
      img.setOpacity(0.0);
    
      buttons.push(img);
  });
  $$('#navigation div.submenu').each(function(div) {
      submenus.push(div);
  });
  $$('#navigation_indicators div').each(function(div) {
    nav_indicators.push(div);
  });
  
  // Initialize global values
  buttons_count     = (buttons.size())/2;
  if($('navigation') && $('navigation').down())
    button_div_height = $('navigation').down().getHeight();
  
  /******** Navigatie bovenop *********/
  $$('.subsiteNavSelect').each(function(e) {
    e.observe('change', function changed(event) {
//      var next = e.next();
//      if(next && next.tagName == 'A') {
//        next.href = event.target.value;
        window.location = event.target.value;
//      }
    });
  });

  /******** Events in the body, when the mouse is outside the menu ********/
	if($('bar')) {
 	 $$('body')[0].observe('mouseover', function obsMouseOver(event) {
	    event.stop();
	    var barDescendants = $('bar').descendants();
	    barDescendants.push($('media'));
	    barDescendants.push($('flash'));
	    barDescendants.push($('photo'));
	    barDescendants.push($('site_band'));
	    $$('.button_background').each(function(el) {
	      barDescendants.push(el);
	    });
	    var isBarEvent = false;
	    barDescendants.each(function(b){
	      if(event.element() == b) {
	        isBarEvent = true;
	        throw $break;
	      }
	    });
    
	    if(!isBarEvent) {
	      stopParallelEffects(lastParallel);
	      var effects = new Array();
	      buttons.each(function(i) {
	      if(i.hasClassName('over') && !i.hasClassName('selected')) {
	          effects.push(new Effect.Opacity(i, { sync: true, to: 0.0}));
	          effects.push(new Effect.Opacity(i.previous(), { sync: true, to: 1.0}));                  
	        } 
	      });

	      if(subwebsite && $('bar').getStyle('display') != 'none')
	        effects.push(new Effect.Fade($('bar'), {sync: true, to: 0.0}));              
	      // Hide the options bar also
	      if(effects.length > 0)
	        lastParallel = new Effect.Parallel(effects, { duration: 0.8 } );
	    }
    
	  });
	}

  /********* Events for the options buttons *********/
  $$('#navigation div a.link_subsite').each(function(el) {
    el.observe('mouseover', function obsMouseOver(event) {
      event.stop();
        buttonOver(el);
    });

    el.observe('click', function obsMouseClick(event) {
      event.stop();
      buttonClick(el);
    });
  });
  
  /********** Events for the news navigation links (divs) **************/
  
  if($('nextNews') && $('prevNews')) {
    $('nextNews').observe('click', 
      function obsMouseClick(event) {
        event.stop();
        newsNav(event, 'next');
      });
      
    $('prevNews').observe('click', 
      function obsMouseClick(event) {
        event.stop();
        newsNav(event, 'prev');
      });
  }
  
      /********** Events for the navigation of the photoalbum **************/  
    $$('#photoalbumNav div.nav div.link a').each(function(el) {
    el.observe('click', function click(event) {
      event.stop();
        var link = el.href;
        link = link.replace("view", "photo");
        ajaxUpdate(link);
    });
  });
  

  /********* Events for the links under the buttons, in the div ul li *********/
  $$('#navigation div.submenu ul li a').each(function(el) {
    el.observe('click', function() {clickOnListItem(el)} );  
  });  
  
  /*** Events for the next and prev links (divs) in the navigation menu********/
  
  var nextPrevLinks = $$('div.linkNextPrev');
  
  if(nextPrevLinks.length > 1) {
    nextPrevLinks.each(function(i) {
      i.observe('click', 
      function obsMouseClick(event) {
        event.stop();
        if(i.hasClassName('next'))
          articlesNav(event, 'next');
        else if(i.hasClassName('prev'))
          articlesNav(event, 'prev');
      });
    });
  }
});

