if (!console) {
    var console = {
        'log': function () { },
        'debug': function(){}
    }
}
var Default = {},
	Nescafe = {},
	detection, overlay, ie = Browser.ie,
	
    compInstance = null,
    compSliderInstance = null;

var machineCookie =  new Hash.Cookie('machineCookie', {path: '/'});

window.addEvent('domready', function () {
    if (machineCookie != null) {
        machineCookie.each(function (val, key) {
            if ($(key) != null) {
                if ($(key).type == 'checkbox' || $(key).type == 'radio') {
                    $(key).set('checked', val);
                }
                else {
                    $(key).value = val;
                }
            }
        });
    }

//    Default.BaseUrl = $(document.head).getElement('base') ?
//		$(document.head).getElement('base').get('href') : document.location.href.replace(document.location.hash, '');

    Default.Pseudos('#footer .footer ul li a', 'before');
    Default.Pseudos('a.btn-default');
    Default.Pseudos('a.btn-rect-stripes', 'after');
    Default.Placeholder();
    new Default.Checkbox;
    Default.noTab($$('input.no-tab'));

    detection = new Nescafe.Detection({
        elms: {
            photo: $$('.photo-holder')[0],
            wrapper: document.id('wrapper'),
            content: document.id('content'),
            footer: document.id('footer'),
            search: document.id('search')
        }
    });

    var sliderElm = $('slider');
    if (sliderElm) {
        new Nescafe.FullpageSlider({
            wrapper: sliderElm,
            items: sliderElm.getElements('ul.items li.item'),
            buttons: sliderElm.getElements('ul.buttons li a')
        });
    }

    overlay = new Nescafe.Overlay;

    Nescafe.SelectorSlider($$('form.productselector div.slider')[0], 1.2);
    compInstance = new Nescafe.Compare({
        form: $$('form.productselector')[0]
    });

    // Add Active Label Class on Active Checkboxes
    $$('form.productselector fieldset.selector div.choices input[type=checkbox]').each(function (inp, i) {
        inp.addEvent('change', function () {
            if (inp.get('checked')) {
                inp.getNext('label').addClass('active');
            } else {
                inp.getNext('label').removeClass('active');
            }
        }).fireEvent('change');
    });

    var tabWrapper = $$('.section.machine-detail')[0];
    if (tabWrapper) {
        new Nescafe.Tabs({
            buttons: tabWrapper.getElements('.tab-buttons li a'),
            content: tabWrapper.getElements('.tab-content')
        });
    }

    var ingredientTabs = $$('.section.page-ingredients')[0];
    if (ingredientTabs) {
        new Nescafe.Tabs({
            buttons: ingredientTabs.getElements('.header ul.buttons li a.btn-tab'),
            content: ingredientTabs.getElements('.tab-content'),
            hashChange: true,
            innerPager: true
        });
    }

    if ($$('div.show-popup').length > 0) {
        new Nescafe.Popup({ elements: $$('div.show-popup') });
    }

    if ($$('.textpage > .block').length > 0) {
        new Nescafe.TextPages({
            wrapper: $$('.textpage')[0],
            blocks: $$('.textpage > .block'),
            buttons: '.nav ul li a'
        });
    }

    var contactForm = $('form');
    if (contactForm) {
        new Nescafe.ContactForm({
            wrapper: contactForm,
            steps: contactForm.getElements('form > .section')
        });
    }

    var search = $('search');
    if (search) {
        new Nescafe.Search({
            wrapper: search,
            input: search.getElement('form input[type=text]'),
            result: search.getElement('.article.result')
        });
    }

    var faqs = $$('.article.faqs')[0];
    if (faqs) {
        new Nescafe.Tabs({
            buttons: faqs.getElements('.nav ul li a'),
            content: faqs.getElements('ol li')
        });
    }

    var references = $$('.section.referenties')[0];
    if (references) {
        new Nescafe.References({
            wrapper: references,
            buttons: references.getElements('ul.buttons li a'),
            items: references.getElements('ol li')
        });
    }

    var machinePageWrapper = $$('body.machines .section.products');
    if (machinePageWrapper[0]) {
        new Nescafe.MachinePager({
            machineLists: machinePageWrapper[0].getElements('.article.main ul.overview'),
            buttons: machinePageWrapper[0].getElements('.header ul.buttons a.prevPage, .header ul.buttons a.nextPage')
        });
    }

    var accesoireWrapper = $$('.page-accessoiry')[0];
    if (accesoireWrapper) {
        new Nescafe.MachinePager({
            machineLists: accesoireWrapper.getElements('.article.main ul.overview'),
            buttons: accesoireWrapper.getElements('.header ul.pager a.prevPage, .header ul.pager a.nextPage')
        });
    }
	$$('.open-conditions').addEvent('click', function () {
		$('action-conditions').fade('in');
    });
	$$('.close-conditions').addEvent('click', function () {
		$('action-conditions').fade('out');
    });
});


// Detection Check and Set HTML Classes
Nescafe.Detection = new Class({
	options: {
		sizes: {
			x: 0, y: 0,
			footer: 0,
			content: 0,
			photoMinWidth: null
		},
		elms: {
			wrapper: null,
			photo: null,
			content: null,
			footer: null,
			search: null
		},
		defaultClass: ''
	},
	Implements: Options,
	initialize: function(options){
		this.setOptions(options);
		
		this.setSizes();
		this.setDefaultClass();
		this.addWindowEvent();
	},
	setSizes: function(){
		this.options.sizes.photoMinWidth = this.options.elms.photo.getStyle('minWidth').toInt();
		this.options.sizes.footer = this.options.elms.footer.getSize().y;
		this.options.sizes.content = this.options.elms.content.getSize().y.toInt();
	},
	addWindowEvent: function(){
		window.addEvent('resize', function(){
			var size = $(document.body).getSize();
			this.options.sizes.x = size.x;
			this.options.sizes.y = size.y;
			this.setHtmlClass();
			this.setContentHeight();
			this.setPhotoWidth();
			this.setSearchPos();
		}.bind(this)).fireEvent('resize');
	},
	setDefaultClass: function(){
		if (ie){
			this.options.defaultClass = 'ie';
			if (Browser.ie6){ this.options.defaultClass += ' ie6'; }
			else if (Browser.ie7){ this.options.defaultClass += ' ie7'; }
			else if (Browser.ie8){ this.options.defaultClass += ' ie8'; }
		}
	},
	setHtmlClass: function(){
		var htmlTag = $(document.html);
		
		// @todo Set HTML Class depending on resolution
	
		htmlTag.set('class', this.options.defaultClass);
	},
	setContentHeight: function(){
		var height = this.options.sizes.y.toInt() - this.options.sizes.footer.toInt();
		var paddingSize = this.options.elms.photo.getElement('.border').getStyle('paddingTop').toInt() + this.options.elms.photo.getElement('.border').getStyle('paddingBottom').toInt();
		
		//console.log((height - paddingSize), height, paddingSize, this.options.sizes.content);
		
		if ((height - paddingSize) > this.options.sizes.content){
			this.options.elms.photo.setStyle('height', height);
			this.options.elms.wrapper.setStyle('height', height);
			this.options.elms.photo.getElement('.border').setStyle('height', height - paddingSize);
		}
		else {
			this.options.elms.photo.setStyle('height', this.options.sizes.content + paddingSize - 3);
			this.options.elms.wrapper.setStyle('height', this.options.sizes.content + paddingSize - 3);
			this.options.elms.photo.getElement('.border').setStyle('height', this.options.sizes.content - 3);
		}
		
		if (this.options.elms.photo.getElement('.photo img')){
			if (this.options.sizes.photoMinWidth > this.options.sizes.x.toInt()){
				this.options.elms.photo.getElement('.photo img').setStyle('width', this.options.sizes.photoMinWidth);
			} else {
				this.options.elms.photo.getElement('.photo img').setStyle('width', this.options.sizes.x);
			}
		}
		//this.options.elms.photo.setStyle('width', this.options.sizes.y.toInt());
	},
	getContentHeight: function(){
		var contentHeight = this.options.elms.photo.getStyle('height').toInt();
		var minHeight = this.options.elms.wrapper.getStyle('min-height').toInt();
		if (contentHeight < minHeight){
			return minHeight - 50;
		}
		return contentHeight - 50;
	},
	setContentHeightAuto: function(){
		this.options.elms.photo.setStyle('height', 'auto');
		this.options.elms.wrapper.setStyle('height', 'auto');
		this.options.elms.photo.getElement('.border').setStyle('height', 'auto');
	},
	setPhotoWidth: function(){
		if (this.options.sizes.photoMinWidth > this.options.sizes.x.toInt()){
			this.options.elms.photo.setStyle('width', this.options.sizes.photoMinWidth);
		} else {
			this.options.elms.photo.setStyle('width', '100%');
		}
	},
	setSearchPos: function(){
		if (this.options.sizes.x.toInt() < this.options.sizes.photoMinWidth){
			var leftPos = this.options.sizes.photoMinWidth - 205;
			if (this.options.elms.search.hasClass('active')){
				leftPos = this.options.sizes.photoMinWidth - 365;
			}
			this.options.elms.search.setStyles({
				'right': 'auto',
				'left': leftPos
			});
		} else {
			this.options.elms.search.setStyles({
				'right': 25,
				'left': 'auto'
			});
		}
	},
	recalc: function(){
		this.setContentHeightAuto();
		this.setSizes();
		window.fireEvent('resize');
	}
});

// Nescafe Search
Nescafe.Search = new Class({
    options: {
        wrapper: null,
        input: null,
        result: null,
        request: null,
        open: false,
        lastValue: '',
        lastQuery: null,
        scrollbar: null
    },
    Implements: Options,
    initialize: function (options) {
        this.setOptions(options);

        this.setRequest();
        this.addEvents();
    },
    addEvents: function () {
        window.addEvent('resize', function () {
            if (this.options.open) {
                var height = this.setHeight();
                this.options.result.setStyle('height', height - 80);
                //this.options.scrollbar.resetHeight(height);
            }
        } .bind(this));

        this.options.wrapper.getElement('a.close').addEvent('click', function (e) {
            e.stop();
            this.hide();
        } .bind(this));
        this.options.wrapper.getElement('form').addEvent('submit', function (e) { e.stop(); });

        this.options.wrapper.getElement('form button').addEvent('click', function (e) {
            e.stop();
            if (!this.options.open && this.options.result.getElement('.item')) {
                this.show()
            }
        } .bind(this));

        this.options.input.addEvents({
            keydown: function (e) { } .bind(this),
            keyup: function (e) {
                this.setValue();
            } .bind(this),
            focus: function () {
                /* if (this.options.result.getElement('.item')){
                this.show()
                } */
            } .bind(this)
        });

        //this.options.scrollbar = new Default.Scrollbar({ content: this.options.result });
    },
    setRequest: function () {
        this.options.request = new Request.JSON({
            url: '/api/search',
            method: 'post',
			onRequest: function() {
				this.setLoading();
			}.bind(this),
            onComplete: function (json) {
                if (json.Count.toInt() > 0) {
                    this.options.lastQuery = json.Query;
                    (function(){
						this.setResult(json);
					}).delay(1000, this);
                }
                else {
                    this.setEmptyResult();
                }
            } .bind(this)
        });
    },
    setHeight: function (type) {
        if (typeof type == 'undefined') { type = 'full'; }
        if (type == 'full') {
            var fullHeight = detection.getContentHeight();
        }
        switch (type) {
            case 'full': this.options.wrapper.setStyle('height', fullHeight); break;
            case 'normal': this.options.wrapper.setStyle('height', 40); break;
        }
        return type == 'full' ? fullHeight : 40;
    },
    setValue: function () {
        var value = this.options.input.get('value');
        if (value.length < 1) {
            this.empty();
            this.hide();
            this.options.lastValue = value;
            return false;
        }
        if (value != this.options.lastValue) {
            this.options.lastValue = value;
			
			var delayFunc = function(val){
				(function(){
					if(val == this.options.input.get('value')){
						this.options.lastValue = val;
						//console.log(val, this.options.input.get('value'));
						this.getResults();
						this.show();
					}
				}).delay(300, this);
			}.bind(this)
			
			delayFunc(value);
            
        }
    },
    show: function () {
        if (this.options.open) { return false; }
        this.setHeight();
        this.options.wrapper.addClass('active');
        detection.setSearchPos();

        this.options.open = true;
    },
    hide: function () {
        this.setHeight('normal');
        this.options.wrapper.removeClass('active');
        detection.setSearchPos();

        this.options.open = false;
    },
    empty: function () {
        this.options.result.empty();
    },
    getResults: function () {
        this.options.request.post({ 'query': this.options.lastValue });
    },
    setResult: function (json) {
        this.empty();
        json.Result.each(function (result, i) {
            var wrapper = new Element('div', { 'class': 'item' }).inject(this.options.result);
            var ahref = new Element('a', { 'href' : result.Url }).inject(wrapper);
            new Element('h3', { 'html': result.Title }).inject(ahref);
            new Element('p', { 'html': result.Content }).inject(ahref);
        } .bind(this));

        this.initResults(json.query);
    },
    setEmptyResult: function () {
        this.empty();
        var wrapper = new Element('div', { 'class': 'item' }).inject(this.options.result);
        new Element('h3', { 'html': 'Geen resultaten' }).inject(wrapper);
        new Element('p', { 'html': 'Er zijn geen resultaten gevonden die aan uw zoekopdracht voldoen. Probeer een andere zoekterm.' }).inject(wrapper);
    },
	setLoading: function () {
        this.empty();
        var wrapper = new Element('div', { 'class': 'item' }).inject(this.options.result);
        new Element('img', { 'src': 'inc/image/loading.gif', 'alt': 'Bezig met laden', 'styles': { 'padding-top': 3 } }).inject(wrapper);
        new Element('span', { 'html': 'Bezig met zoeken...', 'styles': { 'padding-left': 5, 'line-height': '12px' } }).inject(wrapper);
    },
    initResults: function (keywords) {
        this.findKeyWords(keywords);

        window.fireEvent('resize');
        //this.options.scrollbar.reinitialize();
    },
    findKeyWords: function (keywords) {
        /*
        var splittedWords = keywords.split(' ');
        splittedWords.each(function(word, i){
			
        }.bind(this));
        */
    }
});

// ContactForm in 2 Steps with Slider
Nescafe.ContactForm = new Class({
	options: {
		wrapper: null,
		steps: null,
		active: 0,
		total: 0
	},
	Implements: Options,
	initialize: function(options){
		this.setOptions(options);
		this.options.total = this.options.steps.length;
		
		this.options.wrapper.getElement('form').set('tween', { duration: 300, transition: Fx.Transitions.Sine.easeOut });
		this.addEvents();
	},
	addEvents: function(){
		this.options.steps.each(function(step, i){
			step._validator = new Form.Validator(step);

			step._validator.add('validate-NL-postcode', {
			    test: function (field) {
			        return field.get('value').test(/^[1-9][0-9]{3}\s?[a-zA-Z]{2}$/);
			    }
			});

            step._validator.add('validate-empty-space', {
			    test: function (field) {
                    return field.get('value').replace(/^\s+/,"").length > 0;
			    }
			});

            step._validator.add('validate-max-50char', {
			    test: function (field) {
                    return field.get('value').length <= 50;
			    }
			});

            step._validator.add('validate-max-75char', {
			    test: function (field) {
                    return field.get('value').length <= 75;
			    }
			});

            step._validator.add('validate-max-100char', {
			    test: function (field) {
                    return field.get('value').length <= 100;
			    }
			});

            step._validator.add('validate-custom-phone', {
			    test: function (field) {
			        return field.get('value').test(/^\+?\(?\d?\)?( ?\d[- ().]*){7,21}$/);
			    }
			});

            step._validator.add('validate-empty-ordigits', {
			    test: function (field) {
			        return field.get('value').test(/^[ ]*?(\d{0,})?$/);
			    }
			});

			step._validator.add('validate-custom-email', {
			    test: function (field) {
			        return field.get('value').test(/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/);
			    }
			});


            step.getElement('button[type=submit]').addEvent('click', function(e){
				e.stop();
				if (this.validate()){ this.next(); }
			}.bind(this));
			step.getElements('a.btn-back').addEvent('click', function(e){
				e.stop();
				this.prev();
			}.bind(this));
		}.bind(this));
	},
	prev: function(){
		--this.options.active;
		if (this.options.active < 0){
			this.options.active = 0;
			return false;
		}
		this.slide();
	},
	next: function(){
		//if (!this.validate()){ return false; }
		++this.options.active;
		if (this.options.total - this.options.active < 1){
			this.options.active = this.options.total - 1; 
			this.submit();
			return false;
		}
		this.slide();
	},
	slide: function(){
		this.options.wrapper.getElement('form').tween('margin-left', -(this.options.active * 450));
	},
	validate: function(){
		return this.options.steps[this.options.active]._validator.validate();
	},
	submit: function(){
		this.options.wrapper.getElement('form').submit();
	}
});

// TextPages Slider
Nescafe.TextPages = new Class({
	options: {
		active: 0,
		next: 0,
		total: 0,
		wrapper: null,
		blocks: null,
		buttons: null,
		maxHeight: 0,
		changeBg: false
	},
	Implements: Options,
	initialize: function(options){
		this.setOptions(options);
		this.options.total = this.options.blocks.length;
		
		if (this.options.wrapper.hasClass('bgChange')){ this.options.changeBg = true; }
		
		this.setBlocks();
		this.addEvents();
		
        if(document.location.hash.length > 0){
		    var next = this.options.next;
            var hash = document.location.hash.substr(1, document.location.hash.length - 1);
		    this.options.blocks.each(function(block, i){
			    if (block.get('rel') == hash){
				    this.options.next = i;
			    }
		    }.bind(this));
		    if (this.options.next != next){ this.activate('next'); }
        }
	},
	setBlocks: function(){
		this.options.blocks.each(function(block, i){
			block.set('morph', { duration: 300 });			
			block.measure(function(){
				if (block.getSize().y.toInt() + 70 > this.options.maxHeight){
					this.options.maxHeight = block.getSize().y.toInt() + 70;
				}
			}.bind(this));		
		}.bind(this));
		this.options.wrapper.setStyle('height', this.options.maxHeight);
	},
	addEvents: function(){
		this.options.blocks.each(function(block, key){
			block.getElements(this.options.buttons).each(function(btn, i){
				btn.addEvent('click', function(e){
					e.stop();
					if (!btn.hasClass('inactive')){
						if (btn.hasClass('arrow-left')){
							this.prev();
						}
						else if(btn.hasClass('arrow-right')){
							this.next();
						}
                        Default.GA._trackPageview(btn.get('href'));
						var href = btn.get('href').split('#');
						if (href[1]){
							document.location.hash = href[1];
						}
					}
				}.bind(this));
			}.bind(this));
		}.bind(this));
	},
	prev: function(){
		--this.options.next;
		if (this.options.next < 0){
			this.options.next = 0; return false;
		}
		this.activate('prev');
	},
	next: function(){
		++this.options.next;
		if (this.options.total - this.options.next < 1){
			this.options.next = this.options.total - 1; return false;
		}
		this.activate('next');
	},
	activate: function(type){
		this.hide(this.options.active, type);
		this.show(this.options.next, type);
		
		if (this.options.changeBg){
			this.changeBg(this.options.next);
		}
		
		this.options.active = this.options.next;
	},
	hide: function(key, type){
		var to = (type == 'next' ? -550 : 300);
		if(!ie){
			this.options.blocks[key].morph({
				'margin-left': to,
				'opacity': 0
			});
		}
		else {
			this.options.blocks[key].setStyles({
				'margin-left': to,
				'opacity': 0
			});
		}
	},
	show: function(key, type){
		var from = (type == 'next' ? 550 : -550);
		var elm = this.options.blocks[key].setStyles({
			'display': 'block',
			'opacity': 0,
			'margin-left': from
		});
		
		if (!ie){
			this.options.blocks[key].morph({
				'margin-left': 50,
				'opacity': 1
			});
		}
		else {
			this.options.blocks[key].setStyles({
				'margin-left': 50,
				'opacity': 1
			});
		}
		
		var currentSize = this.options.wrapper.getStyle('height').toInt();
		var nextSize = this.options.blocks[this.options.next].getSize().y.toInt() + 70;
		if (currentSize < nextSize){
			this.options.wrapper.setStyle('height', this.options.blocks[this.options.next].getSize().y.toInt() + 70);
			detection.recalc();
		} else {
			(function(){
				this.options.wrapper.setStyle('height', this.options.blocks[key].getSize().y.toInt() + 70);
				detection.recalc();
			}).delay(300, this);
		}
	},
	changeBg: function(item){
		var src = this.options.blocks[this.options.next].getElement('img.bg').get('src');
		$$('.photo-holder > img.bgImage')[0].set('src', src);
		$$('.photo-holder .border .photo img.bgImage')[0].set('src', src);
	}
});

// References Slider
Nescafe.References = new Class({
	options: {
		stepSize: 520,
		wrapper: null,
		buttons: null,
		items: null,
		active: 0,
		next: 0,
		total: 0
	},
	Implements: Options,
	initialize: function(options){
		this.setOptions(options);
		this.options.total = this.options.items.length;
		this.addEvents();
		
		this.checkButtons();
	},
	addEvents: function(){
		this.options.buttons.each(function(btn, i){
			btn.addEvent('click', function(e){
				e.stop();
				if (btn.getParent().hasClass('prev')){
					this.prev();
				}
				else if (btn.getParent().hasClass('next')){
					this.next();
				}
			}.bind(this));
		}.bind(this));
	},
	prev: function(){
		--this.options.next;
		if (this.options.next < 0){
			this.options.next = 0;
			return false;
		}
		this.slide('prev');
	},
	next: function(){
		++this.options.next;
		if (this.options.total - this.options.next < 1){
			this.options.next = this.options.total - 1;
			return false;
		}
		this.slide('next');
	},
	slide: function(type){
		this.slideIn(type);
		this.slideOut(type);
		
		this.options.active = this.options.next;
		this.checkButtons();
	},
	slideIn: function(type){
		var from = (type == 'next' ? this.options.stepSize : -this.options.stepSize);
		this.options.items[this.options.next].tween('left', [from, 0]);
	},
	slideOut: function(type){
		var to = (type == 'next' ? -this.options.stepSize : this.options.stepSize);
		this.options.items[this.options.active].tween('left', to);
	},
	checkButtons: function(){
		if (this.options.active == 0){
			this.options.buttons[0].tween('opacity', .4);
		}
		else {
			this.options.buttons[0].tween('opacity', 1);
		}
		if (this.options.active >= this.options.total -1){
			this.options.buttons[1].tween('opacity', .4);
		}
		else {
			this.options.buttons[1].tween('opacity', 1);
		}
	}
});

// Slider on Homepage
Nescafe.FullpageSlider = new Class({
	options: {
		wrapper: null,
		buttons: null,
		items: null,
		total: 0,
		active: 0,
		next: 0,
		sliding: false
	},
	Implements: Options,
	initialize: function(options){
		this.setOptions(options);
		this.options.total = this.options.items.length;
        if(this.options.total < 2)
        {
            this.options.buttons.each(function(button, i){
                button.setStyles({ 'display' : 'none' });
            });
            return;
        }
		this.initActive();
		this.addEvents();
		this.newImage('show');
	},
	initActive: function(){
		this.options.items.each(function(item, i){
			if (i != this.options.active){
				if (!ie){
					item.setStyles({ 'z-index': 1, 'opacity': 0 });
				}
				else {
					item.setStyles({ 'display': 'none' });
				}
			}
			item.set('morph', {
				duration: 450,
				transition: Fx.Transitions.Sine.easeOut,
				link: 'cancel'
			})
		}.bind(this));
	},
	addEvents: function(){
		window.addEvent('resize', function(){
			this.options.items.setStyles({ 'right': 'auto', 'width': detection.options.sizes.x.toInt() - 50 });
			$$('.fullContentHeight').setStyle('height', detection.options.elms.photo.getElement('.border').getSize().y.toInt() - 50);
		}.bind(this)).fireEvent('resize');
		
		this.options.buttons.each(function(button, i){
			button.addEvent('click', function(e){
				if (e){ e.stop(); }
				if (this.options.sliding){ return false; }
				var li = button.getParent('li');
				if (li.hasClass('prev')){ this.prev(); }
				else if (li.hasClass('next')){ this.next(); }
				return false;
			}.bind(this));
		}.bind(this));
	},
	prev: function(){
		--this.options.next;
		if (this.options.next < 0){
			this.options.next = this.options.total - 1;
		}
		this.activate('prev');
	},
	next: function(){
		++this.options.next;
		if (this.options.total - this.options.next < 1){
			this.options.next = 0;
		}
		this.activate('next');
	},
	activate: function(direction){
		this.options.sliding = true;
		var a = this.options.active;	
		(function(){
			this.hide(this.options.items[a], direction);
		}).delay(75, this);
		this.show(this.options.items[this.options.next], direction);
		
		this.options.active = this.options.next;
	},
	show: function(item, direction){
		var from = (direction == 'next' ? detection.options.sizes.x.toInt() / 2 : -(detection.options.sizes.x.toInt() / 2))
		item.setStyle('z-index', 2);
		if (!ie){
			item.morph({
				'opacity': 1,
				'left': [from, 0]
			});
		} else {
			item.setStyles({
				'left': from,
				'display': 'block'
			});
			item.morph({
				'left': [from, 0]
			});
		}
		this.newImage();
	},
	hide: function(item, direction){
		var to = (direction == 'next' ? -(detection.options.sizes.x.toInt() / 2) : detection.options.sizes.x.toInt() / 2)
		item.setStyle('z-index', 1);
		if (!ie){
			item.morph({
				'opacity': 0,
				'left': to
			});
		}
		else {
			item.setStyles({
				'display': 'none'
			});
		}
	},
	newImage: function(tween){
		var img = this.options.items[this.options.next].getElement('img.bg');
		var options = img.get('rel').split('::');
		
		var bg = new Element('div', {
			'class': 'newImage',
			'styles': {
				'backgroundImage': 'url(' + img.get('src') + ')',
				'backgroundPosition': options[0]
			}
		}).inject($$('.photo-holder')[0], 'top').set('tween', { duration: 600, link: 'cancel' });
		if (options[1]){ bg.setStyle('backgroundColor', options[1]) }
		
		var fg = new Element('div', {
			'class': 'newPhoto',
			'styles': {
				'backgroundImage': 'url(' + img.get('src') + ')',
				'backgroundPosition': this.getBgPosition(options[0])
			}
		}).inject($$('.photo-holder .border')[0]).set('tween', {
			duration: 600, 
			link: 'cancel',
			onComplete: function(){
				this.resetImage(bg, fg);
			}.bind(this)
		});
		if (!tween){ 
			bg.setStyle('opacity', 0); 
			fg.setStyle('opacity', 0); 
		}
		if (options[1]){ fg.setStyle('backgroundColor', options[1]) }
		
		if (!tween){
			bg.fade(1);
			fg.fade(1);
		}
		else {
			this.resetImage(bg, fg);
		}
	},
	resetImage: function(bg, fg){
		this.options.sliding = false;
		
		var bgSel = $$('.photo-holder .newImage');
		$$('.photo-holder')[0].setStyles(bg.getStyles('backgroundImage', 'backgroundPosition', 'backgroundColor'));
		bgSel.dispose();
		
		var fgSel = $$('.photo-holder .newPhoto');
		$$('.photo-holder .border .photo')[0].setStyles(fg.getStyles('backgroundImage', 'backgroundPosition', 'backgroundColor'));
		fgSel.dispose();
	},
	getBgPosition: function(pos){
		switch (pos){
			case 'top left': { return '-25px -25px'; break; }
			case 'center center': { return pos; break; }
		}
	}
});

// Overlayer for Video's & Slideshow
Nescafe.Overlay = new Class({
	options: {
		mask: null,
		overlay: null,
		content: null,
		close: null,
		linkSelector: 'a[rel=overlay]',
		links: null,
		open: false
	},
	Implements: Options,
	initialize: function(options){
		this.setOptions(options);
		this.findLinks();
		
		if (this.options.links.length > 0){
			this.create();
		}
	},
	findLinks: function(){
		this.options.links = $$(this.options.linkSelector);
	},
	create: function(){
		this.options.mask = new Mask;
		this.options.overlay = new Element('div', { 'id': 'overlay' }).inject($(document.body));		
		this.options.content = new Element('div', { 'id': 'overlay-content' }).inject(this.options.overlay);
		
		this.options.close = new Element('a', {
			'class': 'close', 
			'href': '#',
			'html': 'Close'
		}).inject(this.options.overlay, 'top');
		
		this.createEvents();
		this.close();
	},
	createEvents: function(){
		this.options.links.each(function(a, i){
			if (!a.get('isOverlay')){
				a.addEvent('click', function(e){
					e.stop();
					if (a.hasClass('videoPlayer')){
						this.createVideo(a.get('href'));
						return;
					}
					this.get(a.get('href'));
				}.bind(this));
				a.set('isOverlay', true);
			}
		}.bind(this));
		this.options.close.addEvent('click', function(e){
			e.stop();
			this.close();
		}.bind(this));
		
		this.options.mask.addEvent('click', function(){ this.close(); }.bind(this));
	},
	get: function(href){
		this.load();
		Default.GA._trackPageview(href);
		var request = new Request.HTML({
			method: 'get',
			url: href,
			onComplete: function(tree, elements, html, js){
				this.set(html);
			}.bind(this)
		}).send();
	},
	set: function(response){
		this.unload();
		this.options.content.set('html', response);
		
		this.initPage();
	},
	load: function(){
		if (!this.options.open){ this.open(); }
		this.options.content.addClass('loading');
	},
	unload: function(){
		this.options.content.removeClass('loading');
	},
	open: function(){
		this.options.mask.show();
		this.options.overlay.setStyle('display', 'block');
	},
	close: function(){
		this.options.mask.hide();
		this.options.overlay.setStyle('display', 'none');
		
		this.options.content.empty();
	},
	createVideo: function(href){
		this.load();
		Default.GA._trackPageview(href);
		
		this.options.content.set('html', '<div id="videoPlayer" rel="' + href + '"></div>');		
		this.unload();
		this.initPage();
	},
	initPage: function(){
		var player = $('videoPlayer');
		if (player){
			var parameters = {
			    src: player.get('rel'),
			    autoPlay: false,
			    verbose: true,
			    controlBarAutoHide: 'false',
			    controlBarPosition: 'bottom',
				skin: 'inc/skin/skin.xml'
			}
			var flashvars = {
				allowFullScreen: true,
                wmode: 'transparent'
			}
			var attributes = {
			    name: 'videoPlayer'
			}
			swfobject.embedSWF('inc/swf/StrobeMediaPlayback.swf', 'videoPlayer', 946, 588, "10.1.0", "expressInstall.swf", parameters, flashvars, attributes);
		}		
	}
});

// Machine Selector Slider
Nescafe.SelectorSlider = function(slider, lineWidth){
	var activeLine = slider.getElement('div.activeLine');
	var initialStep = $(slider.get('rel')).get('value').length < 1 ? 0 : $(slider.get('rel')).get('value').toInt();
	new Slider(slider.getElement('.line'), slider.getElement('.knob'), {
		range: [0, 102],
		initialStep: initialStep,
		onChange: function(value){
			if (value.toInt() > 100){
				slider.getElement('span.lbl').set('text', '100+');
			} else {
				slider.getElement('span.lbl').set('text', value);
			}			
			activeLine.setStyle('width', value * lineWidth);
			$(slider.get('rel')).set('value', value);
			machineCookie.set('inp-users', value);
		},
		onComplete: function(value){
			$(slider.get('rel')).fireEvent('change');
		}
	});
}

// Machine Compare Scroller
Nescafe.CompareSlider = function(slider, slidingElement, maxWidth, navButtons){
	var active = 0;
	//var total = slidingElement.getElements('li.machine').length;
	var lineWidth = maxWidth / 100;
	compSliderInstance = new Slider(slider, slider.getElement('.knob'), {
		range: [0, 100],
		onChange: function(value){
			slidingElement.setStyle('margin-left', -(value * lineWidth));
			//console.log(value * lineWidth, value);
		}
	});
}

// Compare Form and Set Page
Nescafe.Compare = new Class({
    options: {
        slider: null,
        form: null,
        comparePage: false,
        xhr: null,
        compareMachineUrl: '/api/machines/compare',
        findMachinesUrl: '/api/machines',
        compareMachinePage: null,
        types: ['Coffee', 'CoffeeWith', 'Cappucino', 'Espresso', 'EspressoWith', 'CafeAuLait', 'WienerMelange', 'CafeMacchiato', 'Espreschoc', 'CafeMocca', 'HotChocolate', 'HotWater', 'FullAutomatic', 'NoTap']
    },
    Implements: Options,
    initialize: function (options) {
        this.setOptions(options);

        if ($(document.body).hasClass('machine_vergelijker')) {
            this.options.comparePage = true;
            this.options.compareMachinePage = $('compareMachines');
            this.options.showAllMachines = $('showAllMachines');
        }

        this.options.xhr = new Request.JSON({
            url: this.options.findMachinesUrl,
            onComplete: function (response) {
                this.setResponse(response);
            } .bind(this)
        });

        this.addEvents();
    },
    addEvents: function () {
        if (this.options.comparePage) {
            this.options.showAllMachines.addEvent('click', function (e) {
                e.stop();
                this.setResponse('all');
            } .bind(this));
        }

        this.options.form.getElements('input, input[type=hidden]').each(function (inp, i) {
            inp.addEvent('change', function () {
                if (inp.get('type') == 'checkbox') {
                    if (inp.get('hasChanged')) {
                        this.options.xhr.post(this.getData());
                        //this.options.form.send();
                    }
                    inp.set('hasChanged', true);
                }
                else { this.options.xhr.post(this.getData()); }
            } .bind(this));
        } .bind(this));
        this.options.form.getElement('input').fireEvent('change');
    },
    getData: function () {
        var data = {};
        var elements = this.options.form.getElements('input[type=text],input[type=checkbox],input[type=hidden]').filter(function (el) {
            if (el.get('type') == 'checkbox') {
                machineCookie.set(el.get('name'), el.get('checked'));
                return el.get('checked');
            }
            machineCookie.set(el.get('name'), el.get('value'));
            return true;
        });

        elements.each(function (el) {
            this[el.get('name')] = el.get('value');
        }, data);

        return data;
    },
    setResponse: function (resp) {
        if(resp == null) {
            return;
        }
                
        var counter = this.options.form.getElement('p.result > b');

        if (resp == 'all') {
            resp = [];
        }
        else {
            counter.set('text', resp.length);
        }

        if (this.options.comparePage) {
            var req = new Request.JSON({
                url: this.options.compareMachineUrl,
                headers: { 'Content-Type': 'application/json; charset=utf-8' },
                urlEncoded: false,
                onComplete: function (response) {
                    if (response) {
                        this.buildList(response);
                    }
                } .bind(this)
            });
            req.post(JSON.encode(resp));
        }
    },
    buildList: function (response) {
        var list = this.options.compareMachinePage.getElement('div.results > ul.machines');
        list.empty();
        response.each(function (obj, i) {
            var li = new Element('li', { 'class': 'machine' }).inject(list);
			var a = new Element('a', { 'href': '/koffiemachine/' + obj.Title.replace(/É/g,'e').replace(/\s/g,'_').replace(/\//g,'_').toLowerCase() }).inject(li);
            var header = new Element('span', {'class' : 'header'}).inject(a);
            var figure = new Element('span', {'class' : 'figure'}).inject(header);
            var figcaption = new Element('span', {'class' : 'figcaption', 'html': obj.Title }).inject(figure);
            var img = new Element('img', { 'src': obj.Resource.Uri, 'alt': obj.Title }).inject(figure);
            var h2 = new Element('h2', { 'html': obj.Title.replace('NESCAFÉ ', '') }).inject(header);

            var ul = new Element('ul', { 'class': 'result' }).inject(li);
            this.options.types.each(function (type, i) {
                this.createLi(obj[type], ul)
            } .bind(this));
        } .bind(this));

        this.setSlider();
    },
    createLi: function (value, where) {
        var li = new Element('li', {
            'html': (value ? '<img src="inc/image/icn-vink.png" alt="Vink">' : '&nbsp;')
        }).inject(where);
    },
    setSlider: function () {
        if (compSliderInstance != null) {
            compSliderInstance.detach();
            compSliderInstance.set(0);
        }
        if (this.options.compareMachinePage.getElements('div.results ul.machines li.machine').length.toInt() > 4) {
            this.options.compareMachinePage.getElement('> div.scroll').fade(1);
            Nescafe.CompareSlider(
				this.options.compareMachinePage.getElement('> div.scroll'),
				this.options.compareMachinePage.getElement('div.results ul.machines'),
				(this.options.compareMachinePage.getElements('div.results ul.machines li.machine').length.toInt() - 4) * 160,
				null
			);
        }
        else {
            this.options.compareMachinePage.getElement('> div.scroll').fade(.1);
        }
    }
});

// Nescafe Tabs
Nescafe.Tabs = new Class({
	options: {
		active: 0,
		next: 0,
		buttons: null,
		content: null,
		hashChange: false,
		innerPager: false
	},
	Implements: Options,
	initialize: function(options){
		this.setOptions(options);
		this.addEvents();
		
		if (this.options.hashChange && document.location.hash.length > 0){
			this.options.buttons.each(function(btn, i){
				if (btn.get('href').contains(document.location.hash)){
					this.options.next = i;
				}
			}.bind(this));
		}
		
		this.activate();
	},
	addEvents: function(){
		this.options.buttons.each(function(btn, i){
			btn.addEvent('click', function(e){
				e.stop();
				if (this.options.active != i){
					this.activate(i);
					if (this.options.hashChange){
						Default.GA._trackPageview(btn.get('href'));
						document.location.hash = btn.get('href').split('#')[1];
					}
				}
			}.bind(this));
		}.bind(this));
	},
	activate: function(i){
		if (typeof i != 'undefined'){ this.options.next = i; }
		if (this.options.active != this.options.next){
			this.options.buttons[this.options.active].removeClass('active');
			this.options.content[this.options.active].setStyle('display', 'none');
		}
		this.options.buttons[this.options.next].addClass('active');
		if(!ie){
			this.options.content[this.options.next].setStyle('display', 'block').fade('hide').fade(1);
		}
		else {
			this.options.content[this.options.next].setStyles({'display': 'block'});
		}
		this.options.active = this.options.next;
		
		if (this.options.innerPager){
			var pager = this.options.content[this.options.next].getParent('.section.products').getElement('.header ul.pager');
			if (this.options.content[this.options.next].hasClass('innerPager')){
				pager.fade('show');
			}
			else {
				pager.fade('hide');
			}
		}
		
		this.initTabs();
	},
	initTabs: function(){
		detection.recalc();
	}
});

// Nescafe Popup's for Ingredient Page
Nescafe.Popup = new Class({
	options: {
		elements: null,
		content: '.popup-content',
		popup: null,
		popupContent: null,
		close: null
	},
	Implements: Options,
	initialize: function(options){
		this.setOptions(options);
		
		this.create();
		this.addEvents();
	},
	create: function(){
		this.options.popup = new Element('div', {
			'class': 'popup',
			'events': {
				mouseleave: function(){
					this.hide();
				}.bind(this)
			}
		}).inject($(document.body));
		
		this.options.popupContent = new Element('div', { 'class': 'content' }).inject(this.options.popup);
		
		this.options.close = new Element('a', {
			'href': '#', 'html': 'close', 'class': 'close',
			'events': {
				click: function(e){
					e.stop();
					this.hide();
				}.bind(this)
			}
		}).inject(this.options.popup, 'top');
	},
	addEvents: function(){
		this.options.elements.each(function(btn, i){
			/*
			btn.addEvent('click', function(e){
				e.stop();
				this.activate(i);
			}.bind(this));
			*/
			btn.addEvents({
				mouseenter: function(){
					this.activate(i);
				}.bind(this)
			});
		}.bind(this));
	},
	activate: function(i){
		var content = this.options.elements[i].getElement(this.options.content);
		this.options.popupContent.set('html', content.get('html'));
		
		this.setPosition(i);
		this.show();
	},
	setPosition: function(i){
		var pos = this.options.elements[i].getPosition($(document.body));
		var size = this.options.elements[i].getSize();
		this.options.popup.setStyles({
			'left': (pos.x + (size.x / 2)) - 130,
			'top': (pos.y + (size.y / 2)) - 140
		});
	},
	show: function(){
		this.options.popup.setStyle('display', 'block');
	},
	hide: function(){
		this.options.popup.setStyle('display', 'none');
		this.options.popupContent.empty();
	}
});

// Nescafe Machine Pager
Nescafe.MachinePager = new Class({
	options: {
		ipp: 2,
		active: 0,
		total: 0,
		pages: 0,
		buttons: null,
		machineLists: null
	},
	Implements: Options,
	initialize: function(options){
		this.setOptions(options);
		
		this.setTotals();
		this.addEvents();

        if(document.location.hash.length > 1){
            this.options.active = document.location.hash.replace('#pagina', '').toInt() - 1;
        }
		this.show();
	},
	setTotals: function(){
		this.options.total = this.options.machineLists.length;
		this.options.pages = Math.ceil(this.options.total / this.options.ipp);
	},
	addEvents: function(){
		this.options.buttons.each(function(el, i){
			el.addEvent('click', function(e){
				e.stop();
				if (el.hasClass('prevPage')){
					this.prev();
				}
				else if(el.hasClass('nextPage')){
					this.next();
				}
			}.bind(this));
		}.bind(this));
	},
	prev: function(){
		--this.options.active;
		if (this.options.active < 0){
			this.options.active = 0; return false;
		}
		this.show();
	},
	next: function(){
		++this.options.active;
		if (this.options.pages - this.options.active < 1){
			this.options.active = this.options.pages - 1; return false;
		}
		this.show();
	},
	show: function(){
        Default.GA._trackPageview(document.location.pathname + '#pagina' + (this.options.active + 1));
        document.location.hash = 'pagina' + (this.options.active + 1);
		this.options.machineLists.setStyle('display', 'none');
		this.options.machineLists[this.options.active * this.options.ipp].setStyle('display', 'block');
		if (this.options.machineLists[(this.options.active * this.options.ipp) + 1]){
			this.options.machineLists[(this.options.active * this.options.ipp) + 1].setStyle('display', 'block');
		}
		detection.recalc();
		this.checkButtons();
	},
	checkButtons: function(){
		if (this.options.active < 1){
			this.options.buttons[0].fade('hide');
		}
		else {
			this.options.buttons[0].fade('show');
		}
		
		if (this.options.active >= this.options.pages - 1){
			this.options.buttons[1].fade('hide');
		}
		else {
			this.options.buttons[1].fade('show');
		}
	}
});

// Buttons:Before:After for <= IE7
Default.Pseudos = function(elms, type){
	if (Browser.ie6 || Browser.ie7){
		switch (type){
			default:
			case 'both':
				$$(elms).each(function(a, i){ 
					new Element('span', { 'class': 'elm-before' }).inject(a, 'top'); 
					new Element('span', { 'class': 'elm-after' }).inject(a);
				});
				break;
			case 'before':
				$$(elms).each(function(a, i){ new Element('span', { 'class': 'elm-before' }).inject(a, 'top'); });
				break;
			case 'after':
				$$(elms).each(function(a, i){ new Element('span', { 'class': 'elm-after' }).inject(a); });
				break;
		}
	}
}

// Input Placeholder Attribute for non Supported Browsers
Default.Placeholder = function(input){
	if (typeof input == 'undefined'){ input = 'input[type=text], textarea'; }
	$$(input).each(function(inp, i){
		if (inp.get('placeholder') && !inp.property('placeholder')){
			var placeholder = inp.get('placeholder');
			inp.addEvents({
				focus: function(){
					inp.get('value') == placeholder ? inp.set('value', '').removeClass('noInp') : null;
				},
				blur: function(){
					!inp.get('value') || inp.get('value') == placeholder ? inp.set('value', placeholder).addClass('noInp') : null;
				}
			}).fireEvent('blur');
			inp.getParent('form').addEvent('submit', function(){
				inp.get('value') == placeholder ? inp.set('value', '') : null;
			});
		}
	});
}

// Create Custom Checkboxes & Radiobuttons
Default.Checkbox = new Class({
	options: {
		elements: null
	},
	Implements: Options,
	initialize: function(options){
		this.setOptions(options);
		
		this.setElements();
		this.createCustom();
	},
	setElements: function(){
		this.options.elements = $$('input[type=checkbox], input[type=radio]');
	},
	createCustom: function(){
		var self = this;
		this.options.elements.each(function(element, key){
			if (!element.get('custom')){
				var type = element.get('type');
				var customElement = new Element('a', { 'class': 'custom-' + type }).inject(element, 'after');
				var sameElements = $$('input[type=' + type + '][name="' + element.get('name') + '"]');
				
				element.get('checked') ? customElement.addClass('active') : null;				
				element.addEvent('change', function(){
					if (this.get('checked')){
						customElement.addClass('active');
						self.resetOther(type, sameElements);
					}
					else {customElement.removeClass('active');}
				});
				customElement.addEvents({
					mouseenter: function(){ this.addClass('hover'); },
					mouseleave: function(){ this.removeClass('hover'); },
					click: function(e){
						e.stop();
                        if(element.get('name') == 'coffee') { return; }//if checkbox is coffee cancel the click
						if (element.get('checked') && type != 'radio'){element.set('checked', false);}
						else {
							self.uncheckOther(type, element, sameElements);
							element.set('checked', true);
						}
						element.fireEvent('change');
					}
				});
				element.setStyle('display', 'none').fireEvent('change');
				element.set('custom', true);
			}
		});
	},
	resetOther: function(type, sameElements){
		if (type == 'radio' && sameElements.length > 1){
			sameElements.each(function(radio, key){
				if (!radio.get('checked') && radio.getNext('a.custom-' + type)){
					radio.getNext('a.custom-' + type).removeClass('active');
				}
			});
		}
	},
	uncheckOther: function(type, element, sameElements){
		if (type == 'radio'){
			sameElements.each(function(el, i){
				el != element ? element.set('checked', false) : null;
			});
		}
	}
});

// Disable Tab Key
Default.noTab = function(inputs){
	inputs.each(function(input, i){
		input.addEvents({
			keydown: function(e){ if (e.key == 'tab'){ e.stop(); } }
		});
	});
}

// Google Analytics Helper
Default.GA = {};
Default.GA._trackPageview = function(url){
	if (typeof _gaq != 'undefined'){
		_gaq.push(['_trackPageview', url]);
	}
}


Element.implement({
	property: function(p){
		return p in document.createElement(this.get('tag'));
	}
});
