/*   *****************************************************
 *
 *   BERTUS.COM
 *   Site of Bertus Distribution
 *
 *   For inquiries or comments, contact
 *   vizi - www.vizi.nl
 *
 *   Behaviour layer: javascript enhancements
 *
 *   This should comply with Dutch web guidelines
 *   See: http://www.webrichtlijnen.nl/
 *   
 *   DEPENDS ON MOOTOOLS LIBRARY v1.11
 *   Uses: core, class, native,
 *   element, window. effects,
 *   remote (XHR, Ajax, assets)
 *
 *   location: /behaviour/bertus.js
 *   version:  1
 *   date:     08/05/2009
 *
 *   *****************************************************
 */


//  BERTUS CONFIG START
//
//  Set options for several texts and properties here
//
var bertusReleasesDelay = 4000;      // Delay between releases (milliseconds).
var bertusReleasesSlideshow;         // Keep track of running slideshow.
var bertusReleasesTotal = 0;         // Keep track of highest index of releases in block (0-2).

var bertusMenuDuration = 300;        // Duration of menu animations (milliseconds).

var bertusGalleryDelay = 4000;       // Delay between slides (milliseconds).
var bertusGalleryImgWidth;           // Width of the gallery images.
var bertusGallerySlideshow = false;  // Keep track of running slideshow.
var bertusGalleryCurrent;            // Current slide shown.
var bertusGalleryNew;                // New slide shown.
var bertusGalleryTimer;              // Keep track of gallery timer.
var bertusGalleryTotal;              // Keep track of highest index of gallery images (total-1).


//
//
//  BERTUS CONFIG END
//
//  NO USER EDITABLE OPTIONS BEYOND THIS POINT !!!! (No, really)



//  INIT: Set up enhancements
//
function bertusInit()
{
	// Build block links on homepage.
  bertusBlockLinksInit();
	
	// Build block links on homepage.
  bertusLanguageSwitchInit();
  
  // Build menu animations.
  bertusMenuInit();

  // If this is the homepage, set up the blocks
  if ($(document.body).hasClass('home'))
  {
    bertusHomeInit();
  }

  // Init fade out for new lines in My Bertus. 
  bertusNewHighlightInit();

  // Init slideshow.
  bertusGalleryInit();
  
  // Init form inputs and labels. 
  bertusFormsInit();
    
	// If this is IE, add hover to buttons on page
	if (Browser.Engine.trident)
	{
		bertusIeButtonHoverInit();
		bertusIeFixLogo();
	}
}



//  DOMREADY: Attach init routine to domready event
//
window.addEvent("domready", bertusInit);




//  UTILITY FUNCTIONS: Handy stuff for all other enhancements.
//
function bertusOver()
{
	this.addClass("highlight");
}
function bertusOut()
{
	this.removeClass("highlight");
}

function bertusLangOver()
{
	$("languages").getElement("strong").addClass("lowlight");
}

function bertusLangOut()
{
	$("languages").getElement("strong").removeClass("lowlight");
}






//  BLOCKLINKS: Emphasis, hover and click through
//
function bertusBlockLinksInit()
{
	// Fetch links from homepage
	var bLinks = $$(".spotlight li", 
	                "#contentcolumn .releases li", 
	                "#contentcolumn .news li", 
	                ".messages li", 
	                ".onesheets li", 
	                ".downloads li", 
	                ".release", 
	                "div.spotlight");
	if (bLinks.length == 0) return;
	
	// Loop through and attach events
	bLinks.each(function(bLink)
	{
    if (bLink.getElement("a"))
    {
  		bLink.addEvent("mouseover", bertusOver);
  		bLink.addEvent("mouseout", bertusOut);
  		bLink.addEvent("click", bertusBlockLinkFollow);
		}
	});
}

function bertusBlockLinkFollow()
{
	var bLink = $(this).getElement("a");
	location.href = bLink.href;
}




//  LANGUAGE SWITCH: Make the current language subdued when other is hovered over
//
function bertusLanguageSwitchInit()
{
  var langLinks = $$("#languages a");
	if (langLinks.length == 0) return;
	
	// Loop through and attach events
	langLinks.each(function(langLink)
	{
		langLink.addEvent("mouseover", bertusLangOver);
		langLink.addEvent("mouseout", bertusLangOut);
	});
}



//  BERTUS MENU: Animations
//
function bertusMenuInit()
{
  // Get the page type we are on, and store in navigation list for reference.
  var pageType = $(document.body).getProperty("class");
  pageType = pageType.substr(0, pageType.indexOf(" "));
  if (pageType.search(/(music|bertus|mybertus|home)/g) == -1) return;
  $("navigation").setProperty("pagetype", pageType);
  
  // Set up animation of menu items.
  $$("#navigation .shortcut").each(function(foldable)
  {
    foldable.slider = new Fx.Slide(foldable.getElement(".shortcut-inner"),
    {
      duration: bertusMenuDuration,
      onComplete: function()
      { 
        if (!foldable.slider.open) foldable.getParent().removeClass("open");
        foldable.setStyle("visibility","");
      }
    }).slideOut(); 
  });
  
  // Show only one menu when hovering over item.
  $$("#navigation li").each(function(foldToggle)
  {
    foldToggle.addEvent("mouseenter", function()
    {
      bertusHideMenus(foldToggle.id);
      bertusShowMenu(foldToggle);
    });
    foldToggle.addEvent("mouseleave", function()
    {
      bertusHideMenus();
    });
  });
  
  // Hide menus when leaving header with mouse.
  $("mainbox").addEvent("mouseenter", function()
  {
    bertusHideMenus();
  });

  // Set up behaviour of login form inputs.
  $$("#navigation input").each(function(loginField)
  {
    loginField.addEvent("focus", function()
    {
      loginField.getParent("div.shortcut").locked = true;
      loginField.getPrevious().setStyle("visibility","hidden");
    });
    loginField.addEvent("blur", function()
    {
      loginField.getParent("div.shortcut").locked = false;
      if (loginField.value == "")
      {
        loginField.getPrevious().setStyle("visibility","");
      }
    });
  });

  // Set up behaviour of login form inputs.
  $$("#navigation button").each(function(loginButton)
  {
    loginButton.addEvent("focus", function()
    {
      loginButton.getParent("div.shortcut").locked = true;
    });
  });
  
  // Wait double the animation time before showing menu shortcuts.
  setTimeout(function()
  {
    $("navigation").addClass("sliding");
  }, 3*bertusMenuDuration);
}


function bertusShowMenu(elem)
{
  elem.addClass("open");
  elem.getElement(".shortcut").slider.slideIn();
  if (Browser.Engine.trident && elem.getElement("form"))
  {
    setTimeout(function()
    {
      $$("#navigation form p").each(function(formLine)
      {
        formLine.setStyle('visibility','');
      });
    }, bertusMenuDuration);
  }
}
function bertusHideMenus(except)
{
  $$("#navigation .shortcut").each(function(foldable)
  {
    if (foldable.slider.open 
        && !foldable.locked
        && foldable.getParent().id !== except)
    {
      if (Browser.Engine.trident && foldable.getElement("form"))
      {
        $$("#navigation form p").each(function(formLine)
        {
          formLine.setStyle('visibility','hidden');
        });
      }
      foldable.slider.slideOut();
    }
  });
}



//  HOMEPAGE ENHANCEMENTS: Releases & block heights.
//
function bertusHomeInit()
{
  // Set up releases block.
  bertusHomeReleasesInit();
  
  // Unify heights of all blocks.
  bertusUnifyBlocks();
}


//  HOMEPAGE ENHANCEMENTS: Set up releases carrousel.
//
function bertusHomeReleasesInit()
{
  // Keep track of height of releases.
  var releaseHeight = 0;

  // Build the 'selected release' indicator.
	var releaseArrow = new Element("span",
	{
		'id': 'release-selected'
	});

  $$(".releasesblock .releases li").each(function(release, nr)
  {
    // Position cover image.
    release.getElement("img").setStyle('left',nr*80);
    release.getElement("img").addEvent('mouseover',function()
    { 
      if (bertusReleasesSlideshow) clearTimeout(bertusReleasesSlideshow);
      bertusShowRelease(nr);
    });
    release.getElement("img").addEvent('mouseout',function()
    { 
      if (bertusReleasesSlideshow) clearTimeout(bertusReleasesSlideshow);
      bertusReleasesSlideshow = setTimeout(function()
      {
        bertusNextRelease(nr);
      }, bertusReleasesDelay);
    });
    release.getElement("img").addEvent('click',function()
    { 
      if (bertusReleasesSlideshow) clearTimeout(bertusReleasesSlideshow);
      location.href = $(this).getParent().getElement("a").href;
    });
    
    // Check if this release has the largest height.
    var thisReleaseHeight = parseInt(release.getHeight());
    if (thisReleaseHeight > releaseHeight) releaseHeight = thisReleaseHeight;
    
    // Set height on link in heading.
    release.getElement("a").setStyle('height',100);
  });
  
  // Set new height on all releases.
  $$(".releasesblock .releases li").each(function(release, index)
  {
    release.setStyle('height', (105+releaseHeight));
    bertusReleasesTotal = index;
  });

  releaseArrow.inject($$(".releasesblock .releases li").getLast());

  // Don't forget the list parent holding the releases.
  $("attentionrow").getElement(".releases").setStyle('height', (105+releaseHeight));
  
  // Set hover event for links in releases carrousel.
  $$(".releases h3 a").each(function(link)
  {
    link.addEvent("mouseenter", bertusToggleReleaselink);
    link.addEvent("mouseleave", bertusToggleReleaselink);
  });
  
  
  // Start carrousel of releases.
  bertusShowRelease(0);
  bertusReleasesSlideshow = setTimeout(function()
  {
    bertusNextRelease(1);
  }, bertusReleasesDelay);
}

function bertusShowRelease(slideNr)
{
  // Hide all releases content except cover.
  $$(".releases p.meta", ".releases h3").each(function(elem, nr)
  {
    elem.tween('opacity',0);
    elem.setStyle('z-index',0);
  });
  
  var slide = $$(".releases li")[slideNr];
  slide.getElement("p.meta").tween('opacity',1).setStyle('z-index',120);
  slide.getElement("h3").tween('opacity',1).setStyle('z-index',120);
  
  if (Browser.Engine.trident)
  {
    $("release-selected").tween('background-position-x',(slideNr*80-160));
  }
  else
  {
    $("release-selected").tween('background-position',(slideNr*80-160));
  }
}

function  bertusNextRelease(slideNr)
{
  // Check whether slide number is in range.
  if (slideNr < 0 || slideNr > bertusReleasesTotal) return;

  if (bertusReleasesSlideshow) clearTimeout(bertusReleasesSlideshow);
  
  bertusShowRelease(slideNr);
  
  slideNr++;
  if (slideNr > bertusReleasesTotal) slideNr = 0;
  
  bertusReleasesSlideshow = setTimeout(function()
  {
    bertusNextRelease(slideNr);
  }, bertusReleasesDelay);
}

function bertusToggleReleaselink()
{
  $(this).getParent("li").toggleClass('highlight');
}




//  HOMEPAGE ENHANCEMENTS: Set equal block heights within rows.
//
function bertusUnifyBlocks()
{
  // Keep track of height of blocks; set minimum height first.
  var blockHeight = 200;
  
  // Loop through first row (attentionrow)
  $$("#attentionrow .contentblock").each(function(block)
  {
    // Check if this release has the largest height.
    var thisBlockHeight = parseInt(block.getHeight());
    if (thisBlockHeight > blockHeight) blockHeight = thisBlockHeight;
  });
  
  $$("#attentionrow .contentblock").each(function(block, index)
  {
    // Set height on all blocks.
    if (index == 0)
    {
      block.getElements(".releases li").each(function(release)
      {
        release.setStyle('height',blockHeight);
      });
      block.getElement(".releases").setStyle('height',blockHeight);
      block.setStyle('height',blockHeight);
    }
    else if (index == 2)
    {
      block.getElement(".spotlight").setStyle('height',blockHeight-20);
      block.setStyle('height',blockHeight);
    }
    else
    {
      block.setStyle('height',blockHeight);
    }
  });
  
  // Same for second row blocks.
  var newsBlock = $("contentcolumn").getElement(".newsblock").getElement("ul");
  var gigsBlock = $("contentcolumn").getElement(".gigsblock").getElement("ul");
  
  if (newsBlock.getHeight() > gigsBlock.getHeight())
  {
    gigsBlock.setStyle('height', newsBlock.getHeight());
    gigsBlock.getParent().setStyle('height', newsBlock.getHeight());
  }
  else
  {
    newsBlock.setStyle('height', gigsBlock.getHeight());
    newsBlock.getParent().setStyle('height', gigsBlock.getHeight());
  }
}



//  SLIDESHOW: Set up gallery of images if present
//
function bertusGalleryInit()
{
  var galleryParent = $$(".gallery")[0];
  if (!galleryParent || !photogallery) return false;
  
  // We have a gallery dom node and a object containing the images,
  // so let's roll!
  
  // Fetch all images from array and prepare for gallery.
  for (imageNo in photogallery)
  {
    // Build image DOM node from info in object, and insert in DOM.
  	var tmpImg = new Element("img",
  	{
  		'id': 'gallery-'+imageNo,
  		'src': photogallery[imageNo]['href'],
  		'styles':
  		{
  		  'left': -10000,
  		  'top': 0,
  		  'z-index': 200
  		}
  	});
  	tmpImg.inject(galleryParent);
  	bertusGalleryTotal = imageNo;
  }

  // Show first image over default HTML content image.
  $('gallery-0').setStyle('left',0);
  bertusGalleryCurrent = 0;

  // Dispose of the original HTML content image, but
  // fetch height of the image first, to resize gallery if needed.
  galleryParent.setStyle('height', galleryParent.getFirst("img").getSize().y);
  bertusGalleryImgWidth = galleryParent.getFirst("img").getSize().x;
  galleryParent.getFirst("img").dispose();
  
  
  // Build the slideshow button.
	var pagingLi = new Element("li",
	{
		'class': 'paging-overview'
	});
	var pagingButton = new Element("a",
	{
		'href': '#',
		'html': 'Slideshow',
		'events':
		{
		  'click': function(evt) { bertusGalleryToggle(); $(this).blur(); evt.stop(); }
		}
	});
  pagingButton.inject(pagingLi);
  pagingLi.inject(galleryParent.getNext());	

  // check if the previous link already exists, if not generate it and inject it into the DOM
  if (!$(document.body).getElement("li.paging-previous a")) 
  {
      var liPrev = $(document.body).getElement("li.paging-previous");
      var buttonPrev = new Element("a",
        {
            'href': '#',
            'html': '< Previous',
            'events':
            {
              'click': function(evt) { bertusGalleryPrevious(); $(this).blur(); evt.stop(); }
            }
        });
      buttonPrev.inject(liPrev);
  }

  $$(".paging-next a").addEvent('click', function(evt)
  {
    bertusGalleryNext();
    $(this).blur();
    evt.stop();
  });

}

function bertusGalleryToggle()
{
  if (bertusGallerySlideshow == true)
  {
    clearTimeout(bertusGalleryTimer);
    bertusGalleryTimer = bertusGallerySlideshow = null;
  }
  else
  {
    bertusGallerySlideshow = true;
    bertusGalleryTimer = setTimeout(bertusGalleryNext, bertusGalleryDelay/2);
  }
}

function bertusGalleryPrevious()
{
  // Clear runnig timer.
  clearTimeout(bertusGalleryTimer);

  // Prepare layering.
  $$(".gallery img").each(function(galleryImg)
  {
    galleryImg.setStyle('z-index', 200);
  });
  $("gallery-"+bertusGalleryCurrent).setStyle('z-index',220);
  
  // Determine new image to show
  bertusGalleryNew = bertusGalleryCurrent - 1;
  if (bertusGalleryNew < 0) bertusGalleryNew = bertusGalleryTotal;
  
  $("gallery-"+bertusGalleryNew).setStyle('left', 0);

  $("gallery-"+bertusGalleryCurrent).tween('left', bertusGalleryImgWidth);  
  
  // Update counters.
  bertusGalleryCurrent = bertusGalleryNew;
  bertusGalleryNew = null;
  
  // Set new timer if slideshow is on.
  if (bertusGallerySlideshow == true)
  {
    bertusGalleryTimer = setTimeout(bertusGalleryNext, bertusGalleryDelay);
  }
}

function bertusGalleryNext()
{
  // Clear runnig timer.
  clearTimeout(bertusGalleryTimer);

  // Prepare layering.
  $$(".gallery img").each(function(galleryImg)
  {
    galleryImg.setStyle('z-index', 200);
  });
  $("gallery-"+bertusGalleryCurrent).setStyle('z-index',220);
  
  // Determine new image to show
  bertusGalleryNew = bertusGalleryCurrent + 1;
  if (bertusGalleryNew > bertusGalleryTotal) bertusGalleryNew = 0;
  
  $("gallery-"+bertusGalleryNew).setStyle('left', 0);

  $("gallery-"+bertusGalleryCurrent).tween('left', -bertusGalleryImgWidth);  
  
  // Update counters.
  bertusGalleryCurrent = bertusGalleryNew;
  bertusGalleryNew = null;
  
  
  
  // Set new timer if slideshow is on.
  if (bertusGallerySlideshow == true)
  {
    bertusGalleryTimer = setTimeout(bertusGalleryNext, bertusGalleryDelay);
  }
}




//  FORMS INIT: Hide labels on focus.
//
function bertusFormsInit()
{
  // Set up behaviour of login form inputs.
  $$("#contentcolumn input").each(function(loginField)
  {
    loginField.addEvent("focus", function()
    {
      loginField.getPrevious().setStyle("visibility","hidden");
    });
    loginField.addEvent("blur", function()
    {
      if (loginField.value == "")
      {
        loginField.getPrevious().setStyle("visibility","");
      }
    });
    if (loginField.value != "")
    {
      loginField.getPrevious().setStyle("visibility","hidden");
    }
  });
}




//  HIGHLIGHT FADE OUTS: Add fade to new items in My Bertus.
//
function bertusNewHighlightInit()
{
  if ($$(".new"))
  {
    //if (Browser.Engine.trident) alert(Browser.Engine.version);
    if (Browser.Engine.trident)
    {
      // IE6 version: no PNG alpha transparency, so other fadeout.
      setTimeout(bertusIe6Fader, 2000);
    }
    else
    {
      // PNG alpha version of fade.
      setTimeout(bertusPngFader, 2000);
    }
  }
}

function bertusPngFader()
{
    $$("#contentcolumn .contentblock .new").each(function(newItem)
    {
      newItem.fader = new Fx.Morph(newItem, { 'duration': 5000 });
      newItem.fader.start({ 'background-position': '0 -200' });
    });
}


function bertusIe6Fader()
{
    $$("#contentcolumn .contentblock .new").each(function(newItem)
    {
      newItem.fader = new Fx.Tween(newItem, { 'duration': 2000 });
      newItem.setStyle('background-color', '#AACDDC');
      newItem.removeClass('new');
      newItem.fader.start('background-color', '#F0F0F0');
    });
}




//  BUTTON HOVERS: Add hoverstates to buttons in IE.
//
function bertusIeButtonHoverInit()
{
	// Fetch buttons
	var ieButtons = $$("button");
	if (ieButtons.length == 0) return;
	
	// Loop through and attach events
	ieButtons.each(function(ieButton)
	{
		ieButton.addEvent("mouseover", bertusOver);
		ieButton.addEvent("mouseout", bertusOut);
	});
}


//  LOGOTYPE: Duplicate and put on top in IE (trident).
//
function bertusIeFixLogo()
{
  $("logotype").clone().injectAfter('navigation').setProperty('id', 'logotype-ie');
  $("logotype").dispose();
}

