	
// Joulu 2009, cufon replace
Cufon.replace('.joulu-page #content h1');
Cufon.replace('#joulu-askartelubox .titles span');
Cufon.replace('.fairplex');
Cufon.replace('.myriad-pro');


(function() {
 
    var parse = function(source, separator) {
        var fields = new Hash({});
        if (source.length) source.split(separator).filter($chk).each(function(val) {
            var parts = val.split('=', 2);
            fields[parts[0]] = parts[1] ? decodeURIComponent(parts[1]).replace(/\+/g, ' ') : true;
        });
        return fields;
    }
    
    $extend(window, {
    
        QueryString: parse(location.search.substr(1), '&'),
        HashString: parse(location.hash.substr(1), ';')
    
    });
 
})();

window.addEvent('domready', function() {
	$$('.grillivinkit h2').each(function(el, i) {
		var vinkki = el.getNext('p');
		var slide = new Fx.Slide(vinkki);
		el.onclick = function() {
			slide.toggle();
			el.toggleClass('passive');
		}
		if(i != 0) slide.hide();
	});
	
	var popup = $('grilli-popup');
	if(document.getElementById('grilli-popup')) {
	var voteclose = document.getElementById('voteclose');
	voteclose.onclick = function() {
		document.getElementById('popupcontent2').style.display="none";
		document.getElementById('popupcontent1').style.display="block";
		popup.style.display="none";
	};
	$$('.aanestabtn').each(function(el) {
		var vote = el.title;
		
		el.onclick = function() {
			document.getElementById('votenumber').value=vote;
			popup.style.display="block";
		};
	});
	}
if(document.getElementById('grilli-popup')) {
	document.getElementById('popuptakaisin').onclick = function() {
		document.getElementById('popupcontent2').style.display="none";
		document.getElementById('popupcontent1').style.display="block";
	};
	
	document.getElementById('hellasaannot').onclick = function() {
		document.getElementById('popupcontent2').style.display="block";
		document.getElementById('popupcontent1').style.display="none";
	};
}
	
	if(document.getElementById('grilli-popup2')) {
	var popup2 = $('grilli-popup2');
	var voteclose2 = document.getElementById('voteclose2');
	var voteclose3 = document.getElementById('voteclose3');
	voteclose2.onclick = function() {
		document.getElementById('popupcontent2').style.display="none";
		document.getElementById('popupcontent1').style.display="block";
		popup2.style.display="none";
	};
	voteclose3.onclick = function() {
		document.getElementById('popupcontent2').style.display="none";
		document.getElementById('popupcontent1').style.display="block";
		popup2.style.display="none";
	};
	}
	

});

// Fix Request.HTML
 
Request.HTML.implement({
 
    processHTML: function(text){
        var match = text.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
        text = (match) ? match[1] : text;
        
        var container = new Element('div');
        
        return $try(function(){
            var root = '<root>' + text + '</root>', doc;
            if (Browser.Engine.trident){
                doc = new ActiveXObject('Microsoft.XMLDOM');
                doc.async = false;
                doc.loadXML(root);
            } else {
                // gecko doesn't support this, but the fallback should be good enough
                doc = new DOMParser().parseFromString(root, 'text/html');
            }
            root = doc.getElementsByTagName('root')[0];
            for (var i = 0, k = root.childNodes.length; i < k; i++){
                var child = Element.clone(root.childNodes[i], true, true);
                if (child) container.grab(child);
            }
            return container;
        }) || container.set('html', text);
    }
      
});
 
var Showcase = {
    
    build: function(path, options) {
    	if (Browser.Plugins.Flash.version < 8) return;
        var container = $('showcase');
        if (!container) return;
        new Swiff(path, $merge({
            wMode: 'transparent',
            container: container
        }, options));
    },
    
    hide: function() {
        $('showcase').addClass('compact');
    },
    
    show: function() {
        $('showcase').removeClass('compact');
    }
 
};
 
var ProductGroupCarousel = {
 
    place: function(where, options) {
    	if (Browser.Plugins.Flash.version < 8) return;
        if (!where) return;
        new Swiff('/files/tiesydameen/tuotekaruselli/karuselli.swf?src=/tuoteryhmat%2Exml', $merge({
            wMode: 'transparent',
            container: where,
            params: {
                bgcolor: '#fcf5db'
            },
            width: 612,
            height: 195
        }, options));
    }
 
};
 
var ProductCarousel = {
 
    place: function(where, options) {
    	if (Browser.Plugins.Flash.version < 8) return;
        if (!where) return;
        new Swiff('/files/tiesydameen/tuotekaruselli/karuselli2.swf?src=/tuotekaruselli%2Exml', $merge({
            wMode: 'transparent',
            container: where,
            params: {
                bgcolor: '#fcf5db'
            },
            width: 612,
            height: 195
        }, options));
    }
 
};
 
var Stars = new Class({
    
    Implements: [ Options, Events ],
    
    options: {
        action: '/videoarvostelu?ngform_on=1',
        data: {},
        name: 'q1',
        value: null
    },
    
    initialize: function(element, options) {
        this.bound = {
            preview: this.preview.bind(this),
            revert: this.revert.bind(this),
            onClick: this.onClick.bind(this)
        };
        this.setOptions(options);
        this.element = element || this.create();
        this.current = this.current || this.element.getElement('.current');
        this.attach();
    },
    
    attach: function() {
        this.element.getElements('li').addEvents({
            mouseover: this.bound.preview,
            mouseout: this.bound.revert,
            click: this.bound.onClick
        });
    },
    
    create: function() {
        var list = new Element('ul', {
            'class': 'stars'
        });
        for (var i = 1; i <= 5; ++i) {
            var li = new Element('li');
            if (this.options.value >= i) li.className = 'full';
            if (this.options.value == i) this.current = li;
            list.adopt(li.adopt(new Element('a', {
                href: '#',
                text: i
            })));
        }
        return list;
    },
    
    preview: function(e) {
        var target = $(e.target);
        var li = target.match('li') ? target : target.getParent('li');
        var found = false;
        this.element.getElements('li').each(function(el) {
            el[found ? 'removeClass' : 'addClass']('full');
            found = found || (el == li);
        });
    },
    
    revert: function(e) {
        var found = !this.current;
        this.element.getElements('li').each(function(el) {
            el[found ? 'removeClass' : 'addClass']('full');
            found = found || (el == this.current);
        }, this);
    },
    
    onClick: function(e) {
        e.stop();
        var target = $(e.target);
        this.set(target.match('li') ? target : target.getParent('li'));
        this.send();
        target.blur();
    },
    
    set: function(value) {
        var el = $type(value) == 'element' ? value : this.element.getChildren('li')[value];
        if (!el) return;
        if (this.current != el) {
            this.fireEvent('change', el.getAllPrevious('li').length + 1);
            this.current = el;
        }
    },
    
    send: function() {
        this.element.addClass('stars-loading');
        var params = {};
        if (this.current) params[this.options.name] = this.current.getAllPrevious('li').length + 1;
        new Request({
            url: this.options.action,
            onSuccess: function() {
                this.element.removeClass('stars-loading');
            }.bind(this)
        }).post($merge(this.options.data, params));
    },
    
    toElement: function() {
        return this.element;
    }
    
});
 
var CustomInput = {
    
    checkbox: function(input) {
        new Element('span', { 'class': 'checkbox' }).wraps(input);
        input.addEvents({
            change: (function() {
                input.getParent('span')[input.checked ? 'addClass' : 'removeClass']('checkbox-checked');
                return arguments.callee;
            })(),
            click: function() {
                if (Browser.Engine.trident) this.fireEvent('change');
            }
        });
    },
    
    radio: function(input) {
        new Element('span', { 'class': 'radio' }).wraps(input);
        input.addEvents({
            change: (function() {
                input.getParent('span')[input.checked ? 'addClass' : 'removeClass']('radio-checked');
                return arguments.callee;
            })(),
            click: function() {
                if (Browser.Engine.trident) this.fireEvent('change');
            }
        });
    },
    
    text: function(input) {
    	if (input.hasClass('ginput')) {} else {
        new Element('span', { 'class': 'textbox' }).wraps(input);
        new Element('span', { 'class': 'inner' }).wraps(input);
        if (input.hasClass('has-default')) {
            input.addEvents({
                focus: function() {
                    if (this.value == this.defaultValue) {
                        this.value = '';
                    }
                    input.removeClass('has-default');
                },
                blur: function() {
                    if (this.value == '') {
                        this.value = this.defaultValue;
                        input.addClass('has-default');
                    }
                }
            });
        }}
    },
    
    password: function(input) {
        new Element('span', { 'class': 'textbox' }).wraps(input);
        new Element('span', { 'class': 'inner' }).wraps(input);
        if (input.hasClass('has-default')) {
            var defaultDisplay = input.getStyle('display');
            var text = new Element('input', {
                type: 'text',
                value: input.defaultValue,
                size: input.size,
                events: {
                    focus: function() {
                        this.setStyle('display', 'none');
                        input.setStyle('display', defaultDisplay).set('value', '').focus();
                    }
                }
            }).inject(input, 'before');
            if (input.value == input.defaultValue) {
                input.setStyle('display', 'none');
            }
            input.addEvents({
                blur: function() {
                    if (this.value == '') {
                        this.setStyle('display', 'none');
                        text.setStyle('display', defaultDisplay);
                        this.value = this.defaultValue;
                    }
                }
            });
        }
    },
    
    textarea: function(input) {
        new Element('span', { 'class': 'textarea' }).wraps(input);
        new Element('span', { 'class': 'inner' }).wraps(input);
        new Element('span', { 'class': 'inner' }).wraps(input);
        new Element('span', { 'class': 'inner' }).wraps(input);
        if (input.hasClass('has-default')) {
            input.addEvents({
                focus: function() {
                    if (this.value == this.defaultValue) {
                        this.value = '';
                    }
                    input.removeClass('has-default');
                },
                blur: function() {
                    if (this.value == '') {
                        this.value = this.defaultValue;
                        input.addClass('has-default');
                    }
                }
            });
        }
    }
    
};
 
var Select = new Class({
    
    Implements: [ Options, Events ],
    
    options: {
        related: '.select',
        maxLabelLength: 18,
        autoHide: true
    },
    
    initialize: function(el, options) {
        this.bound = {
            hide: this.hide.bind(this),
            show: this.show.bind(this),
            toggle: this.toggle.bind(this)
        };
        this.element = $(el);
        this.setOptions(options);
        var max = this.element.get('class').match(/max-(\d+)/);
        if (max) this.options.maxLabelLength = max[1];
        this.labelElement = this.element.getElement('dt');
        this.originalLabel = this.labelElement.get('text');
        this.select(this.element.getElement('.current'));
        this.attach();
    },
    
    attach: function() {
        this.element.addEvents({
            click: function(e) {
                e.stop();
                this.toggle();
                var target = $(e.target);
                if (!target.match('a')) target = target.getParent('a');
                if (target) this.select(target);
            }.bind(this),
            mouseleave: function() {
                if (this.options.autoHide) this.hideDelay = this.bound.hide.delay(1000);
            }.bind(this),
            mouseenter: function() {
                $clear(this.hideDelay);
            }.bind(this)
        });
        if (this.options.autoHide) document.addEvent('click', this.bound.hide);
    },
    
    hide: function() {
        this.element.removeClass('expanded');
        this.fireEvent('toggle').fireEvent('hide');
    },
    
    isExpanded: function() {
        return this.element.hasClass('expanded');
    },
    
    reset: function() {
        this.element.removeClass('value-selected');
        this.element.getElements('.current').removeClass('current');
        this.selected = null;
        this.labelElement.set('text', this.originalLabel);
    },
    
    select: function(target) {
        if (!target) return false;
        if (target === this.selected) {
            this.reset();
            this.fireEvent('select', null);
            return false;
        }
        var label = target.get('text') || target.getElements('img').get('alt').join('');
        if (label.length > this.options.maxLabelLength) label = label.substring(label, this.options.maxLabelLength - 2) + '..';
        this.element.addClass('value-selected');
        this.labelElement.set('text', label);
        this.element.getElements('.current').removeClass('current');
        this.selected = target.addClass('current');
        this.fireEvent('select', target);
        return true;
    },
    
    show: function() {
        $$(this.options.related).removeClass('expanded');
        this.element.addClass('expanded');
        this.fireEvent('toggle').fireEvent('show');
    },
    
    toggle: function() {
        this[this.isExpanded() ? 'hide' : 'show']();
    }
    
});
 
var Pagination = new Class({
    
    Implements: [ Events, Options ],
    
    initialize: function(elements, options) {
        this.bound = {
            onItemClicked: this.onItemClicked.bind(this)
        };
        this.setOptions(options);
        this.elements = elements;
        this.current = this.options.current;
        this.bounds = {
            from: 1,
            to: this.options.total
        };
        this.attach();
    },
    
    attach: function() {
        this.elements.addEvents({
            click: this.bound.onItemClicked
        });
    },
    
    checkBounds: function() {
        if (this.current == this.bounds.from) {
            this.elements.each(function(el) {
                el.getElements('.previous').addClass('disabled');
            });
        }
        else {
            this.elements.each(function(el) {
                el.getElements('.previous').removeClass('disabled');
            });
        }
        if (this.current == this.bounds.to) {
            this.elements.each(function(el) {
                el.getElements('.next').addClass('disabled');
            });
        }
        else {
            this.elements.each(function(el) {
                el.getElements('.next').removeClass('disabled');
            });
        }
    },
    
    getPageFromItem: function(item) {
        if (!item) return null;
        var page = item.retrieve('pagination:page');
        if (!page) {
            item.store('pagination:page', page = Number(item.get('text')));
        }
        return page;
    },
    
    onItemClicked: function(e) {
        e.stop();
        var target = $(e.target);
        if (!target.match('a')) return;
        target.blur();
        if (target.hasClass('next')) {
            this.set(this.current + 1);
            return;
        }
        if (target.hasClass('previous')) {
            this.set(this.current - 1);
            return;    
        }
        this.set(this.getPageFromItem(target));
    },
    
    render: function() {
        this.checkBounds();
        this.elements.each(function(el) {
            var list = new Element('ul', { 'class': 'pages' });
	        for (var i = this.bounds.from; i <= this.bounds.to; ++i) {
	            list.adopt(
	                new Element('li', {
	                    'class': i == this.current ? 'current': ''
	                }).adopt(
	                    new Element('a', {
	                        href: '#',
	                        text: i
	                    })));
	        }
            list.replaces(el.getElement('.pages'));
        }, this);
        return this;
    },
    
    set: function(to) {
        if (to < this.bounds.from || to > this.bounds.to || to == this.current) return this;
        this.setCurrent(to);
        this.render();
        this.fireEvent.delay(5, this, 'change');
        return this;
    },
    
    setCurrent: function(current) {
        this.current = current;
        return this;
    },
    
    setBounds: function(from, to) {
        this.bounds.from = from;
        this.bounds.to = to;
        this.render();
        return this;
    }
    
});
 
var Products = new Class({
    
    Implements: [ Options, Events ],
    
    options: {
        feed: '/tuotehaku.json',
        icon: 'http://media.artstudio.fi/FotoWeb/fwbin/pvagent.dll?im-query=(iptc201%20contains%20(@@product_id@@))&folder-id=5001&username=hkpa&password=hk&pv-size=111', // there's nothing interesting to see there, don't waste your time :)
        perPage: 20,
        rowLength: 5,
        yUnit: 189
    },
    
    initialize: function(container, options) {
        this.bound = {
            load: this.load.bind(this),
            loadFromStart: this.loadFromStart.bind(this),
            onProductsLoaded: this.onProductsLoaded.bind(this)
        };        
        this.setOptions(options);
        this.container = $(container);
        this.selector = this.container.getElement('#product-selector');
        this.productList = this.container.getElement('#product-list');
        this.selectorForm = this.selector.getElement('form');
        this.pagination = new Pagination(this.container.getElements('.pagination'), {
            current: 1,
            total: 1
        }).addEvents({
            change: this.bound.load
        });
        var products = this, ignore = true;
        this.container.getElements('.select-all').addEvents({
            click: function() {
                ignore = true;
                var anyUnchecked = this.getParent('fieldset').getElements('input').some(function(el) {
                    return !el.checked;
                });
                this.getParent('fieldset').getElements('input').each(function(input) {
                    input.checked = anyUnchecked;
                    input.fireEvent('change');
                });
                ignore = false;
                products.load(true);
            }
        });
        this.container.getElements('.reset').addEvents({
            click: function() {
                ignore = true;
                this.getParent('fieldset').getElements('input').each(function(input) {
                    input.checked = false;
                    input.fireEvent('change');
                });
                ignore = false;
                products.load(true);
            }
        });
        this.container.getElements('.reset-all').addEvents({
            click: function() {
            	this.forget();
                window.location.href = '/tuotteet';
            }.bind(this)
        });
        var changed = function() {
            if (!ignore) this.loadFromStart.delay(10, this);
        }.bind(this);
        var slowChanged = function() {
            if (!ignore) this.loadFromStart.delay(500, this);
        }.bind(this);
        var selected = function(target) {
            this.element.getElements('.selected').removeClass('selected');
            if (!target) return;
            $(target).addClass('selected').getParent('li').addClass('selected');
        };
        $('product-selector').getElements('input[type=checkbox]').addEvent('change', changed);
        this.brandSelect = new Select($('brand-select'), { related: '#group-select' }).addEvent('select', changed).addEvent('select', selected);
        this.groupSelect = new Select($('group-select'), { related: '#brand-select' }).addEvent('select', changed).addEvent('select', selected);
        this.specialSelect = new Select($('special-select'), { autoHide: false, related: null }).addEvent('toggle', slowChanged).addEvent('toggle', function() {
            $$('#products .special').slide(this.isExpanded() ? 'in' : 'out');
        });
        var specialPanel = $$('#products .special').setStyle('display', 'block');
        if (!HashString.get('erikoishaku')) specialPanel.slide('hide');
        else this.specialSelect.show();
        if ($('healthy-select')) {
	        this.healthySelect = new Select($('healthy-select'), { autoHide: false, related: null }).addEvent('toggle', changed);
        	if (QueryString.get('sydanmerkki')) this.healthySelect.show();
        }
        this.selectorForm.addEvent('submit', function() {
            changed();
            return false;
        });
        this.selectorForm.getElements('input').each(function(input) {
            input.checked = false;
            input.fireEvent('change');
        });
        if (QueryString.getLength()) this.forget();
        else this.remember();
        ignore = false;
        this.load();
        $$('#print-products').addEvent('click', function() {
            var qs = this.selector.toQueryString();
            if (qs.length) qs += '&';
            qs += this.filters().toQueryString();
            location.href = '/tuotteet_tuloste' + (qs && '?') + qs;
            return false;
        }.bind(this));
    },
    
    save: function() {
	if (this.selector.hasClass('no-products')) {
		this.forget();
		return;
	}
    	var filters = this.filters();
    	var specials = [];
    	this.container.getElements('form input[type=checkbox]').each(function(input) {
    		if (input.checked) specials.push(input.id);
    	});
    	filters.specials = specials.join(',');
    	filters.filter = $$('#ifilter').get('value').join('');
    	filters.page = this.pagination.current;
    	Cookie.write('psf', JSON.encode(filters));
    },
    
    remember: function() {
    	var filters = Cookie.read('psf');
    	if (!filters) return;
    	filters = JSON.decode(filters);
    	if (filters.specials) {
    		$$('#' + filters.specials.replace(/,/g, ', #')).each(function(input) {
    			input.checked = true;
    			input.fireEvent('change');
    		});
    		this.specialSelect.show();
    	}
    	if (filters.tuotemerkki) $$('#brand-select img').each(function(img) {
    		if (img.alt === filters.tuotemerkki) this.brandSelect.select(img.getParent('a'));
    	}.bind(this));
   	if (filters.tuoteryhma) this.groupSelect.select($$('#group-select a[href*="tuoteryhma=' + filters.tuoteryhma + '"]')[0]);
    	if (filters.sydanmerkki) this.healthySelect.show();
    	if (filters.filter) $$('#ifilter').set('value', filters.filter);
   	this.pagination.setCurrent(filters.page || 1);
    },
    
    forget: function() {
    	Cookie.dispose('psf');
    },
    
    // plain JS for speed
    createProduct: function(data) {
        var container = document.createElement('li');
        container.className = 'product';
        container.onmouseover = function() {
            if (this.className.indexOf('hover') < 0) this.className += ' hover';
        };
        container.onmouseout = function() {
            this.className = this.className.replace(/(\s+|^)hover(?:(?=\s+)|$)/g, '');
        };
        var title = document.createElement('h3');
        var link = document.createElement('a');
        link.href = data.url;
        link.title = data.name;
        link.onclick = function(e) {
            if (!e) e = window.event;
            if (e.preventDefault) e.preventDefault();
            else e.returnValue = false;
            location.href = this.href;
        };
        title.appendChild(link);
        container.appendChild(title);
        var pic = document.createElement('span');
        pic.className = 'pic';
        link.appendChild(pic);
        if (data.id) {
            pic.style.backgroundImage = 'url("' + this.options.icon.replace('@@product_id@@', data.id.split(',')[0]) + '")';
        }
        if (data.is_new) {
            var flag = document.createElement('span');
            flag.className = 'new';
            flag.innerHTML = 'UUTUUS';
            link.appendChild(flag);
        }
        link.appendChild(document.createTextNode(data.name.length > 40 ? data.name.substr(0, 40) + '..' : data.name));
        return container;
    },
    
    filters: function() {
        var filters = new Hash();
        if (this.brandSelect.selected) filters.tuotemerkki = decodeURIComponent(this.brandSelect.selected.href.match(/tuotemerkki=(.*?)(?:&|$)/)[1]).replace('+', ' ');
        if (this.groupSelect.selected) filters.tuoteryhma = this.groupSelect.selected.href.match(/tuoteryhma=(.*?)(?:&|$)/)[1];
        if (this.healthySelect && this.healthySelect.isExpanded()) filters.sydanmerkki = 1;
        ['valmistustapa', 'erityisruokavalio', 'hyvaa_suomesta', 'grillaustuote'].each(function(q) {
            var val = QueryString.get(q);
            if (val) filters[q] = val;
        });
        if (!this.specialSelect.isExpanded() && this.selectorForm.q && this.selectorForm.q.value != '') filters.q = this.selectorForm.q.value;
        return filters;
    },
    
    load: function(fromStart) {
        this.productList.addClass('loading');
        var filters = this.filters();
        var data = this.selector.toQueryString();
        this.container.getElements('.list-type').set('html', filters.getLength() == 0 && !this.specialSelect.isExpanded() ? 'Kaikki tuotteet:' : 'Hakusi tulokset:');
        new Request.JSON({
                url: this.options.feed + (this.specialSelect.isExpanded() ? '?' + this.selector.toQueryString() : '')
            }).addEvents({
                success: this.bound.onProductsLoaded
            }).get(filters.combine({
                page: fromStart ? 1 : this.pagination.current,
                ts: new Date().getTime()
            }));
    },
    
    loadFromStart: function() {
        this.load(true);
    },
    
    onProductsLoaded: function(data) {
    	this.selector[data.products.length ? 'removeClass' : 'addClass']('no-products');
        this.productList.setStyle('height', Math.max(1, Math.ceil(this.productList.getElements('.product').length / this.options.rowLength)) * this.options.yUnit);
        this.productList.empty();
        data.products.each(function(product) {
            this.productList.appendChild(this.createProduct(product));
        }, this);
        this.pagination.setCurrent(1 + Math.floor(data.from / this.options.perPage)).setBounds(1, Math.max(1, Math.ceil(data.total / this.options.perPage)));
        this.productList.get('tween', { transition: 'quad:out'}).start('height', Math.max(1, Math.ceil(data.products.length / this.options.rowLength)) * this.options.yUnit).chain(function() {
            this.subject.removeClass('loading');    
        });
        this.save();
    }
    
});
 
var BBQProducts = new Class({
    
    Extends: Products,
    
    options: {
        feed: '/tuotehaku-grilli.json'
    },
    
    initialize: function(container, options) {
        this.bound = {
            load: this.load.bind(this),
            loadFromStart: this.loadFromStart.bind(this),
            onProductsLoaded: this.onProductsLoaded.bind(this)
        };
        this.setOptions(options);
        this.container = $(container);
        this.selector = this.container.getElement('#product-selector');
        this.productList = this.container.getElement('#product-list');
        this.selectorForm = this.selector.getElement('form');
        this.pagination = new Pagination(this.container.getElements('.pagination'), {
            current: 1,
            total: 1
        }).addEvents({
            change: this.bound.load
        });
        var products = this, ignore = true;
        this.container.getElements('.select-all').addEvents({
            click: function() {
                ignore = true;
                var anyUnchecked = this.getParent('fieldset').getElements('input').some(function(el) {
                    return !el.checked;
                });
                this.getParent('fieldset').getElements('input').each(function(input) {
                    input.checked = anyUnchecked;
                    input.fireEvent('change');
                });
                ignore = false;
                products.load(true);
            }
        });
        this.container.getElements('.reset-all').addEvents({
            click: function() {
                window.location.href = '/grillituotteet';
            }.bind(this)
        });
        var changed = function() {
            if (!ignore) this.loadFromStart.delay(10, this);
        }.bind(this);
        var slowChanged = function() {
            if (!ignore) this.loadFromStart.delay(500, this);
        }.bind(this);
        this.selector.getElements('input[type=checkbox]').addEvent('change', changed);
        this.selectorForm.addEvent('submit', function() {
            changed();
            return false;
        });
        this.selectorForm.getElements('input').each(function(input) {
            input.checked = false;
            input.fireEvent('change');
        });
        this.checkboxes = [];
        this.selector.getElements('.toggle-select').each(function(el) {
            this.checkboxes.push(new Select(el, { autoHide: false, related: '.toggle-select' }).addEvent('toggle', changed));
        }, this);
        ignore = false;
        this.load();
        $$('#print-products').addEvent('click', function() {
            var qs = this.selector.toQueryString();
            if (qs.length) qs += '&';
            qs += this.filters().toQueryString();
            location.href = '/tuotteet_tuloste?grillaustuote=1' + (qs && '&') + qs;
            return false;
        }.bind(this));
    },
    
    filters: function() {
        var filters = new Hash();
        this.checkboxes.each(function(cb) {
            if (cb.isExpanded()) filters.tuoteryhma = cb.element.id.substr(2);
        });
        filters.q = this.selectorForm.q.value;
        return filters;
    },
    
    load: function(fromStart) {
        this.productList.addClass('loading');
        new Request.JSON({
                url: this.options.feed
            }).addEvents({
                success: this.bound.onProductsLoaded
            }).get(this.filters().combine({
                page: fromStart ? 1 : this.pagination.current,
                ts: new Date().getTime()
            }));
    }
    
});
 
var Rating = new Class({
    
    initialize: function(data) {
        this.data = data;
        this.element = this.create();
    },
    
    create: function() {
        return new Element('div', {
                'class': 'rate'
            }).adopt(new Element('label', {
                text: 'Arvostele:'
            }))
            .adopt(new Stars(null, { data: { q0: this.data.id }, value: this.data.rating }));
    },
    
    toElement: function() {
        return this.element;
    }
 
});
 
var RecipeRating = new Class({
 
    Extends: Rating,
    
    create: function() {
        return new Element('div', {
                'class': 'rate'
            }).adopt(new Element('label', {
                text: 'Arvostele:'
            }))
            .adopt(new Stars(null, { action: '/reseptiarvostelu?ngform_on=1', data: { q0: this.data.id }, value: this.data.rating }));
    }
    
});
 
var UserRecipeRating = new Class({
 
    Extends: Rating,
    
    create: function() {
        return new Element('div', {
                'class': 'rate'
            }).adopt(new Element('label', {
                text: 'Arvostele:'
            }))
            .adopt(new Stars(null, { action: '/kotikokin-ruokaohje-arvostelu?ngform_on=1', data: { q0: this.data.id }, value: this.data.rating }));
    }
    
});
 
var Videos = new Class({
    
    Implements: [ Options, Events ],
    
    options: {
        feed: '/videot.json',
        perPage: 10
    },
    
    initialize: function(container, options) {
        this.bound = {
            load: this.load.bind(this),
            onVideosLoaded: this.onVideosLoaded.bind(this)
        };
        this.setOptions(options);
        this.container = $(container);
        this.videoList = this.container.getElement('.video-list');
        this.options.feed = this.videoList.get('data-feed');
        this.pagination = new Pagination(container.getElements('.pagination'), {
            current: 1,
            total: 1
        }).addEvents({
            change: this.bound.load
        });
        this.load();
    },
    
    createVideo: function(data) {
        var container = new Element('li', {
                'class': 'video',
                events: {
                    mouseover: function() {
                        this.addClass('hover');
                    },
                    mouseout: function() {
                        this.removeClass('hover');
                    }
                }
            });
        var thumb = new Element('div', {
                'class': 'thumb'
            }).adopt(new Element('a', {
                href: data.url
            }).adopt(new Element('img', {
                src: data.thumb,
                events: {
                    error: function() {
                        this.dispose();
                    }
                }
            }))).inject(container);
        var title = new Element('h3', {
                'class': 'title'
            }).inject(container);
        var link = new Element('a', {
                href: data.url,
                text: data.title
            }).inject(title);
        var description = new Element('div', {
                'class': 'description',
                html: data.description
            }).inject(container);
        container.adopt(new Rating(data));
        return container;
    },
    
    load: function(fromStart) {
        this.container.addClass('loading');
        var filters = new Hash();
        new Request.JSON({
                url: this.options.feed
            }).addEvents({
                success: this.bound.onVideosLoaded
            }).get(filters.combine({
                page: this.pagination.current,
                ts: new Date().getTime()
            }));
    },
    
    onVideosLoaded: function(data) {
        this.videoList.empty();
        data.videos.each(function(video) {
            this.videoList.adopt(this.createVideo(video));
        }, this);
        if (this.videoList.getLast()) {
            this.videoList.getLast().addClass('last');
            this.videoList.removeClass('no-videos');
        }
        else {
            this.videoList.addClass('no-videos');
        }
        this.pagination.setCurrent(1 + Math.floor(data.from / this.options.perPage)).setBounds(1, Math.max(1, Math.ceil(data.total / this.options.perPage)));
        this.container.removeClass('loading');
    }
    
});
 
var Tabs = new Class({
    
    initialize: function(el) {
        this.element = $(el);
        this.list = this.element.match('dl') ? this.element : this.element.getElement('dl');
        this.attach();
        if (location.hash) this.activate(location.hash.substring(1));
    },
    
    activate: function(id) {
        if (!$(id)) return;
        this.list.getChildren().removeClass('active');
        this.list.getChildren('dt.go-' + id).addClass('active');
        $(id).addClass('active');
    },
    
    onTabClicked: function() {
        this.getParent('dl').getChildren().removeClass('active');
        this.getParent('dt').addClass('active');
        $(this.href.replace(/^.*#/, '')).addClass('active');
        try {
            this.blur();
        }
        catch (e) {}
        return false;
    },
    
    attach: function() {
        this.list.getChildren('dd').inject(this.list);
        this.list.getChildren('dt').each(function(el) {
            el.getElement('a').addEvent('click', this.onTabClicked);
            el.addEvents({
                mouseover: function() {
                    this.addClass('hover');
                },
                mouseout: function() {
                    this.removeClass('hover');
                }
            });
        }, this);
    }
    
});
 
var HenkkaOsoitin = {
    
    place: function() {
        if (Browser.Plugins.Flash.version < 9) return;
        window.addEvent('domready', function() {
            var container = new Element('div', {
                id: 'henkkaosoitin'
            }).inject($('page'));
            window.closeFlash = function() {
                $$('#henkkaosoitin').setStyle('display', 'none');    
            };
            new Swiff('/files/tiesydameen/henkat/henkkaOsoitin.swf', {
                width: 300,
                height: 200,
                container: container
            });
        });
    }
    
};
 
var OsioHenkka = {
    
    insert: function(path, width, height, klass) {
        if (Browser.Plugins.Flash.version < 9) return;
        window.addEvent('domready', function() {
            var container = new Element('div', {
                'class': 'static-henkka' + (klass ? ' ' + klass : '')
            }).inject($('page'));
            new Swiff(path, {
                width: width || 350,
                height: height || 190,
                container: container
            });
        });
    }
    
};
 
var ImageLoader = {
    
    load: function(src, container) {
        $(container).addClass('picture-loading');
        (function poll() {
            var loader = $(new Image());
            loader.addEvents({
                error: function() {
                    setTimeout(poll, 2000);
                },
                load: function() {
                    $(container).adopt(loader).removeClass('picture-loading');
                }
            });
            loader.src = src + (src.indexOf('?') == -1 ? '?' : '&') + $time();
        })();
    }
 
};
 
window.init = function() {

    (function(intro) {
    
        if (!intro) return;
        
        if (Cookie.read('i:hide') == 'y') {
            intro.setStyle('display', 'none');
        }
        else {
            Cookie.write('i:hide', 'y', { duration: 30, path: '/' });
        }
        
    })($('intro'));
    
    if (window.Cufon) Cufon.DOM.ready();
    
    $$('#nav li, #box-product-navigation li, #box-navigation li').addEvents({
        mouseenter: function() {
            this.addClass('hover');
        },
        mouseleave: function() {
            this.removeClass('hover');
        }
    });
    
    // input

    $$('input[type]').each(function(el) {
        if (CustomInput[el.type]) CustomInput[el.type](el);
    });

    $$('textarea').each(function(el) {
        if (CustomInput['textarea']) CustomInput['textarea'](el);
    });
    
    $$('.dropdown').each(function(el) {
        new Select(el, {
            related: '.dropdown'
        }).addEvent('select', function(target) {
            location.href = target.href;
        });
    });
    
    // products
    
    var products = $('products');
    if (products) {
        if (products.hasClass('bbq')) new BBQProducts(products);
        else if (products.hasClass('joulu')) new Products(products, { feed: '/joulu-tuotehaku.json', perPage: 15, rowLength: 3 });
        else if (products.hasClass('grilli')) new Products(products, { feed: '/grillikesa-tuotehaku.json', perPage: 15, rowLength: 3 });
        else new Products(products);
    }
    
    // videos
    
    $$('.videos dd.active, .videos dd').each(function(el) {
        new Videos(el);
    });
 
    // product carousel
    
    ProductGroupCarousel.place($('box-tuoteryhmakaruselli'));
    ProductCarousel.place($('box-tuotekaruselli'));
    
    // tabs
    
    $$('.tabbed').each(function(el) {
        new Tabs(el);
    });
    
    // path
    
    if (Browser.Engine.trident) $$($$('.path li').slice(0, -1)).each(function(el) {
        el.innerHTML += '<span class="after">/</span>';
    });
    
    // grid
    
    $$('.primary .box').each(function(box) {
        if (box.offsetLeft > box.offsetWidth) {
            box.addClass('box-right');
        }
    });
    
    // content images
    
    $$('#content img').each(function(el) {
        switch (el.getStyle('float')) {
            case 'right':
                el.addClass('align-right');
                break;
            case 'left':
                el.addClass('align-left');
                break;
        }
    });
    
    // ie6 png cover
    
    if (Browser.Engine.trident4) $$('.box-variant-16 .box-content, .box-variant-12 .box-content, .box-variant-26 .box-content').each(function(el) {
        new Element('div', {
            'class': 'box-content-cover'
        }).wraps(el);
    });
    
    // list items
    
    $$('#content li:last-child').addClass('last');
    
    $$('ol li').each(function(el, i) {
        new Element('span', { 'class': 'bullet bullet' + i }).inject(el, 'top');
    });
    
    // showcase
    
    Showcase.build('/files/tiesydameen/hk_flash/' + (QueryString.get('fv') || 'banner').replace(/[^a-z0-9_\-]/g, '') + '.swf?src=/' + (QueryString.get('fs') || 'showcase').replace(/[^a-z0-9_\-]/g, '') + '%2Exml', {
        height: 295,
        width: 925
    });
 
    // toggleboxes
    $$('h3.toggle').addEvent('click', function() {
        this.toggleClass('collapse');
        this.getNext('.text').toggleClass('hidden');
    });
        
};

 
window.addEvent('load', function() {

/*
        
    (function() {
    
        // logon vaihdos flashiin
    
//    	if (!QueryString.get('logotest')) return; // disabled
        if (!Browser.Plugins.Flash || Browser.Plugins.Flash.version < 8) return;

        var slogan = document.getElement('#head .slogan');
        if (!slogan) return;

             
        slogan.setStyles({
            'background': 'none',
            'cursor': 'default',
            'text-indent': 0,
            'margin-top': 0,
            'margin-right': 0,
            'position': 'absolute',
            'top': -6,
            'right': -64,
            'width': 286,
            'height': 175,
            'filter': ''
        });

        new Swiff('/files/tiesydameen/sesongit/hk_kesa_logo.swf', {
            wMode: 'transparent',
            container: slogan,
            width: 286,
            height: 175
        });

    })();

*/

    
    (function() {
    
        return; // remove to enable
        
        var wait = 30000;
        var duration = 100; // days
    
        var start = Cookie.read('q:start'), now;
        
        if (start == 'complete' || !start) { // done is the real one
            Cookie.write('q:start', new Date().getTime(), { duration: duration, path: '/' });
            return;
        }
        
        if (start == 'done') return;
        
        function ask() {
            
            start = parseInt(start, 10);
            now = new Date().getTime();
            
            if (now - start < wait) return;
            
            Cookie.write('q:start', 'done', { duration: duration, path: '/' });
            
            GoDialog.show({
                title: 'Vapaaehtoinen k�ytt�j�tutkimus',
                message: 'Tiesydameen.fi -sivustoa kehitet��n jatkuvasti. ' +
                    'Voit antaa mielipiteesi sivustosta vastaamalla k�vij�tutkimukseemme.<br /><br />' +
                    'Vastaaminen kest�� noin 10 minuuttia. Vastaajien kesken arvomme palkintoja.<br /><br />' +
                    'Haluatko osallistua kyselyyn?',
                url: 'http://digiumenterprise.com/answer/?sid=310290&chk=5J9MMB9M',
                goText: 'Kyll�, avaa kysely!',
                cancelText: 'En t�ll� kertaa'
            });
            
        }
        
        ask.delay(1500);
    
    })();
    
}); 
 
var GoDialog = new Class({
 
    Implements: [ Options ],
    
    options: {
        title: '',
        message: '',
        url: '',
        windowName: 'godialog',
        cancelText: 'Peruuta',
        goText: 'Siirry',
        sizeParams: 'height=600,width=920',
        windowParams: '600,width=920,menubar=no,toolbar=no,location=yes,status=yes,directories=no,resizable=yes,scrollbars=yes'
    },
 
    initialize: function(options) {
        this.bound = {
            go: this.go.bind(this),
            hide: this.hide.bind(this)
        };
        this.setOptions(options);
    },
    
    go: function() {
        if (!window.open(this.options.url, this.options.windowName, this.options.sizeParams + ',' + this.options.windowParams)) {
            location.href = this.options.url;
        }
        return this.hide();
    },
    
    hide: function() {
        this.element.dispose();
        this.element = null;
        return this;
    },
    
    show: function() {
        $(document.body).adopt(this.toElement());
        return this;
    },
    
    toElement: function() {
        if (this.element) return this.element;
        var wrapper = new Element('div', {
            'class': 'godialog dialog'
        });
        var head = new Element('div', {
            'class': 'godialog-head',
            html: this.options.title
        });
        var content = new Element('div', {
            'class': 'godialog-content',
            html: this.options.message
        });
        var foot = new Element('div', {
            'class': 'godialog-foot'
        });
        var cancel = new Element('button', {
            'class': 'godialog-cancel',
            type: 'button',
            text: this.options.cancelText
        });
        cancel.addEvent('click', this.bound.hide);
        var ok = new Element('button', {
            'class': 'godialog-ok',
            type: 'button',
            text: this.options.goText
        });
        ok.addEvent('click', this.bound.go);
        wrapper.adopt(head, content, foot.adopt(ok, cancel));
        return this.element = wrapper;
    }
 
});
 
GoDialog.show = function(options) {
    return new GoDialog(options).show();
};
 
 
// Lihakoulun ajax
// var lihakoulu_content;
 
// window.addEvent('domready', function() {
//  lihakoulu_content = $('lihakoulu_contentarea');
//  
//  if(lihakoulu_content) {
//    lihakoulu_content.load('/lihakoulu_possu_etusivu');
//  }
// });
 
// function lihakouluLataaSisalto(loadPageName)  {
//  lihakoulu_content.load('/lihakoulu_possu_' + loadPageName);
// }
 
// Lautasmallit - Overlay
var imagepopup_vars = {
  dim: false,
  overlay: false,
  close: false,
  image: false,
  text: false
}
 
function imagePopup(img, title, text) {
  if(!imagepopup_vars.dim) {
    imagepopup_vars.dim = new Element('div', {id: 'dim'}).inject(document.body);
    imagepopup_vars.overlay = new Element('div', {id: 'overlay'}).inject(document.body);
    imagepopup_vars.close = new Element('a', {id: 'overlay-close', text: 'Sulje ikkuna'}).inject(imagepopup_vars.overlay);
    imagepopup_vars.image = new Element('img').inject(imagepopup_vars.overlay);
    imagepopup_vars.text = new Element('div').inject(imagepopup_vars.overlay);
    
    imagepopup_vars.dim.addEvent('click', function() {
      imagepopup_vars.overlay.fade('out');
      (function() { imagepopup_vars.dim.fade('out'); }).delay(250);
    });
    
    imagepopup_vars.close.addEvent('click', function() {
      imagepopup_vars.dim.fireEvent('click');
    });
    
    imagepopup_vars.dim.setStyle('opacity', 0);
    imagepopup_vars.overlay.setStyle('opacity', 0);
  }
  
  if(Browser.Engine.trident4) {
    imagepopup_vars.overlay.setStyle('top', document.documentElement.scrollTop + 350);
  }
  
  imagepopup_vars.image.src = '';
  imagepopup_vars.image.src = img;
  imagepopup_vars.text.empty();
  new Element('h1', {text: title}).inject(imagepopup_vars.text);
  new Element('p', {text: text}).inject(imagepopup_vars.text);
  
  imagepopup_vars.dim.fade(0.5);
  (function() { imagepopup_vars.overlay.fade('in'); }).delay(250);
}

