//
// selectors
//

Selector.apply({

	/**
	 * Apply some special fonts
	 * @author François Patry (francois.patry@lemieuxbedard.com)
	 */
	'body': function(el){
		if( Browser.ie && ( Browser.version <= 8 ) ) {
            Cufon.replace('#main-header nav ul li');
            Cufon.replace('#main-content-header h1');
            Cufon.replace('#main-content-header p');
            Cufon.replace('.gallery-view h2');
            Cufon.replace('.gallery-view h3');
            Cufon.replace('#division-selector a');
            Cufon.now();
        }
        
        //Hide infopress-banner
        /*setTimeout(function(){
        	var banner = document.id('infopress-banner');
        	
        	banner.morph({
			    'height': 25, // Morphs the height from the current to 100px.
			    'line-height': 25   // Morphs the width from the current to 300px.
			});
        	
        }, 250);*/
        
        //Hide eyeforpharma-banner
        /*setTimeout(function(){
        	var banner = document.id('eyeforpharma-banner');
        	if(banner)
        	{
	        	banner.morph({
	        		'top':'-57px'
				});
			}
        }, 250);*/
	},

	/**
	 * Fade in and out the navigation.
	 * @author François Patry (francois.patry@lemieuxbedard.com)
	 */
	'#main-header nav ul li a::mouseenter': function(el) { el.fade(0.3); },
	'#main-header nav ul li a::mouseleave': function(el) { el.fade(1.0); },
	
	'.gallery-browser .select::mouseenter': function(el) {
		el.addClass('open');
	},

	'.gallery-browser .select::mouseleave': function(el) {
		el.removeClass('open');
	},
	
	
	/*'#eyeforpharma-banner::mouseenter': function(el) {
		var banner = document.id('eyeforpharma-banner');
        	
    	banner.morph({
    		'top':'0px'
		});
	},
	
	'#eyeforpharma-banner::mouseleave': function(el) {
		var banner = document.id('eyeforpharma-banner');
        	
    	banner.morph({
    		'top':'-57px'
		});
	},*/

	
	/**
	 * Initialize different pieces of this page.
	 * @author Jean-Philippe Dery (jean-philippe.dery@lemieuxbedard.com)
	 */
	'#contact-index': function() {
		var togglers = $$('#contact-index .accordion .toggler');
		var elements = $$('#contact-index .accordion .element');
		var expertises = new lemieuxbedard.web.Accordion(togglers, elements);
	},
	
	/**
	 * Initialize different pieces of this page.
	 * @author Jean-Philippe Dery (jean-philippe.dery@lemieuxbedard.com)
	 */
	'#career-apply': function() {
		var togglers = $$('#career-apply .accordion .toggler');
		var elements = $$('#career-apply .accordion .element');
		var expertises = new lemieuxbedard.web.Accordion(togglers, elements);
	},
	
	/**
	 * Initialize different pieces of this page.
	 * @author Jean-Philippe Dery (jean-philippe.dery@lemieuxbedard.com)
	 */
	'#expertise-list': function() {
		var togglers = $$('#expertise-list .accordion .toggler');
		var elements = $$('#expertise-list .accordion .element');
		var expertises = new lemieuxbedard.web.Accordion(togglers, elements);
	},
	
	/**
	 * Initialize this page.
	 * @author Jean-Philippe Dery (jean-philippe.dery@lemieuxbedard.com)
	 */	
	'#default-index': function(el) {
		// automatically adujust the background element to make sure
		// it will not go beyond the bottom of the screen
		var bg = el.getElement('.bg');
		if (bg) {
			bg.adjust = function() { this.setStyle('height', window.getSize().y + 20); };
			bg.adjust();
			window.addEvent('resize', function() { 
				bg.adjust();
			});
		}
	},

	/**
	 * Center the main text of the default page.
	 * @author Jean-Philippe Dery (jean-philippe.dery@lemieuxbedard.com)
	 */	
	'#default-index #showreel': function(el) {
		el.position({
			offset: {
				y: 50
			}
		});	
	},
	
	/**
	 * Center the main text of the default page.
	 * @author Jean-Philippe Dery (jean-philippe.dery@lemieuxbedard.com)
	 */	
	'#default-index #promo-2011-2012': function(el) {
		el.position({
			offset: {
				y: 50
			}
		});	
	},

	/**
	 * Initialize a mask for the video.
	 * @author Jean-Philippe Dery (jean-philippe.dery@lemieuxbedard.com)
	 */		
	'#default-index #video': function(el) {
		var start = document.id('play');

		if (Browser.ie6==undefined && Browser.ie7==undefined && Browser.ie8==undefined) {
			var video = new lemieuxbedard.web.Video(el, { mask: true, start: start});
		}
		else
		{
			start.addEvent('click', function(e) {
				e.stop();
				$('promo-2011-2012').hide();
				$('showreel').show();
				/*document.body.addEvent('click', function(e) {
					$('showreel').hide();
				});*/
			});
		}

		if (video && video.isUsable() == false) {
			document.id('play').destroy();
		}
	},
	
	'#default-index #video-mp4': function(el) {
		if (Browser.Platform.ios) {
			el.src = el.src.replace('showreel', 'showreel.ios');
		}
	},
	
	/**
	 * Center the division selector bar.
	 * @author Jean-Philippe Dery (jean-philippe.dery@lemieuxbedard.com)
	 */	
	'#default-index #division-selector': function(el) {
		el.position({
			position: 'centerLeft'
		});
		if (Browser.ie6) el.setStyle('width', window.getSize().x);
		
		$('promo-2011-2012').hide();
	},

	/**
	 * Remove the href property from both links.
	 * @author Jean-Philippe Dery (jean-philippe.dery@lemieuxbedard.com)
	 */	
	'#default-index #division-selector a': function(el) {
		el.disposeHrefProperty();
	},

	/**
	 * Fade the division selector once a navigation element is clicked.
	 * @author Jean-Philippe Dery (jean-philippe.dery@lemieuxbedard.com)
	 */	
	'#default-index #division-selector a::click': function(el) {
		var bar = document.id('division-selector');
		var reel = document.id('showreel');
		var header = document.id('main-header');
		var footer = document.id('main-footer');
		var y1 = bar.getCoordinates().top;
		var y2 = header.getCoordinates().top + 50;
		new Fx.Tween(bar).start('top', y1, y2).chain(function() {
			bar.fade(0);
			$('promo-2011-2012').show();
			
			if (el.hasClass('redirect')) {
				window.location.href = el.getDisposedHrefProperty();
			} else {
				[header, footer].each(function(elem) {
					elem.fade('hide');
					elem.fade(1);
					elem.show();				
				});
			}
		});	
	},
	
	/**
	 * Initialize each gallery.
	 * @author Jean-Philippe Dery (jean-philippe.dery@lemieuxbedard.com)
	 */		
	'#portfolio-list .gallery': function(el) {
		new lemieuxbedard.web.Gallery(el, { items: 5 });
	},
	
	/**
	 * Initialize different pieces of this page.
	 * @author Jean-Philippe Dery (jean-philippe.dery@lemieuxbedard.com)
	 */
	'#portfolio-view': function() {
		var togglers = $$('#portfolio-view .accordion .toggler');
		var elements = $$('#portfolio-view .accordion .element');
		var expertises = new lemieuxbedard.web.Accordion(togglers, elements);
	},

	/**
	 * Initialize different pieces of this page.
         *
         * - Updated by Yannick Gagnon (yannick.gagnon@lemieuxbedard.com)
         *   Binded the events(mouseenter and mouseleave) to the element itself
         *   to prevent the closing of the dropdown when the mouse leave the button
         *   
	 * @author Jean-Philippe Dery (jean-philippe.dery@lemieuxbedard.com)
	 */	
	'#portfolio-view .popup': function(el) {
		var title = el.getElement('span');
		var list = el.getElement('ul');
		el.empty();
		var button = new Element('div.handle').grab(title);
		var items = new Element('div.items').grab(list);
		el.grab(button);
		el.grab(items);
		var tween = new Fx.Tween(items);		
		el.addEvent('mouseenter', function() {
			items.show();
			tween.cancel();
			tween.start('opacity', 0, 1).chain(function() {});
		});
		el.addEvent('mouseleave', function() {
			tween.cancel();
			tween.start('opacity', 1, 0).chain(function() { items.hide(); });
		});
	},

        /**
         *  Adds a class to the last li element to prevent the addition of the bottom border
         *
         *  @author Yannick Gagnon (yannick.gagnon@lemieuxbedard.com)
         */
        '#portfolio-view .popup .items li:last-child': function(el) {
		el.addClass('last');
	},

    '#team-view .reach-me .email': function(el) {
        var email = el.get('html');

        email = email.replace(/dot/ig, ".");
        email = email.replace(/\(at\)/ig, "@");
        email = email.replace(/\s/g, "");

        el.set( 'html', '<a href="mailto:{email}">{email}</a>'.replace(/{email}/ig, email) );
    },
    
    '#promo-2011-2012 .step1::click': function(el) {
    	el.fade('toggle');
    	$$('#promo-2011-2012 .step2').show();
    },
    
    '#promo-2011-2012 .start::click': function(el) {
    	$$('#promo-2011-2012 .footer .desc').hide();
    	var slideshow = new Slideshow('people', {'interval': 3500});
    	$$('#promo-2011-2012 .footer .people').show().fade(1);
    }
	
});

window.addEvent('resize', function() {

	var showreel = document.id('showreel');
	if (showreel) {
		showreel.position({
			offset: {
				y: 50
			}
		});	
	}

	var selector = document.getElement('#default-index #division-selector');
	if (selector) {
		selector.position({position: 'centerLeft'});
		if (Browser.ie6) selector.setStyle('width', window.getSize().x);
	}
	
	var promo = document.id('promo-2011-2012');
	if (promo) {
		promo.position({
			offset: {
				y: 50
			}
		});	
	}
	
});

window.addEvent('load', function() {
	SA.redirection_mobile ({
        //mobile_url : "victory-assist.amgen.dev.lemieuxbedard.ca/m",
        mobile_prefix : 'm',
        noredirection_param:"redirection"
    });
});

//
// class definitions
//

window.lemieuxbedard     = {};
window.lemieuxbedard.web = {};

lemieuxbedard.web.Video = new Class({
	
	Implements: [Events, Options],
	
	element: null,

	start: null,

	mask: null,
		
	options: {
		mask: true,
		start: null
	},
	
	initialize: function(element, options) {
		this.setOptions(options);
		
		this.element = document.id(element);
		if (this.options.start) this.start = document.getElement(this.options.start);
		if (this.options.mask) {
			this.mask = new Mask($(document.body), {
		        hideOnClick: true,
				style: {'opacity': 0 },
				onShow: function() { 
					this.element.show().fade(0.75); 
					document.id('showreel').show().fade(1); 
				},
				onHide: function() { 
					this.element.show().fade(0);
					document.id('showreel').fade(0); 
					
					(function(){
						document.id('showreel').hide();
					}).delay(300);
				}
			});
		} 
		
		
		if (Browser.Platform.ios) {
			if (this.start) {
				this.start.destroy();
			}
			this.element.fade('show');
			this.element.show();
		}
		
		this.attachEvents();
		return this;
	},

	attachEvents: function() {
		this.element.addEvent('play', this._onPlay.bind(this));
		this.element.addEvent('pause', this._onPause.bind(this));
		if (this.mask) this.mask.addEvent('hide', this._onMaskHide.bind(this));
		if (this.start) this.start.addEvent('click', this._onStartClick.bind(this));
	},
	
	detachEvents: function() {
		this.element.removeEvent('play', this._onPlay);
		this.element.removeEvent('pause', this._onPause);
		if (this.mask) this.mask.removeEvent('hide');
		if (this.start) this.start.removeEvent('click');
	},
	
	_onStartClick: function() {
		this.play();
	},	
	
	_onMaskHide: function() {
		this.pause();
	},

	_onPlay: function() {

		if (this.start) this.element.fade(1);
		if (this.mask) this.mask.show();
		//if (this.start) this.start.fade(0);
	},
	
	_onPause: function() {
		/*if (this.mask) this.mask.hide();*/
		//if (this.start) this.start.fade(1);	
	},
		
	play: function() {
		this.element.play();
	},
		
	pause: function() {
		this.element.pause();
	},
	
	showMask: function() {
		if (this.mask) this.mask.show();
	},
		
	hideMask: function() {
		if (this.mask) this.mask.hide();
		this.element.hide();
	},

	isUsable: function() {
		return this.element.play != undefined;
	}
		
});

/**
 * This class extends the basic accordion class and set the default
 * options and events all accordions must use on that site
 * @package lemieuxbedard
 * @subpackage web
 * @author Jean-Philippe Dery (jean-philippe.dery@lemieuxbedard.com)
 * @version 1.0.0
 */
lemieuxbedard.web.Accordion = new Class({
	
	Extends: Fx.Accordion,
	
	options: {
	    display: -1,
	    alwaysHide: true
	},
	
	initialize: function(togglers, elements, options) {
		this.parent(togglers, elements, options);
		this.attachEvents();
	},

	attachEvents: function() {
		this.addEvent('active', this.togglerActivated.bind(this));
		this.addEvent('background', this.togglerBackgrounded.bind(this));
	},

	detatchEvents: function() {
		this.removeEvent('active', this.togglerActivated);
		this.removeEvent('background', this.togglerBackgrounded);
	},
	
	togglerActivated: function(toggler, element) {
		toggler.addClass('active');
	},
	
	togglerBackgrounded: function(toggler, element) {
		toggler.removeClass('active');
	}
	
});


lemieuxbedard.web.Gallery = new Class({

	/**
	 * @implements Events, Options
	 */
	Implements: [Events, Options],
	
	/**
	 * @var object The root element of the gallery.
	 * @access protected
	 */
	element: null,
	
	/**
	 * @var array The headers of each departments.
	 * @access protected
	 */
	heads: null,
	
	/**
	 * @var array The list underneath each headers.
	 * @access protected
	 */
	items: null,
	
	/** 
	 * @var object The options.
	 * @access protected
 	 */
	options: {
		// itemShrinked
		// itemExpanded
		items: null
	},
	
	/**
	 * @var object The scroller object.
	 * @access protected
	 */
	scroller: null,
	
	/**
	 * @var string The current status, shrinked or expanded.
	 * @access protected
	 */
	status: 'shrinked',
	
	/**
	 * Initialize the gallery.
	 * @param object The root element.
	 * @return object This instance.
	 * @author Jean-Philippe Dery (jean-philippe.dery@lemieuxbedard.com)
	 * @access public
	 */
	initialize: function(element, options) {
		this.setOptions(options);
		this.element = document.id(element);

		this.head = this.element.getElement('h3');
		this.more = this.element.getElement('h3 .more');
		this.more.show();
		this.less = this.element.getElement('h3 .less');
		this.less.hide();
		this.items = this.element.getElements('.gallery-item');
		this.scroller = new Fx.Scroll($(document.body));
		this._initializeLists();
		this.attachEvents();
		return this;
	},
	
	/**
	 * Initialize the list by hiding all but the set ammount of visible items.
	 * @return object This instance.
	 * @author Jean-Philippe Dery (jean-philippe.dery@lemieuxbedard.com)
	 * @access public
	 */		
	_initializeLists: function() {
		if (this.items.length > this.options.items) {
			for (var i = this.options.items; i < this.items.length; i++) {
				this.items[i].hide();
			}
		}
		return this;
	},	
	
	/**
	 * Attach events to element of this object.
	 * @return object This instance.
	 * @author Jean-Philippe Dery (jean-philippe.dery@lemieuxbedard.com)
	 * @access public
	 */	
	attachEvents: function() {
		this.more.addEvent('click', this.toggleListItems.bind(this));
		this.less.addEvent('click', this.toggleListItems.bind(this));
		return this;
	},
	
	/**
	 * Detatch events to element of this object.
	 * @return object This instance.
	 * @author Jean-Philippe Dery (jean-philippe.dery@lemieuxbedard.com)
	 * @access public
	 */		
	detatchEvents: function() {
		this.more.removeEvent('click', this.toggleListItems);
		this.less.removeEvent('click', this.toggleListItems);
		return this;
	},
	
	/**
	 * Detatch events to element of this object.
	 * @return object This instance.
	 * @author Jean-Philippe Dery (jean-philippe.dery@lemieuxbedard.com)
	 * @access public
	 */	
	toggleListItems: function() {
		switch (this.status) {
			case 'shrinked': 
				this._expandListItems(); 
				this.more.hide();
				this.less.show();
			break;
			case 'expanded': 
				this._shrinkListItems(); 
				this.more.show();
				this.less.hide();
			break;
		}
	},
	
	/**
	 * Detatch events to element of this object.
	 * @return object This instance.
	 * @author Jean-Philippe Dery (jean-philippe.dery@lemieuxbedard.com)
	 * @access public
	 */	
	_expandListItems: function() {
		var mult = 0;
		this.status = 'expanded';
		this.items.each(
			function(item, index) {
				var max = this.options.items - 1;
				if (max < index) {
					item.show();
					item.fade('hide');
					item.fade(1);
					item.fade.delay(mult * 100, item, 1);
					mult++;
				}				
			}.bind(this)
		);
		this.scroller.toElement(this.head);
		this.fireEvent('expanded');
	},
	
	/**
	 * Detatch events to element of this object.
	 * @return object This instance.
	 * @author Jean-Philippe Dery (jean-philippe.dery@lemieuxbedard.com)
	 * @access public
	 */	
	_shrinkListItems: function() {
		this.status = 'shrinked';
		this.items.each(
			function(item, index) {
				var max = this.options.items - 1;
				if (max < index) {
					item.hide();
				}
			}.bind(this)
		);
		this.fireEvent('shrinked');
	}

});
	
//
// html video mootools fix
//	
	
var media_events = {
   loadstart: 2, progress: 2, suspend: 2, abort: 2,
   error: 2, emptied: 2, stalled: 2, play: 2, pause: 2,
   loadedmetadata: 2, loadeddata: 2, waiting: 2, playing: 2,
   canplay: 2, canplaythrough: 2, seeking: 2, seeked: 2,
   timeupdate: 2, ended: 2, ratechange: 2, durationchange: 2, volumechange: 2
}

Element.NativeEvents = Object.merge(Element.NativeEvents, media_events);

var media_properties = [
  'videoWidth', 'videoHeight', 'readyState', 'autobuffer',
  'error', 'networkState', 'currentTime', 'duration', 'paused', 'seeking',
  'ended', 'autoplay', 'loop',  'controls', 'volume', 'muted',
  'startTime', 'buffered', 'defaultPlaybackRate', 'playbackRate', 'played', 'seekable' // these 6 properties currently don't work in firefox      
]; 

media_properties.each(function(prop) {
  Element.Properties[prop] = {
     set: function(value) { this[prop] = value; },
     get: function() { return this[prop]; }
  };
});

/*
---

name: Slideshow

description: Site-wide initialization using selectors.

license: MIT-style license.

requires:
        

provides:
    - Slideshow

...
*/

/**
* Class Pager is reponsible for building a pager for the SlideShow Class
*/
var Pager = new Class({
    Implements: [Options],
    options: {
        orientation: 'horizontal'
    },

    /**
    * Constructor
    */

    initialize: function(element_id, slideshowWidget, options) {
        this.setOptions(options);

        this.widget = $(element_id);
        this.widget.addClass(this.options['orientation']);

        this.slideshowWidget = slideshowWidget;

        this.slideshowWidget.addEvent('loaded', this.setup.bind(this));
        this.slideshowWidget.addEvent('updated', this.update.bind(this));
    },

    /**
    * Setup the pager by adding one button per image
    */
    setup: function() {
        var total = this.slideshowWidget.totalSlides;

        /**
        * Could be overhauled to suport alt tags for thumbnail puck
        */
        for( var i = 0; i < total; i++ ) {
                this.widget.grab(
                        new Element('img', {'class': 'puck', 'data-index': i, src: 'images/pixel.gif'})
                );
        }

        /**
        * Assigns a click event to all pucks to select an image from the slideshow
        */
        this.widget.getElements('.puck').each(function(item, index){
                item.addEvent('click', this.slideshowWidget.select.pass(item.get('data-index'), this.slideshowWidget));
        }.bind(this));

        /**
        * Sets the first puck as selected
        */
        this.widget.getElement('.puck').addClass('selected');
    },

    /*
    * Tells the pager to flag the selected button
    */
    update: function() {
        var selectedIndex = this.slideshowWidget.getCurrent();

        this.widget.getElements('.puck').each(function(item, index){
            if(index == selectedIndex) {
                    item.addClass('selected');
            } else {
                    item.removeClass('selected');
            }
        }.bind(this));
    }
});

/**
* Class Slideshow generates a slideshow off of a list of elements
*/
var Slideshow = new Class({
    Implements: [Options, Events],
    options: {
        'interval': 5000,
        'orientation': 'horizontal',
        'autoplay': true
    },
    /**
    * Constructor
    */
    initialize: function(element_id, options) {
        this.setOptions(options);

        this.slideshowElement = $(element_id);
        this.slideIdPrefix = element_id + '-';
        this.totalSlides = 0;
        this.currentSlide = 0;
        this.timer = null;

        if( this.options['pager'] ) {
                this.pager = new Pager(this.options['pager'], this, {orientation: this.options['orientation']});
        }

        this.load();
        this.slideshowElement.addClass(this.options['orientation']);
        this.start();
    },

    /**
    * Loads all the elements and hide them
    */
    load: function() {
        var slides = this.slideshowElement.getElements('li');
        this.totalSlides = slides.length;

        slides.each(function(item, index){
                item.set('id', this.slideIdPrefix + index.toString());
                item.setStyles({'position': 'absolute'});
                item.fade('hide');
        }.bind(this));

        this.fireEvent('loaded');
    },

    /**
    * Kick off the slideshow processing
    */
    start: function() {
        var firstSlide = $( this.slideIdPrefix + this.currentSlide);
        firstSlide.fade('show');

        if( this.options['autoplay'] == true) {
                this.timer = this.process.periodical(this.options['interval'], this);
        }
    },

    /**
    * Clears the timer, which stops the slideshow
    */
    stop: function() {
        clearInterval( this.timer );
    },

    /**
    * Starts the slideshow effect
    */
    process: function() {
        this.select();
    },


    /**
    * Sets the current index
    */
    setCurrent: function(index) {
        this.currentSlide = index;
    },

    /**
    * Gets the next index
    */
    getNext: function() {
        return this.currentSlide = this.currentSlide + 1 >= this.totalSlides ? 0 : this.currentSlide + 1;
    },

    /**
    * Gets the current index
    */
    getCurrent: function() {
        return this.currentSlide;
    },

    /**
    * Gets a slide element off of an element_id
    */
    getSlideElement: function(element_id) {
        return $(element_id);
    },

    /**
    * Selects the specified index of the next one
    */
    select: function(index) {

        if( index && (index == this.getCurrent())) {
                return;
        }

        var currentSlideElement = this.getSlideElement(this.slideIdPrefix + this.getCurrent().toString());
        currentSlideElement.removeClass('current');
        currentSlideElement.addClass('previous');

        var next = this.getNext();
        
        //If only 1 person stop
        if(this.totalSlides==2 && next==0) {
        	this.stop();
        	return false;
        }
        
        if( index ) {
                this.stop();
                this.setCurrent( index );
                next = index;
        }

        var nextSlideElement = this.getSlideElement(this.slideIdPrefix + next.toString());
        nextSlideElement.addClass('current');
        nextSlideElement.set('tween', {duration: 700}).fade(1);

        this.fireEvent('updated');

        currentSlideElement.set('tween', {duration: 700}).fade(0);
        currentSlideElement.removeClass('previous');
    }
});
	
