Cufon.set('forceHitArea', true);
Cufon.replace('#nav-main a', { fontFamily: 'Block Berthold', textShadow: '-1px -1px rgba(0, 0, 0, .75)', hover: true });
Cufon.replace('h1, .box h2, .box h3, li h3, .berthold, #nav-footer h3', { fontFamily: 'Block Berthold' });
Cufon.replace('.video-item h3', { fontFamily: 'Block Berthold' });
Cufon.replace('.btn span', { fontFamily: 'Block Berthold' });
Cufon.replace('ul.gda li', { fontFamily: 'Myriad Pro Condensed' });

try {
	document.execCommand('BackgroundImageCache', false, true);
}
catch(e) {}

$(function() {

	if (window.DD_belatedPNG) { /* ie6 only */
		DD_belatedPNG.fix('.icon');
		DD_belatedPNG.fix('body.front .section-third');
		DD_belatedPNG.fix('ul.news li');
	}

	$('#header .search .submit').click(function() {
		var form = $(this).parents('form:first');
		var query = $('[name=dig_query]', form);
		$(query).attr('disabled', $(query).hasClass('autoclear-default'));
		form.submit();
		$(query).attr('disabled', false);
	});

	/* Main navigation dropdown fading */
	$('#nav-main li.main').hover(function() {
		$('ul', this).fadeIn('fast');
	}, function() {
		$('ul', this).fadeOut('fast');	
	});

	/* Center main navigation dropdowns */
	$('#nav-main ul li:first-child a').each(function() {
		var main = $(this).parents('li.main:first');
		var ul = $(this).parents('ul:first');
		if (ul.width() < main.width())
			ul.css('left', (main.width() - ul.width()) / 2);
	});

	$('.keep-width').each(function() { $(this).width($(this).width()); });
	
	$('.video-item .inner').each(function() {
		var m = $('a[href*="youtube.com/watch?v="]', this).attr('href').match(/v=([^&]+)/);
		if (m && m.length > 1) {
			var youtube_id = m[1];
			var thumb = $('<div class="thumb"><img src="http://img.youtube.com/vi/' + youtube_id + '/0.jpg" alt="" /></div>')
				.prependTo(this.parentNode);
		}
	});

	$('hr').wrap('<div class="hr"></div>');
	
	$('.box > a:last-child').addClass('last-child');
	

	/* Tuotehaku */	
	
	$('form.tuotehaku .btn-dropdown').click(function() {
		var menu = $('#' + $(this).attr('id').replace('-select', '-menu'));
		if (menu.css('display') == 'block')
			Product_list.fetch();
		menu.slideToggle();
		menu.siblings('.menu').slideUp();
	});

	var select_tuoteryhma = function(li) {
		li.addClass('selected').siblings().removeClass('selected');
		var label = li.text();
		$('#tuoteryhma-select')
			[li.hasClass('default') ? 'removeClass' : 'addClass']('btn-dropdown-changed')
			.find('.inner').text(label.length > 18 ? label.substr(0, 17) + ' ..' : label);			
		Cufon.refresh('.btn span');
		$('#tuoteryhma-menu').slideUp();	
	}

	$('#tuoteryhma-menu li').click(function() {
		select_tuoteryhma($(this));
		Product_list.fetch();
	});
	
	$('#tuoteryhma-menu').each(function() {
		var m = window.location.href.match(/#ryhma\-(.+)/);
		/*if (m && m.length > 1) {
			$.cookie('product-query', null);
			var li = $('#tuoteryhma-' m[1].replace(/\-/g, '.'));
			select_tuoteryhma(li);
			return false;
		}*/
		var cookie = $.cookie('product-query');
		if (! cookie) return;
		var saved_search = cookie.substr(1).split('&');
		$.each(saved_search, function() {
			var pair = this.split('=');
			var key = pair[0].substr(pair[0].length - 2) == '[]' ? pair[0].substr(0, pair[0].length - 2) : pair[0];
			var val = decodeURIComponent(pair[1]);
			if (key == 'ingredient-filter' || key == 'spice-filter') {
				$('#' + key + ' li').each(function() {
					if ($.trim($(this).text()) == val) $(this).addClass('checked');
				});
			} else if (key == 'tuoteryhma') {
				var li = $('#tuoteryhma-' + val.replace(/\./g, '-'));
				if (li.length > 0) select_tuoteryhma(li);
			}
		});
		$('#ruokavalio-select')[$('#ruokavalio-menu li.checked').length > 0 ? 'addClass' : 'removeClass']('btn-dropdown-changed');
	});
	
	$('.nav-footer-products a').click(function() {
		
	});
	
	$('form.tuotehaku .paginator .prev, form.tuotehaku .paginator .next').click(function(e) {
		e.preventDefault();
		$(this).parents('.paginator:first').find('li.current')
			[$(this).hasClass('next') ? 'next' : 'prev']().find('a').click();
	});
	
	$('.btn-print').click(function(e) { e.preventDefault(); window.print(); });
	
	$('#ruokavalio-menu ul.filter li').click(function() {
		$(this).toggleClass('checked');
		$('#ruokavalio-select')[$('#ruokavalio-menu li.checked').length > 0 ? 'addClass' : 'removeClass']('btn-dropdown-changed');
		Product_list.fetch();
	});
	
	$('#ruokavalio-menu .select-all').toggle(function(e) {
		e.preventDefault();
		$(this).text('Tyhjennä').prev('ul').find('li').addClass('checked');
		Product_list.fetch();
	}, function(e) {
		e.preventDefault();
		$(this).text('Valitse kaikki').prev('ul').find('li').removeClass('checked');
		Product_list.fetch();
	});
	
	$('form.tuotehaku .clear').click(function() {
		$('form.tuotehaku .btn-dropdown').removeClass('btn-dropdown-changed');
		$('form.tuotehaku .sanahaku').val('').blur();
		$('#ruokavalio-menu .filter li').removeClass('checked');
		$('#tuoteryhma-menu li:first-child').click();
		$('#ruokavalio-menu').slideUp();
	});

	$('form.tuotehaku').submit(function() {
		Product_list.fetch();
		return false;
	}).submit();
	
	
	/* Reseptihaku */

	$('#reseptihaku-form .dropdown').hover(function() {
		$('.bubble', this).fadeIn();
	}, function() {
		$('.bubble', this).fadeOut();
	});

	$('#reseptihaku-form .dropdown .btn').click(function() {
		var menu = $('.menu', this.parentNode).slideToggle();
		$(this).parents('fieldset:first').find('.menu').not(menu).slideUp();
	});

	$('#reseptihaku-form .dropdown .menu li').click(function() {
		$(this.parentNode).slideUp('', function() {
			$('#reseptihaku-form').submit();
		});
		var dropdown = $(this).parents('.dropdown:first');
		var value = $.trim($(this).text());
		dropdown.find('.btn').addClass('btn-changed').find('.inner').text(value);
		dropdown.find('input[type=hidden]').val(value);
		Cufon.refresh('.btn span');
	});

	$('#reseptihaku-nav > li > a').click(function(e) {
		e.preventDefault();
		var ul = $('ul', this.parentNode);
		$(this.parentNode)[ul.css('display') == 'none' ? 'addClass' : 'removeClass']('open');
		$('#reseptihaku-nav ul:visible').not(ul).slideUp().parent().removeClass('open');
		ul.slideToggle();
	});

	/*$('#reseptihaku-form .clear').click(function(e) {
		e.preventDefault();		
		$(this).parents('form:first').submit();
	});*/
	

	/* Form input "autoclear" functionality */

	$('FORM .autoclear').focus(function () {
		if ($(this).hasClass('autoclear-default')) {
			$(this).removeClass('autoclear-default');
			$(this).addClass('autoclear-edited');
			$(this).val('');
		}
	}).blur(function () {
		if ($(this).val() == '') {
			$(this).addClass('autoclear-default');
			$(this).removeClass('autoclear-edited');
			$(this).val($(this).attr('default_value'));
		}
	}).each(function() {
		$(this).attr('default_value', $(this).val());	
	});

		
	var rate_form = $('#document.page-resepti form.rate');
	$('.big-stars', rate_form).mousemove(function(e) {
		if (! rate_form.hasClass('rated') && ! rate_form.hasClass('busy')) {
			var r = parseInt((e.pageX - $(this).offset().left) / 18 + 1);
			this.className = this.className.replace(/big\-stars\-[0-9]/g, '') + ' big-stars-' + r;
		}
	}).mouseout(function() {
		if (! rate_form.hasClass('rated') && ! rate_form.hasClass('busy')) {
			this.className = this.className.replace(/big\-stars\-[0-9]/g, '')
				+ ' big-stars-' + $.trim($(this).text());
		}
	}).click(function() {
		if (! rate_form.hasClass('rated') && ! rate_form.hasClass('busy')) {
			rate_form.addClass('busy');
			var that = this;
			var m = this.className.match(/big\-stars\-([0-9])/)
			if (m && m.length > 1) $('[name=q1]', rate_form).val(m[1]);
			$.post(rate_form.attr('action'), rate_form.serialize(), function(data, status) {
				var rated_ids = ($.cookie('reseptiarvostelut') || '') + $('[name=q0]', rate_form).val() + ' ';
				$.cookie('reseptiarvostelut', rated_ids, { expires: 1, path: '/' });
				var bubble = $('.bubble', this.parentNode).fadeIn();
				window.setTimeout(function() {
					bubble.fadeOut(1500, function() {
						that.className = that.className.replace(/big\-stars\-[0-9]/g, '')
							+ ' big-stars-' + $.trim(data).substr(0, 1);
						rate_form.addClass('rated');
						rate_form.removeClass('busy');
					});
				}, 3000);
			})
		}
	});

	var comment_form = $('#resepti-comment-form').submit(function() {
		var f = $(this);
		if (f.hasClass('busy')) return false;
		f.addClass('busy');
		setTimeout(function() { f.removeClass('busy') }, 2000);  // prevent double-posting
		var params = { ngform_on: 1 };
		$(':input', f).each(function() {
			if (! $(this).hasClass('autoclear-defaultx'))
				params[$(this).attr('name')] = $(this).val();
		});
		var container = $('<div/>');
		container.load(f.attr('action') + ' #content', params, function(html, status) {
			var li = $('.comments li.new', container).appendTo('.comments ul');
			var new_form = $('#resepti-comment-form', container);
			$.each(['img.captcha', 'input.captcha', '[name=ngform_fid]', '[name=ngf_signature]'], function(i, selector) {
				$(selector, f).replaceWith($(selector, new_form));
			});
			if (li.length > 0) {
				$('.subject, .comment, input.captcha', f).val('');
				var count = $('.comments h4 .count .number');
				count.text(parseInt(count.text()) + 1);
				$.scrollTo(li, 1000);
			} else {
				alert('Tarkista että täytit kaikki kentät ja syötit varmistuskoodin oikein.');
				$(':input[value=""], .autoclear-default:input', f).eq(0).focus();
			}
		});
	}).find('.submit').click(function(e) { e.preventDefault(); comment_form.submit() });


	// Form input "autoclear" functionality
	$('form .autoclear').focus(function () {
		if ($(this).hasClass('autoclear-default')) {
			$(this).removeClass('autoclear-default');
			$(this).addClass('autoclear-edited');
			$(this).val('');
		}
	}).blur(function () {
		if ($(this).val() == '') {
			$(this).addClass('autoclear-default');
			$(this).removeClass('autoclear-edited');
			$(this).val($(this).attr('default_value'));
		}
	}).each(function() {
		$(this).attr('default_value', $(this).val());	
	});
	
	
	$('.faq-section .header').click(function() {
		var faq = $(this.parentNode);
		if (! faq.hasClass('faq-open')) {
			faq.addClass('faq-open');
			var ul = faq.find('ul').slideDown();
			faq.siblings('.faq-section').removeClass('faq-open');
			$('.faq-section ul').not(ul).slideUp();
		} else {
			faq.removeClass('faq-open');
			var ul = faq.find('ul').slideUp();
		}
	});
	
	$('.faq-section .read-more').click(function() {
		$('.answer', this.parentNode).toggle();
		$(this).toggleClass('open').text($(this).hasClass('open') ? 'Sulje' : 'Lue lisää');
	});
	

	$('#faq-form .categories li').click(function() {
		$(this).addClass('selected').siblings().removeClass('selected');
		$(this).parents('form:first').find('input.category').val($('strong', this).text().toLowerCase());
	});
	

	$('form.ajax').submit(function() {
		var f = $(this);
		if (f.hasClass('busy')) return false;
		$('.required', f).each(function() {
			if ($(this).val() == '' || $(this).hasClass('autoclear-default')) {
				$(this).addClass('invalid');
				alert('Ole hyvä ja täytä kaikki pakolliset kentät.');
				$(this).focus();
				return false;
			} else { $(this).removeClass('invalid') }
		});
		if ($('.invalid', f).length == 0) {
			f.addClass('busy');
			var success = function(text, status) {
				f.removeClass('busy');
				if ($.trim(text) == 'FORM SAVED') {
					var saved = $('.saved', f).fadeIn();
					setTimeout(function() { saved.fadeOut() }, 10000);
					$('[type=text], textarea', f).val('').blur();
				} else {
					alert('Tarkista, että täytit pakolliset kentät ja syötit sähköpostiosoitteesi oikein.');
					$('.email', f).focus();
				}
			}
			if ($('[type=file]', f).length > 0) {
				f.ajaxSubmit(success);
			} else {
				$.post(f.attr('action'), f.serialize() + '&ngform_on=1', success);
			}
		}
		return false;
	});


	$('#feedback-form .tabs span').click(function() {
		$(this.parentNode).addClass('selected')
			.siblings().removeClass('selected');
	});
	
	$('#feedback-form .contact label').click(function() {
		$(this).addClass('selected')
			.siblings().removeClass('selected');
	});

	/* Open youtube videos into popup */	
	$('a[href^="http://www.youtube.com/watch"]').click(function(e) {
		e.preventDefault();
		var m = $(this).attr('href').match(/\?v=([^&]+)/);
		if (m && m.length >= 2)
			play_youtube(m[1]);
	});
	/* Automatically open the video if corresponding anchor given */
	var m = window.location.href.match('#video\-[0-9]+');
	if (m) $(m[0]).find('a[href^="http://www.youtube.com/watch"]:first').click();

	
	$('form.kilpailu').submit(function() {
		var errors = false;
		$('fieldset.question', this).each(function() {
			if ($('input[type=radio]:checked', this).length == 0) {
				alert('Ole hyvä ja valitse yksi vastaus jokaiseen kysymykseen.');
				errors = true;
				return false;
			}
		});
		if (errors) return false;
		$('input[type=text]', this).each(function() {
			if ($(this).val() == '') {
				alert('Ole hyvä ja täytä kaikki kentät.');
				$(this).focus();
				errors = true;
				return false;
			}
		});
		return ! errors;
	});
	
	$('#reseptihaku-adv-form li').click(function() {
		$(this).toggleClass('checked');
		$('input', this).attr('checked', $(this).hasClass('checked'));
	}).each(function() {
		if ($('input:checked', this).length > 0) $(this).addClass('checked');
	});

	$('#reseptihaku-adv-form .btn-clear').click(function(e) {
		e.preventDefault();
		$(this).parents('form:first').find('li.checked').click();
	});

	$('#reseptihaku-adv-form .btn-submit').click(function(e) {
		e.preventDefault();
		$(this).parents('form:first').submit();
	});

});


Product_list = {};  // namespace for product list related functions

Product_list.fetch = function() {
	var viewport = $('#tuotehaku-results-viewport').addClass('loading');
	var query = Product_list.build_query();
	$.cookie('product-query', query);
	$('#tuotehaku-results').load($('form.tuotehaku').attr('action') + query, null, function() {
		viewport.removeClass('loading');
		Product_list.update_paginator();
	});
}

Product_list.build_query = function() {
	var params = [];
	params.push('tuoteryhma=' + encodeURIComponent($('#tuoteryhma-menu li.selected').attr('id').replace(/^tuoteryhma\-/, '').replace(/\-/g, '.')));
	params.push('sana=' + encodeURIComponent($('form.tuotehaku .sanahaku').val().replace('Sanahaku', '')));
	$('#ruokavalio-menu .filter .checked').each(function() {
		params.push($(this.parentNode).attr('id') + '[]=' + encodeURIComponent($.trim($(this).text())));
	});
	return '?' + params.join('&');
}

Product_list.change_page = function(pagenum, skip_animation) {
	var height = 540; //$('#tuotehaku-results-viewport').innerHeight();
	var new_margin = (pagenum - 1) * height * -1;
	var li = $('form.tuotehaku .paginator a[href$="#sivu-' + pagenum + '"]').parent()
		.addClass('current').siblings().removeClass('current');
	if (li.length == 0) return false;
	if (skip_animation) {
		$('#tuotehaku-results').css('marginTop', new_margin);
	} else {
		$('#tuotehaku-results').animate(
			{ marginTop: new_margin },
			{ duration: 1000, easing: 'easeInOutQuad' }
		);
	}
}

Product_list.update_paginator = function() {
	var ul = $('form.tuotehaku .paginator ul').empty();
	var pages = Math.ceil($('#tuotehaku-results li').length / 15);
	for (var i = 1; i <= pages; i++) {
		var a = $('<li><a href="#sivu-' + i + '">' + i + '</a></li>')
			.appendTo(ul)
			.addClass(i == 1 ? 'current' : '')
			.find('a').click(function(e) {
				Product_list.change_page(parseInt($(this).text()))
			});
	}
	ul.parent().show();
	Product_list.sync_with_url();
}

Product_list.sync_with_url = function() {
	var m = window.location.href.match(/#sivu\-([0-9]+)/);
	if (m && m.length > 1) {
		Product_list.change_page(m[1], true);
	}
}

function debug(obj) {
	if ($('body').hasClass('debug')) {
		if (window.console) console.log(obj);
		else alert(obj);
	}
}

function play_youtube(video_id) {
	var popup = $('<div><object width="640" height="505"><param name="movie" value="http://www.youtube.com/v/' + video_id + '&hl=en&fs=1&"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/' + video_id + '&hl=en&fs=1&" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="505"></embed></object></div>');
	$('<a href="#sulje">Sulje</a>').click(function(e) {
		e.preventDefault();
		$(this.parentNode).remove();
	}).prependTo(popup).addClass('close');
	popup.addClass('video-popup').prependTo('body').css('visibility', 'hidden');
	popup.css('left', ($(document).width() - popup.outerWidth()) / 2)
		.css('top', ($(window).height() - popup.outerHeight()) / 2)
		.hide().css('visibility', 'visible').show();
}

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie=function(a,b,c){if(typeof b!='undefined'){c=c||{};if(b===null){b='';c.expires=-1}var d='';if(c.expires&&(typeof c.expires=='number'||c.expires.toUTCString)){var e;if(typeof c.expires=='number'){e=new Date();e.setTime(e.getTime()+(c.expires*24*60*60*1000))}else{e=c.expires}d='; expires='+e.toUTCString()}var f=c.path?'; path='+(c.path):'';var g=c.domain?'; domain='+(c.domain):'';var h=c.secure?'; secure':'';document.cookie=[a,'=',encodeURIComponent(b),d,f,g,h].join('')}else{var j=null;if(document.cookie&&document.cookie!=''){var k=document.cookie.split(';');for(var i=0;i<k.length;i++){var l=jQuery.trim(k[i]);if(l.substring(0,a.length+1)==(a+'=')){j=decodeURIComponent(l.substring(a.length+1));break}}}return j}};

/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);
