Cufon.set('fontFamily', 'DinBlack');
Cufon.set('hover', 'true');

// mainmenu
Cufon.replace('#main-nav a > span:first-child', {hoverables: {span: true}});
Cufon.replace('#main-nav a > span:first-child + span', {fontFamily: 'DinBold', hover: true});

// Blog nav
Cufon.replace('header nav#blog-nav');

// footer
Cufon.replace('footer ul li',{fontFamily: 'DinBold', hover: false});

//The mouseout does not work on mainmenu. Therefore this workaround
Lazzo.runFixCufonMainMenu = function(){
    var refresh = function(){
        Cufon.refresh('#main-nav a > span:first-child');
		Cufon.refresh('#main-nav a > span:first-child + span');
    };
    var f = function() {
        setTimeout(refresh, 10)
    }
    $$('#main-nav a').invoke('on', 'mouseleave', f);
	$$('#main-nav a').invoke('on', 'mouseenter', f);
}
//prevent cufon from flicker
Cufon.CSS.ready(function() {
  $(document.body).addClassName('cufon-ready');
});

/*
 *
 * CufonReplace
 *
 *
 */

Lazzo.CufonReplace = Class.create(Lazzo.Mixin, {
	initialize: function( element ) {
//        Short cut: use own select method. Will do for now.
        Cufon.replace('#subnavigation a');
        Cufon.replace('#blog-pages-header');
        Cufon.replace('#tagline');
	}
});
Lazzo.runCufonReplace = function() {
	try {
		$$('*[data-widget~=cufon-replace]').each(function(element) {
			new Lazzo.CufonReplace(element);
		});
	} catch (e) {
		Lazzo.catching.error('CufonReplace', e);
	}
};













/*
 *
 * MainAppear
 *
 *
 */

Lazzo.MainAppear = Class.create(Lazzo.Mixin, {
	initialize: function() {
		var main = $('main');
		if (!main) { /* home does not have main */
			main = new Element('div', {id:'main'});
			$('container').insert( main );
		}
		main.setStyle({opacity:0,visibility:'visible'});
		main.appear({ delay: 2.0, duration: 0.5 });
	}
});
Lazzo.RunMainAppear = function() {
	try {
		new Lazzo.MainAppear();
	} catch (e) {
		Lazzo.catching.error('Lazzo.MainAppear', e);
	}
};




Lazzo.AjaxGet = Class.create(Lazzo.Mixin, {
	initialize: function(wrapper) {
		this.wrapper = wrapper;
        this.wrapper.removeAttribute('data-widget');
        this.loadingElement = $('loading');
        this.body = $(document.body);
		this.config = this.readConfig(this.wrapper, 'ajax-get');
        this.wrapper.select('a').each(this.attachHandler.bind(this));
	},
    attachHandler: function(element) {
        element.on('click', this.get.bind(this))
    },
    get: function(evt){
        evt.stop();
        this.loadingElement.addClassName('active');
        var element = evt.findElement('a');
		// add active class
		if (this.config.addActiveClass && element.up('li')) {
			element.up('ul').select('li').invoke('removeClassName', 'active');
			element.up('li').addClassName('active');
			Cufon.refresh('#main-nav a > span:first-child');
		}
        var href = element.readAttribute('href');
		if (Modernizr.history) {
			window.history.pushState({reload:true}, "Title", href);
		}
        new Ajax.Request(href, {
            method:'get',
            onComplete:this.showResponse.bind(this)
        })
    },
    showResponse: function(t) {
        var html = t.responseText.stripScripts();
        var temp = new Element('div').update(html); // todo: used html as element. IE didn't like it. Now using body. Check what's best.

        if ( this.body.down('div#main') ) {
            this.body.down('div#main').replace(temp.down('div#main'));
        } else {
            this.body.down('header').insert({after:temp.down('div#main')});
        }
//        movie pages
        if ( this.body.down('header').next('.fill-screen-image') ) {
            this.body.down('header').next('.fill-screen-image').replace(temp.down('header').next('.fill-screen-image'));
            this.body.down('header').next('.fill-screen-image-css3').replace(temp.down('header').next('.fill-screen-image-css3'));
        } else {
//            we've got a new one, but element does not exist yet
            if (temp.down('header').next('.fill-screen-image')) {
                this.body.down('header').insert({after:temp.down('header').next('.fill-screen-image-css3')});
                this.body.down('header').insert({after:temp.down('header').next('.fill-screen-image')});
            }
        }

        this.body.down('#container').writeAttribute('class', temp.down('#container').readAttribute('class'));
        this.body.down('#container').writeAttribute('data-menu-style-mode', temp.down('#container').readAttribute('data-menu-style-mode'));

        Lazzo.Bootstrap();

        addthis.toolbox($('addthis'), {ui_open_windows:true}, {templates: {twitter: '{{url}} #Ambassadors'}});      // todo. move this into his own class.

        this.loadingElement.removeClassName('active');
    }
});
Lazzo.RunAjaxGet = function() {
	if (lessThanIE9) { return; }
    if ($('apache-made')) {       // this is a deeplink. Make a pagerefresh after this one.
        return;
    }
	try {
		$$('*[data-widget~=ajax-get]').each(function(element) {
			new Lazzo.AjaxGet(element);
		});
	} catch (e) {
		Lazzo.catching.error('Lazzo.AjaxGet', e);
	}
};








/*
 *
 * SetCookieNav
 * Must the next page start width docked or open navigation?
 *
 *
 */

Lazzo.SetCookieNav = Class.create(Lazzo.Mixin, {
	initialize: function(element) {
		this.element = element;
        this.setNavDockedCookie('true');
        this.element.select('a').each(this.attachHandler.bind(this));

	},
    attachHandler: function(element) {
        element.on('click', this.setNavDockedCookieFalse.bind(this))
    },
    setNavDockedCookieFalse: function(){
        this.setNavDockedCookie('false');
    },
    setNavDockedCookie: function(string) {
        var c_value = "navdocked=" + string;
        document.cookie = c_value + ';path=/';


    }
});
Lazzo.RunSetCookieNav = function() {
	try {
		$$('*[data-widget~=set-cookie-nav]').each(function(element) {
			new Lazzo.SetCookieNav(element);
		});
	} catch (e) {
		Lazzo.catching.error('Lazzo.SetCookieNav', e);
	}
};





/*
 *
 * Navigation
 *
 *
 */

Lazzo.Navigation = Class.create(Lazzo.Mixin, {
	initialize: function(wrapper) {
		this.LEFT_OFFSET = 68;
        //this.vpdims = document.viewport.getDimensions();
		this.wrapper = wrapper;
		this.inRest = true;
		this.isHome = ($('container').hasClassName('index') && $('container').hasClassName('default'));
		this.handle(this.wrapper, ['touchstart','mouseenter','mouseleave']);
        Event.on(document.onresize ? document : window, "resize", this.handleResize.bind(this) );

        if (!this.isHome) {
            // wrapper must be docked. animate on page load.
            this.slideToDocked();
        }

	},
    handleResize:function(){
        //this.vpdims = document.viewport.getDimensions();
        this.initPosition();
    },
    initPosition: function(){
        if (!this.isHome) {
            this.wrapper.setStyle({left:this.getSlideX()+'px'});
        }
    },
	getSlideX: function() {
		var w = $('container').getWidth();
		return w - this.LEFT_OFFSET;
	},
	setInRest: function() {
        this.wrapper.select('#social-media-nav, #blog-nav, h1').invoke('show');
		this.inRest = true;
	},
    beforeStart: function(){
        this.wrapper.select('#social-media-nav, #blog-nav, h1').invoke('hide');
    },
    slideToDocked: function() {
        this.wrapper.setStyle({visibility:'visible'});

        if (Modernizr.csstransforms) {
            if (this.wrapper.readAttribute('data-navdocked') == 'true') {
                this.wrapper.setStyle({left:this.getSlideX()+'px'});
            } else {
                Element.setStyle.delay(0.8, this.wrapper, {left:this.getSlideX()+'px'})
            }
            return;
        }

        this.inRest = false;
		this.isHome = true;
		this.fx = new Effect.Move(this.wrapper, {
            delay:2,
            transition:
            Effect.Transitions.linear,
            duration:0.8,
            fps:75,
            x: this.getSlideX(),
            y: 0,
            mode: 'relative',
            afterSetup: this.beforeStart.bind(this),
            afterFinish:this.setInRest.bind(this)
        });
    },
	slide:function() {
        if (Modernizr.csstransforms) {
            if (this.isCssAnimating) {return;}
            this.wrapper.setStyle({left:0});
            this.isHome = true;
            return;
        }
		if (this.inRest && this.isHome) {
			this.inRest = false;
			this.isHome = false;
			this.fx = new Effect.Move(this.wrapper, {
                transition: Effect.Transitions.linear,
                duration:0.8,
                fps:75,
                x: -this.getSlideX(),
                y: 0,
                mode: 'relative',
                afterFinish:this.setInRest.bind(this)
           });
		}
	},
    handleTouchstart:function(){
        this.handleMouseenter();
    },
	handleMouseenter:function() {

		if (this.timer) {
			clearTimeout(this.timer);
		}

        if (Modernizr.csstransforms) {
            var left = this.wrapper.offsetLeft;
            this.timer = setTimeout( function(){ if (this.wrapper.offsetLeft == left) {this.slide()}  }.bind(this), 350);
            return;
        }

		if (this.inRest && !this.isHome) {
			this.timer = setTimeout( this.slide.bind(this), 350);
		}
	},
	handleMouseleave:function() {
		if (this.timer) {
			clearTimeout(this.timer);
		}
	}
});
Lazzo.RunNavigation = function() {
	try {
		$$('*[data-widget~=navigation]').each(function(element) {
			new Lazzo.Navigation(element);
		});
	} catch (e) {
		Lazzo.catching.error('Lazzo.Navigation', e);
	}
};






/*
 *
 * Paged
 *
 *
 */

Lazzo.Paged = Class.create(Lazzo.Mixin, {
	initialize: function(wrapper) {
        this.body = $(document.body);
		this.inRest = true;
		this.wrapper = wrapper;
        this.config = this.readConfig(this.wrapper, 'paged');
		this.content = this.wrapper.down('div');
		this.currentSheet = 1;
        this.calcNeededScale();
        this.setNumberOfPages();
		this.content.addClassName('initialized');
		if (this.numberOfPages > 1) {
			this.insertNavPoints();
        	this.insertNavArrows();
			this.attachDragHandler();
		}
	    this.windowResizeTimer();

	},
	attachDragHandler: function(){
	     if (!Prototype.Browser.IE) {
            // dragging disabled for now in IE. It conflicts with the pop up
		    var d = new Draggable(this.content, {constraint:'horizontal', onStart:this.onStart.bind(this), onEnd:this.onEnd.bind(this)});
        }
	},
    calcNeededScale: function(){
        if (this.config.scale == false) {
            this.scale = 1;
            return;
        }
		if (!Modernizr.csstransforms) {
			this.scale = 1;
			return;
		}
		var blogNavWidth = ($('blog-sub-nav'))? $('blog-sub-nav').offsetWidth:0;
		var blogLayoutHelperTop = ($('blog-layout-helper'))? $('blog-layout-helper').offsetTop:0;
		var availWidth = document.viewport.getDimensions().width - blogNavWidth - 150;
		var availHeight = document.viewport.getDimensions().height - blogLayoutHelperTop - 70;

		var contentWidth= 920;
		var contentHeight = 600;


		var contentRatio = contentHeight / contentWidth;
		var viewportRatio = availHeight / availWidth;
		if (contentRatio > viewportRatio) {
			this.scale = availHeight / contentHeight;
		} else {
			this.scale = availWidth / contentWidth;
		}

		this.wrapper.setStyle({WebkitTransform:'scale('+this.scale+')'});
		this.wrapper.setStyle({MozTransform:'scale('+this.scale+')'});
		if (this.wrapper.down('#addthis')) {
				this.wrapper.down('#addthis').setStyle({MozTransform:'scale('+1/this.scale+')'});
				this.wrapper.down('#addthis').setStyle({WebkitTransform:'scale('+1/this.scale+')'});
		}
		var f = function(){
			if (this.wrapper.down('.nav-points')) {
				this.wrapper.down('.nav-points').setStyle({MozTransform:'scale('+1/this.scale+')'});
				this.wrapper.down('.nav-points').setStyle({WebkitTransform:'scale('+1/this.scale+')'});
			}
		}.bind(this);
		f.delay(1);
    },
    setNumberOfPages: function() {
        var offsetWidth = this.content.offsetWidth;
		var hasClone = false;
		var oneRow, cellWidth, offsetwidthPadded, nrOfCells;

        // if quantized is on, insert a margin's every x cell's so that one cell will never be cutoff in the middle
        if (this.config.quantized == true) {
			oneRow = this.body.hasClassName('one-row');							// if set, only one row is shown on the first page
			cellWidth = 170;

            offsetwidthPadded = offsetWidth - (cellWidth + 68);     			// 68 is the right margin used by the navigation
            nrOfCells = Math.floor(offsetwidthPadded / cellWidth) - 1;			// number of cells per page

			this.content.select('.one-row-odd-dummy').invoke('remove');			// remove dummy element
			this.content.select('li').invoke('removeClassName', 'first-page');	// reset
			this.content.removeClassName('one-page');
			
			var onlyOnePage = true;
			if (oneRow) {
				this.content.select('li').each(function(element, i){			// set which cells are on the first page.
					if (i<((nrOfCells+1)/2)) {									//
						element.addClassName('first-page');
					} else {
						onlyOnePage = false;
					}
				});
				if (onlyOnePage) {												// if one page, or a cell is stretching over two pages,
					this.content.addClassName('one-page')						// the negative cell top margin is causing the cells to render too high
				}
				if(nrOfCells%2 == 0) {											// if odd, insert dummy cell to fill gap
					var cloneThis = this.content.down('li.first-page', (nrOfCells/2)-1).down('a');
					if (cloneThis) {
						var clone = cloneThis.clone(true);
						var lastCellFirstPage = this.content.down('li.first-page', nrOfCells/2);

						lastCellFirstPage.insert(clone);
						clone.addClassName('one-row-odd-dummy');

						// this clone cannot be used in number of pages calculation
						hasClone = true;
					}

				}
			}
            var remainder = offsetwidthPadded % cellWidth;
            remainder = remainder + cellWidth;

            var cells = this.content.select('li.first-page a:not(.one-row-odd-dummy), li:not(.first-page)');
            // make the 'gaps'
            cells.each( this._gapMaker.bind(this, nrOfCells, remainder) );

            // let's have the paragraph in this section also this right margin's!
            this.content.down('.p1').setStyle({marginLeft:(remainder/2)-34+'px', marginRight:(remainder/2)+90+'px'});
        }
		var scrollWidth = (hasClone)? this.content.scrollWidth-cellWidth:this.content.scrollWidth;

        this.numberOfPages = Math.ceil( scrollWidth / offsetWidth );
    },
	_removeGapMargins: function() {
		this.content.select('a, li').invoke('writeAttribute','style','').invoke('removeAttribute','marker');
	},
    _gapMaker: function(nrOfCells, remainder, cell, i) {

        var cellIsLeftMostOrRightMost = (i+1) % (nrOfCells+1);

        switch (cellIsLeftMostOrRightMost) {
            case 1:
				cell.setStyle({marginRight:'6px', marginLeft:(remainder/2)-34+'px'});       // make left gap
                cell.removeAttribute('marker');
                break;
            case 0:
                cell.setStyle({marginRight:(remainder/2)+'px', marginLeft:'0px'});          // make right gap
                cell.writeAttribute('marker', 'marker');
                break;
            default:
                cell.writeAttribute('style','');
                cell.removeAttribute('marker');
        }

    },
    reinitialize: function(){
        this.currentSheet = 1;
		this._removeGapMargins();
        this.calcNeededScale();
        this.content.removeClassName('initialized').setStyle({left:0});
        this.setNumberOfPages();
		if (this.numberOfPages > 1) {
        	this.insertNavPoints();
        	this.insertNavArrows();
		}
        this.content.addClassName('initialized');
    },
    windowResizeTimer: function(){
        var timer;
        var doFunction = this.reinitialize.bind(this);
        var f = function(){
            clearTimeout(timer);
            timer = setTimeout(doFunction, 400);
        };
        Event.on(document.onresize ? document : window, "resize", f );
    },
	getSlideX: function() {
        var w;
        if (this.config.quantized == true) {
            w = $('content').getWidth()-71;		// 68 + (6/2) = right margin used by navigation + cell margin/2
        } else {
            w = $('content').getWidth();
        }
		//return w * this.scale;
        return w;
	},
	handleNavPointsClick: function(evt) {
		var pos = (evt.pointerX() - this.navPoints.cumulativeOffset()[0]);
		if (pos < 640) {    //todo: make this variable.
			this.movePrevious();
		} else {
			this.moveNext();
		}
	},
    /*
    Drag action
     */
	onStart: function() {
		this.currentOffsetLeft = this.content.offsetLeft;
        this.navArrows.invoke('hide');
	},
    /*
    Drag action
     */
	onEnd: function() {
        this.broadcast('Paged.onEndDrag', {});
        var sheet;
		if (this.currentOffsetLeft > this.content.offsetLeft) {
			if ( this.currentSheet >= this.numberOfPages ) {
				sheet = this.currentSheet;
				this.fx = new Effect.Move(this.content, { duration:0.4, x: (this.numberOfPages - 1) * -this.getSlideX(), y: 0, mode: 'absolute', beforeStart:this.beforeStart.bind(this), afterFinish:this.afterFinish.bind(this, sheet) });
			} else {
				sheet = this.currentSheet + 1;
				this.fx = new Effect.Move(this.content, { duration:0.4, x: this.currentSheet * -this.getSlideX(), y: 0, mode: 'absolute', beforeStart:this.beforeStart.bind(this), afterFinish:this.afterFinish.bind(this, sheet) });
			}
		} else {
			if ( this.currentSheet <= 1) {
				sheet = this.currentSheet;
				this.fx = new Effect.Move(this.content, { duration:0.4, x:  0, y: 0, mode: 'absolute', beforeStart:this.beforeStart.bind(this), afterFinish:this.afterFinish.bind(this, sheet) });
			} else {
				sheet = this.currentSheet - 1;
				this.fx = new Effect.Move(this.content, { duration:0.4, x:  ( sheet - 1 ) * -this.getSlideX(), y: 0, mode: 'absolute', beforeStart:this.beforeStart.bind(this), afterFinish:this.afterFinish.bind(this, sheet) });
			}
		}
	},
    /*
    Effect 'move'
     */
	beforeStart: function() {
        this.navArrows.invoke('hide');
	},
    /*
    Effect 'move'
     */
	afterFinish: function(sheet) {
		this.setInRest();
        this.navArrows.invoke('show');
        if (sheet == 1) {
            this.navArrows[0].hide();
        }
        if (sheet == this.numberOfPages) {
            this.navArrows[1].hide();
        }
		this.currentSheet = sheet;
		this.navPoints.select('span').invoke('removeClassName', 'active');
		this.navPoints.down('span', sheet - 1).addClassName('active');
	},
	setInRest: function() {
		this.inRest = true;
	},
    insertNavArrows: function(){
        this.removeNavArrows();
        var left = new Element('div', {id:'nav-arrow-left'}).hide();
        var right = new Element('div', {id:'nav-arrow-right'}).hide();
        if (this.numberOfPages > 1) {
            right.show();
        }

		// position arrows relative to the content-block
		var oneRow = this.body.hasClassName('one-row');
		var firstCell = (oneRow)? this.content.down('a'):this.content.down('li');
		if (firstCell) {
			left.setStyle({left:firstCell.cumulativeOffset().left-18-47+'px'});
		}

        var firstMarker = this.content.down('li[marker], a[marker]');
        if (firstMarker) {
            right.setStyle({left:firstMarker.cumulativeOffset().left+208+'px'});
        }

        this.navArrows = [left, right];

        left.on('click', this.movePrevious.bind(this));
        right.on('click', this.moveNext.bind(this));

        var blogLayoutHelper = $('blog-layout-helper');
        if (blogLayoutHelper) {
            blogLayoutHelper.insert(right);
            blogLayoutHelper.insert(left);
        } else {
            this.wrapper.insert(right);
            this.wrapper.insert(left);
        }



    },
    removeNavArrows: function(){
        if (this.navArrows) {
            this.navArrows.invoke('remove');
        }
    },
	insertNavPoints: function() {
        this.removeNavPoints();
		var navPoints = new Element('div', {className:'nav-points'});
		var move = this.move.bind(this);
		$R(1, this.numberOfPages).each( function(i) {
			var p = new Element('span');
			navPoints.insert(p);
			p.on('click', move);
			p.store('sheet', i);
			if (i == 1) {
				p.addClassName('active');
			}
		});
		this.navPoints = navPoints;
		this.navPoints.on('click', this.handleNavPointsClick.bind(this));
		this.wrapper.insert( this.navPoints );
	},
    removeNavPoints: function() {
        if (this.navPoints) {
            this.navPoints.remove();
        }
    },
	move: function(evt) {
		evt.stop();
		if (this.inRest) {
			this.inRest = false;
			var element = evt.element();
			var sheet = element.retrieve('sheet');
			var steps = sheet - this.currentSheet;
			this.fx = new Effect.Move(this.content, { duration:0.4, x: steps * -this.getSlideX(), y: 0, mode: 'relative', beforeStart:this.beforeStart.bind(this), afterFinish:this.afterFinish.bind(this, sheet) });
		}
	},
	moveNext: function() {
		if (this.inRest && this.currentSheet < this.numberOfPages) {
			this.inRest = false;
			var sheet = this.currentSheet + 1;
			this.fx = new Effect.Move(this.content, { duration:0.4, x: -this.getSlideX(), y: 0, mode: 'relative', beforeStart:this.beforeStart.bind(this), afterFinish:this.afterFinish.bind(this, sheet) });
		}
	},
	movePrevious: function() {
		if (this.inRest && this.currentSheet > 1) {
			this.inRest = false;
			var sheet = this.currentSheet - 1;
			this.fx = new Effect.Move(this.content, { duration:0.4, x: this.getSlideX(), y: 0, mode: 'relative', beforeStart:this.beforeStart.bind(this), afterFinish:this.afterFinish.bind(this, sheet) });
		}
	}
});
Lazzo.RunPaged = function() {
	try {
		$$('*[data-widget~=paged]').each(function(element) {
			new Lazzo.Paged(element);
		});
	} catch (e) {
		Lazzo.catching.error('Lazzo.Paged', e);
	}
};











/*
 *
 * Popped
 *
 *
 */

Lazzo.Popped = Class.create(Lazzo.Mixin, {
	initialize: function(wrapper) {
		this.wrapper = wrapper;
		this.createPopupNode();
        this.attachHandlers();
        //this.checkDeepLink();

        this.resetAndListen('Paged.onEndDrag', this.cancelPopupTimer.bind(this));

	},
    // todo: after deep link, user clicks on another thumb. video section shouldn't pop up than.
    checkDeepLink: function(){
		if ($$('.video-js-box').size() > 0) {

        	this.videoSection.addClassName('fadein');

        	var height = this.videoInnerSection.getHeight();
        	this.videoInnerSection.setStyle({marginTop:-(height/2)+'px'});
        	this.videoSection.addClassName('active');

		}
    },
    popupAttachHandlers: function() {
        this.videoSection.on('click', this.removePopOnClick.bind(this));
		$(document).on('keydown', function(evt){
			if (evt.keyCode == Event.KEY_ESC) {
				this.removePop();
			}
		}.bind(this));
		this.videoSection.addClassName('handlers-attached')
    },
    createPopupNode: function() {
        // two ways how this node can already exist: ajax load or deep link
		var clone = null;
		if ($$('.video-js-box').size() > 0) {
			clone = $$('.video-js-box')[0].up().clone(true);
		}

		// remove already created ones.
		$$('#video-section').invoke('remove');

		// create new video section element
		this.videoSection = new Element('div', {id:'video-section'});
		if (clone) {
			this.videoInnerSection = clone.wrap( new Element('div') );
		} else {
			this.videoInnerSection = new Element('div');
		}
		this.videoSection.insert( this.videoInnerSection );
		$(document.body).insert( this.videoSection );

		this.popupAttachHandlers();
		this.insertCloseButton();

		if (clone) {
			this.videoSection.addClassName('fadein');
        	var height = this.videoInnerSection.getHeight();
        	this.videoInnerSection.setStyle({marginTop:-(height/2)+'px'});
        	this.videoSection.addClassName('active');

			setTimeout(function() {
				this.myPlayer = VideoJS.setup("clip", {
					controlsBelow: true,
					controlsHiding: false
				});
				this.videoSection.addClassName('show-video-player');
				try {this.myPlayer.play(); } catch (e) {};
			}.bind(this), 500);

		}

    },
    insertCloseButton: function() {
        this.closebutton = new Element('div', {className:'video-section-close-button'});
		this.videoInnerSection.insert( this.closebutton );
    },
	attachHandlers: function() {
		this.wrapper.on('click', function(e) {
            var element = e.element();
//            links with this className can be 'clicked'.
            if (!element.hasClassName('regular-event')) {
                e.stop();
            }
		});
		this.wrapper.on('mouseup', function(e) {
            this.setPopupTimer( e );
		}.bind(this));
        // todo: check this on iOs
		this.wrapper.on('touchend', function(e) {
            this.setPopupTimer( e );
        }.bind(this));
	},
    removePopOnClick: function(e){
		var element = e.element();
//        only remove if not clicked on the video itself
		if ((!element.descendantOf(this.videoInnerSection) && element != this.videoInnerSection) || element == this.closebutton ) {
            this.removePop();
        }
    },
	removePop: function() {
        this.videoSection.removeClassName('fadein');
        var videoSection = this.videoSection;
        (function() {videoSection.removeClassName('active');}).delay(0.75);
        this.videoSection.removeClassName('show-video-player');
        this.videoInnerSection.update('');
	},
    cancelPopupTimer: function(m){

        if (Prototype.Browser.IE) { return; }   // disabled for IE
        if (this.timer) {
            clearTimeout(this.timer);
        }

    },
    setPopupTimer: function(e){
        this.timer = setTimeout(this.handleClick.bind(this,e), 100);
    },
	handleClick: function(e) {
			var element = e.findElement('a.movie-thumb');
            if (typeof element != 'undefined' && element != document) {
                this.loadUrl( element.readAttribute('href') );
                this.videoSection.addClassName('fadein');
            }

	},
	loadUrl: function(href) {
		new Ajax.Request(href, {
			onSuccess: this.onSuccess.bind(this)
		})
	},
	onSuccess: function(t) {
		this.videoInnerSection.update( t.responseText );
		this.videoInnerSection.insert( this.closebutton );

        var height = this.videoInnerSection.getHeight();
        this.videoInnerSection.setStyle({marginTop:-(height/2)+'px'});
        this.videoSection.addClassName('active');

		setTimeout(function() {
			this.myPlayer = VideoJS.setup("clip", {
				controlsBelow: true,
				controlsHiding: false
			});
			addthis.toolbox($('addthis'), {ui_open_windows:true}, {description:'Ambassadors', templates: {twitter: '{{url}} #Ambassadors'}});
			this.videoSection.addClassName('show-video-player');
			try {this.myPlayer.play(); } catch (e) {};
		}.bind(this), 500);

	}
});
Lazzo.RunPopped = function() {
	try {
		$$('*[data-widget~=popped]').each(function(element) {
			new Lazzo.Popped(element);
		});
	} catch (e) {
		Lazzo.catching.error('Lazzo.Popped', e);
	}
};




/*
 *
 * FillScreenImage
 *
 *
 */

Lazzo.FillScreenImage = Class.create(Lazzo.Mixin, {
	initialize: function(image) {
        this.image = image;

        if (this.image.hasClassName('navigation-image')) {
            // dimensions of this image can be cached.
            if (this.image.readAttribute('width') == '100%') {
                // server does not know dimensions yet, hence 100%. Do the onload to resize.
                this.setOnload();
            }
        } else {
            // 'normal' image.
            this.setOnload();
        }

        // resize image when viewport changes
        Event.on(document.onresize ? document : window, "resize", this.resize.bind(this) );
	},
    setOnload: function(){
        if (this.image.getHeight()>0) {
                    this.resize();
                } else {
                    this.image.on('load', this.resize.bind(this));
                }

    },
    setImageDimensionsInCookie: function(width, height, top, left) {

		var c_value = "fillscreenimage=" + width + "x" + height + "x" + top + "x" + left;
		document.cookie = c_value + ';path=/';


    },
    resize: function() {

        /************************************************************
        This function resizes the background image so it always
        fills the screen.

        first set the width of the image to the width of the window
        and then check if the height is too small. If so zoom the
        whole image in.

        /************************************************************/
              var top, left;
			  var elem = this.image;
              var bgImgAspect = this.image.getWidth() / this.image.getHeight();

			  if (elem == undefined || elem == null) return false;

				var tmpWidth = 0;
				var tmpHeight = 0;

				// set width.
				tmpWidth = window.innerWidth;
				tmpHeight = Math.round(window.innerWidth / bgImgAspect);

				// set zoom if needed.
				if (tmpHeight < window.innerHeight) {
					tmpWidth = Math.round(tmpWidth * (window.innerHeight/tmpHeight));
					tmpHeight = Math.round(tmpHeight * (window.innerHeight/tmpHeight));
				}
                elem.setStyle({width:tmpWidth+'px', height:tmpHeight+'px'});

			  // center the image when needed
			  if (elem.getHeight() > window.innerHeight) {
			  	top = Math.round((elem.getHeight() - window.innerHeight)/-2);
			  } else {
			  	// reset
			  	top = 0;
			  }


			  if (elem.getWidth() > window.innerWidth) {
                  left = Math.round((elem.getWidth() - window.innerWidth)/-2);

			  } else {
			  	left = 0;

			  }
                elem.setStyle({top:top+'px', left:left+'px'});

               //elem.setStyle({visibility:'visible'});
                if (this.image.hasClassName('navigation-image')) {
                    this.setImageDimensionsInCookie(tmpWidth, tmpHeight, top, left);
                }

			}
});
Lazzo.runFillScreenImage = function() {
//    use css3 background size if possible
    if (Modernizr.backgroundsize) { return; }
	try {
		$$('*[data-widget~=fill-screen-image]').each(function(element) {
			new Lazzo.FillScreenImage(element);
		});
	} catch (e) {
		Lazzo.catching.error('Lazzo.FillScreenImage', e);
	}
};





/*
 *
 * Lazy Background
 *
 *
 */

Lazzo.LazyBackground = Class.create(Lazzo.Mixin, {
	initialize: function( wrapper ) {
        var batch = wrapper.select('span[data-lazy-background]');
        batch.each( function( span, i ){
           if (i<21) {
               span.setStyle({backgroundImage:'url("'+span.readAttribute('data-lazy-background')+'")'});
           }
        });
        (function(){
            batch.each( function( span, i ){
               if (i>20) {
                   span.setStyle({backgroundImage:'url("'+span.readAttribute('data-lazy-background')+'")'});
               }
            });
        }).delay(2);
	}
});
Lazzo.runLazyBackground = function() {
	try {
		$$('*[data-widget~=lazy-background]').each(function(element) {
			new Lazzo.LazyBackground(element);
		});
	} catch (e) {
		Lazzo.catching.error('LazyBackground', e);
	}
};












/*
 *
 * SubnavHover
 *
 *
 */

Lazzo.ScaleFont = Class.create(Lazzo.Mixin, {
	initialize: function( element ) {
        this.MIN_ALLOWED_HEIGHT = 80;
		this.element = element;
        this.resizeTimed();
        Event.on(document.onresize ? document : window, "resize", this.resizeTimed.bind(this) );
	},
    resizeTimed: function(){
      if (this.timer)
        clearTimeout(this.timer);
      this.timer = setTimeout(this.resize.bind(this), 333);
    },
    resize: function() {
        this.element.setStyle({fontSize:'1.1em'}).show();
        if (this.heightIsAllowed()) {
            return;
            //this.element.setStyle({fontSize:'1.1em'}).show();
        }
        if (!this.heightIsAllowed()) {
            this.element.setStyle({fontSize:'1em'});
        }
        if (!this.heightIsAllowed()) {
            this.element.setStyle({fontSize:'0.95em'});
        }
        if (!this.heightIsAllowed()) {
            this.element.setStyle({fontSize:'0.85em'});
        }
        if (!this.heightIsAllowed()) {
            this.element.hide();
        }
    },
    heightIsAllowed: function(){
        var bottom = this.element.cumulativeOffset().top + this.element.offsetHeight;
        var vpheight = document.viewport.getDimensions().height;
        return (vpheight - bottom) > this.MIN_ALLOWED_HEIGHT;
    }
});
Lazzo.runScaleFont = function() {
	try {
		$$('*[data-widget~=scale-font]').each(function(element) {
			new Lazzo.ScaleFont(element);
		});
	} catch (e) {
		Lazzo.catching.error('ScaleFont', e);
	}
};




Lazzo.SetNumberOfRows = Class.create(Lazzo.Mixin, {
	initialize: function( element ) {
		this.element = element;
        this.check();
        Event.on(document.onresize ? document : window, "resize", this.checkTimed.bind(this) );
	},
    checkTimed: function(){
      if (this.timer)
        clearTimeout(this.timer);
      this.timer = setTimeout(this.check.bind(this), 100);
    },
    check: function() {
        var h = document.viewport.getDimensions().height;
		if (h < 800) {
			$(document.body).addClassName('one-row');
		} else {
			$(document.body).removeClassName('one-row');
		}
    }
});
Lazzo.runSetNumberOfRows = function() {
	try {
		$$('*[data-widget~=set-number-of-rows]').each(function(element) {
			new Lazzo.SetNumberOfRows(element);
		});
	} catch (e) {
		Lazzo.catching.error('SetNumberOfRows', e);
	}
};





/*

RecentPostsPaged
 */


Lazzo.RecentPostsPaged = Class.create(Lazzo.Mixin, {
	initialize: function( element ) {
		this.element = element;
		this.element.addClassName('active');
		this.firstLi = this.element.down('li');
		if (this.firstLi && (this.element.scrollHeight != this.element.offsetHeight)) {
			this.doNotRespond = false;
			this.marginTop = 0;
			if (sessionStorage && sessionStorage.getItem('recent-posts-paged')) {

				this.marginTop = parseFloat(sessionStorage.getItem('recent-posts-paged'));
				this.firstLi.setStyle({marginTop:this.marginTop+'px'});
			}
			this.createInterface();
			Event.on(document.onresize ? document : window, "resize", this.clearSession.bind(this) );
		}
	},
	clearSession: function(){
		sessionStorage.clear('recent-posts-paged')
	},
	setTimer: function(){
		this.doNotRespond = true;
		setTimeout( function(){
			if (this.element.scrollHeight == this.element.offsetHeight) {
				this.next.hide();
			} else {
				this.next.show();
			}
			this.doNotRespond = false;
		}.bind(this), 500);
	},
	createInterface: function(){
		this.next = new Element('div').update('next');
		if (this.element.scrollHeight == 0) {
			this.next.hide();
		}
		this.element.insert({after:this.next});
		this.next.on('click', this.doNext.bind(this));

		this.previous = new Element('div').update('previous').hide();
		if (this.marginTop != 0) {
			this.previous.show();
		}
		this.element.insert({after:this.previous});
		this.previous.on('click', this.doPrevious.bind(this));
	},
	doPrevious: function() {
		if (this.doNotRespond) { return; }
		this.setTimer();
		var newMarginTop = this.marginTop + this.element.offsetHeight;
		if (newMarginTop>=0) {
			this.previous.hide();
		}
		this.marginTop = newMarginTop;
		this.firstLi.setStyle({marginTop:this.marginTop+'px'});

		if (sessionStorage) {
			sessionStorage.setItem('recent-posts-paged', this.marginTop);
		}

	},
	doNext: function() {
		if (this.doNotRespond) { return; }
		this.setTimer();
		if (this.element.scrollHeight == 0) {
			this.next.hide();
		}
		this.previous.show();
		this.marginTop -= this.element.offsetHeight;
		this.firstLi.setStyle({marginTop:this.marginTop+'px'});

		if (sessionStorage) {
			sessionStorage.setItem('recent-posts-paged', this.marginTop);
		}
	}
});
Lazzo.runRecentPostsPaged = function() {
	try {
		$$('*[data-widget~=recent-posts-paged]').each(function(element) {
			new Lazzo.RecentPostsPaged(element);
		});
	} catch (e) {
		Lazzo.catching.error('RecentPostsPaged', e);
	}
};











