/*   *****************************************************

 *

 *   FEMTO ENGINEERING

 *

 *   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/femto.js

 *   version:  0.1

 *   date:     12/04/2009

 *

 *   *****************************************************

 */





//  CONFIG START

//

//  Set options for several texts and properties here

//



var femtoMenuDuration = 500;  // Animation duration for menu items





var femtoGalleryDelay = 4000;       // Delay between slides (milliseconds).

var femtoGalleryImgWidth;           // Width of the gallery images.

var femtoGallerySlideshow = false;  // Keep track of running slideshow.

var femtoGalleryCurrent;            // Current slide shown.

var femtoGalleryNew;                // New slide shown.

var femtoGalleryTimer;              // Keep track of gallery timer.

var femtoGalleryTotal;              // Keep track of highest index of gallery images (total-1).





//

//  CONFIG END

//

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







//  INIT: Set up enhancements

//

function femtoInit()

{

	// Build block links on homepage.

  // femtoLanguageSwitchInit();

  

  // Build menu animations.

  femtoMenuInit();



  // Init slideshow.

  // femtoGalleryInit();

  

  //new slideshow

//  initSlideshow();

  

  // Init form inputs and labels. 

  femtoFormsInit();

  

}







//  DOMREADY: Attach init routine to domready event

//

window.addEvent("domready", femtoInit);









//  UTILITY FUNCTIONS: Handy stuff for all other enhancements.

//

function femtoOver()

{

	this.addClass("highlight");

}



function femtoOut()

{

	this.removeClass("highlight");

}



function femtoGetIeVersion()

{

  var rv = -1; // Return value assumes failure.

  if (navigator.appName == 'Microsoft Internet Explorer')

  {

    var ua = navigator.userAgent;

    var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");

    if (re.exec(ua) != null)

    {

      rv = parseFloat(RegExp.$1);

    }

  }

  //alert("IE:"+rv);

  return rv;

}









//  LANGUAGE SWITCH

//

function femtoLanguageSwitchInit()

{



}







//  FEMTO MENU: Animations

//

function femtoMenuInit()

{

  // Set up animation of menu items.
  // For now, without languages: "#languages ul ul"

  $$("#navigation ul ul", ".filters .aspect ul").each(function(foldable)

  {

    foldable.originalHeight = parseInt(foldable.getSize()['y']) - 13;

    

    foldable.morph = new Fx.Morph(foldable,

    {

      duration: femtoMenuDuration,

      transition: Fx.Transitions.Sine.easeOut,

      onComplete: function(foldable)

      {

        if (foldable.hasClass("open"))

        {

          foldable.removeClass("open");

        }

        else

        {

          foldable.addClass("open");

        }

      }

    });

    

    if (!foldable.hasClass("open"))

    {

      foldable.morph.set({'height':0, 'opacity':0});

    }

    

    foldable.setStyles(

    {

      'position': 'relative',

      'left': '0',

      'overflow': 'hidden'

    });

  });

  

  // Show only one menu when hovering over item.
  // For now, without languages: "#languages > ul > li > a"

  $$("#navigation > ul > li > a", ".filters .aspect h3").each(function(foldToggle)

  {

    foldToggle.addEvent("click", function()

    {

      var foldable = $(this).getParent().getElement("ul");

      if (foldable.hasClass("open"))

      {

        foldable.morph.start({'height':0, 'opacity':0});

      }

      else

      {

        foldable.morph.start({'height':foldable.originalHeight, 'opacity':1});

      }

    });

  });

  //ddetyuk [Feb 08, 2010]

  $$("#navigation > ul > li > ul > li, #languages > ul > li > ul > li").each(function(foldToggle)

  {

      foldToggle.setStyles({

      'position': 'relative',

      'left': '0'

    });

  });

}













//  HOMEPAGE ENHANCEMENTS: Releases & block heights.

//

function femtoHomeInit()

{



}







//  FORM ENHANCEMENTS: Add presentation for focus.

//

function femtoFormsInit()

{

  var formFields = $$("form p input", 

                      "form p textarea", 

                      "form p select", 

                      "form button");

  if (formFields.length == 0) return;

  

  formFields.each(function(elem, index)

  {

    elem.addEvent('focus', function()

    {

      if (!this.getParent().hasClass('focus'))

      {

        this.getParent().addClass('focus');

      }

    });

    elem.addEvent('blur', function()

    {

      this.getParent().removeClass('focus');

    });

  });

}









//  SLIDESHOW: Set up gallery of images if present

//

function femtoGalleryInit()

{

  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);

  	femtoGalleryTotal = imageNo;

  }



  // Show first image over default HTML content image.

  $('gallery-0').setStyle('left',0);

  femtoGalleryCurrent = 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);

  femtoGalleryImgWidth = 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) { femtoGalleryToggle(); $(this).blur(); evt.stop(); }

		}

	});

  pagingButton.inject(pagingLi);

  pagingLi.inject(galleryParent.getNext());	

  

  // Set up previous and next buttons to use script instead of vanilla urls.

  $$(".paging-previous a").addEvent('click', function(evt)

  {

    femtoGalleryPrevious();

    $(this).blur();

    evt.stop();

  });

  $$(".paging-next a").addEvent('click', function(evt)

  {

    femtoGalleryNext();

    $(this).blur();

    evt.stop();

  });



}



function femtoGalleryToggle()

{

  if (femtoGallerySlideshow == true)

  {

    clearTimeout(femtoGalleryTimer);

    femtoGalleryTimer = femtoGallerySlideshow = null;

  }

  else

  {

    femtoGallerySlideshow = true;

    femtoGalleryTimer = setTimeout(femtoGalleryNext, femtoGalleryDelay/2);

  }

}



function femtoGalleryPrevious()

{

  // Clear runnig timer.

  clearTimeout(femtoGalleryTimer);



  // Prepare layering.

  $$(".gallery img").each(function(galleryImg)

  {

    galleryImg.setStyle('z-index', 200);

  });

  $("gallery-"+femtoGalleryCurrent).setStyle('z-index',220);

  

  // Determine new image to show

  femtoGalleryNew = femtoGalleryCurrent - 1;

  if (femtoGalleryNew < 0) femtoGalleryNew = femtoGalleryTotal;

  

  $("gallery-"+femtoGalleryNew).setStyle('left', 0);



  $("gallery-"+femtoGalleryCurrent).tween('left', femtoGalleryImgWidth);  

  

  // Update counters.

  femtoGalleryCurrent = femtoGalleryNew;

  femtoGalleryNew = null;

  

  // Set new timer if slideshow is on.

  if (femtoGallerySlideshow == true)

  {

    femtoGalleryTimer = setTimeout(femtoGalleryNext, femtoGalleryDelay);

  }

}



function femtoGalleryNext()

{

  // Clear runnig timer.

  clearTimeout(femtoGalleryTimer);



  // Prepare layering.

  $$(".gallery img").each(function(galleryImg)

  {

    galleryImg.setStyle('z-index', 200);

  });

  $("gallery-"+femtoGalleryCurrent).setStyle('z-index',220);

  

  // Determine new image to show

  femtoGalleryNew = femtoGalleryCurrent + 1;

  if (femtoGalleryNew > femtoGalleryTotal) femtoGalleryNew = 0;

  

  $("gallery-"+femtoGalleryNew).setStyle('left', 0);



  $("gallery-"+femtoGalleryCurrent).tween('left', -femtoGalleryImgWidth);  

  

  // Update counters.

  femtoGalleryCurrent = femtoGalleryNew;

  femtoGalleryNew = null;

  

  

  

  // Set new timer if slideshow is on.

  if (femtoGallerySlideshow == true)

  {

    femtoGalleryTimer = setTimeout(femtoGalleryNext, femtoGalleryDelay);

  }

}



function updateSlide(project){

	var title = new Element('a', {

		'href': project.title.href,

		'html': project.title.value,

		'title': project.title.href

		});

	$("slideshow_title").empty().grab(title);

	$("slideshow_introduction").empty().appendText(project.introduction);

	$("slideshow_links").empty();

	if(typeof(project.links)!="undefined"){

		$each(project.links,function(links){

			var aspect = new Element("div", {"class": "aspect"});

			var name = new Element("h3", {"html": links.name});

			var ul = new Element("ul");

			if(typeof(links.links)!="undefined"){

				$each(links.links,function(link){

					var li = new Element("li");

					var a = new Element('a', {'href':link.href,'title': link.name});

					var title = new Element("span",{"html":  "<span>"+link.name+"</span>&nbsp;&gt;"});	

					a.grab(title);

					li.grab(a);

					ul.grab(li);

				});

			}

			aspect.grab(name);

			aspect.grab(ul);

			$("slideshow_links").grab(aspect);

		});

	}

}



function updateControl(){

	if(slideshow.paused){

		$('control-play').getFirst().set('text',"Play slideshow");
		$('control-play').getFirst().setStyle('background-image', 'url("http://www.femto-engineering.ru/tl_files/femto/presentation/images/bg-slideshow-control-play.gif")')		


	}else{

		$('control-play').getFirst().set('text',"Pause slideshow");	
		$('control-play').getFirst().setStyle('background-image', 'url("http://www.femto-engineering.ru/tl_files/femto/presentation/images/bg-slideshow-control-pause.gif")')		

	}

}



function initSlideshow(){

	var feed = '/tl_files/femto/xml/top_projects.json';

	var config = {

		thumbnails: false,

		controller: true, 	

		overlap:false,

		height: 400, 

		width: 600,

		delay: 10000,

		duration: 1000,

		onStart:function(){

			updateSlide(projects[this.slide]);

			updateControl();

		}

	};

	var request = new Request({

		url: feed,

		onSuccess: function(text, xml){

			projects = eval(text);

			var data = new Object();

			$each(projects,function(project){

				data[project.image]  =  new Object({"caption":project.title.value});

			});

			slideshow = new Slideshow.Flash('slideshow_image', data, config);

			//slideshow = new Slideshow.Push('slideshow_image', data, config);

			//slideshow = new Slideshow.Fold('slideshow_image', data, config);

			//slideshow = new Slideshow.KenBurns('slideshow_image', data, config);

			//slideshow = new Slideshow('slideshow_image', data, config);

			

			$('slideshow_image').addClass('visual');

			$('slideshow_image').setStyle("position","absolute");

			$('control-next').addEvent('click',function(){

				slideshow.next();

				updateControl();

			});

			$('control-play').addEvent('click',function(){

				if(slideshow.paused){

					slideshow.pause(false);

				}else{

					slideshow.pause(true);

				}

				updateControl();

			});

		}

	}).get();

}
