var smallBorder = RUZEE.ShadedBorder.create({ corner:12, shadow:0, border:2, edges:'tbr' }); // 
var rightBlock  = RUZEE.ShadedBorder.create({ corner:16, shadow:0, border:0, edges:'tbl' }); // 
var leftBlock   = RUZEE.ShadedBorder.create({ corner:16, shadow:0, border:0, edges:'tbr' }); // 
var popupBorder = RUZEE.ShadedBorder.create({ corner:20, shadow:0, border:6, edges:'tbrl', borderOpacity:0.3});

var flashvars = {path: '/flash/videos/'};
var params = {wmode: 'opaque'};
var attributes = {};

try {
  document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}

$(function() {

	
/*  -------------------------------------------------------------------
	Document Ready ---------------------------------------------------- */
	// FAQ collapse
	$('dt').prepend('<div></div>').addClass('close').css('cursor', 'pointer').toggle(
		function () { $(this).removeClass('close').addClass('open').next('dd').show(); redrawCorner(); },
		function () { $(this).removeClass('open').addClass('close').next('dd').hide(); redrawCorner(); }
	).bind('mouseover', function () {$(this).addClass('hover')})
	 .bind('mouseout', function () {$(this).removeClass('hover')});
	$('dd').hide();

	// Rounded Corder
	smallBorder.render($('div.subcontent, div.faq-section, div.block'));
	rightBlock.render($('#contact, div.content-block.right-block'));
	leftBlock.render($('div.content-block', '#home-know, #home-forum'));
	leftBlock.render($('#form-wrap'));

	// Custom checkbox
	$('#frm_step3 :checkbox')
		.bind('focus.cssized', function () { $(this).parent().addClass('focus'); })
		.bind('blur.cssized',  function () { $(this).parent().removeClass('focus'); })
		.bind('click.cssized', function () { $(this).parent().toggleClass('selected'); })
		.parent('label')
			.addClass('cssized')
			.bind('mouseover.cssized', function () { $(this).addClass('focus'); })
			.bind('mouseout.cssized',  function () { $(this).removeClass('focus'); })
		.end().filter(':checked').parent().addClass('selected'); /**/

	// Rollover on table row & Stripe table
	$("#content tbody tr")
		.hover(function(){ $(this).addClass("hover"); },
			   function(){ $(this).removeClass("hover"); })
		.filter(':odd').addClass("odd");

	// Rollover on button
	$("input:image")
        .bind('mouseover focus', function(){this.src = this.src.replace(/(?:_o)?\.([a-z]*)$/i,"_o.$1"); })
	    .bind('mouseout blur',   function(){this.src = this.src.replace(/_o\./i,".");});

	// External link in popup
	$('a[@rel=external]')
		.click(function(){
			pageTracker._trackPageview('/external/'+this.href);
			return !window.open(this.href);
		})
		.attr('title', 'will open in new window');
	
	
/*  -------------------------------------------------------------------
    Utilities --------------------------------------------------------- */
	$("#backtop").click(function(){
		window.scroll(0,0);
		return false;
	});

	$('#share').addClass('show').hover (
		function () { $('ul', this).show() },
		function () { $('ul', this).hide() }
	).find('a').bind("click", function(event){
		event.preventDefault();
		var size, which = $(this).attr("id").replace('b_', '');
		switch (which) {
			case 'facebook': size = "width=620,height=436"; break;
			case 'delicious': size = "width=725,height=400"; break;
			case 'digg': size = "width=962,height=500"; break;
			default: size = "width=500,height=500";
		}
		pageTracker._trackPageview('/share/'+which);
		var my_popup = window.open($(this).attr("href"), "share_"+which, "scrollbars=yes,resizable=yes,toolbar=no,location=no,status=no,"+size);
		if (my_popup) {my_popup.focus();}
		return !my_popup;
	});
	
	$('#b_print').css('display', 'block');


/*  -------------------------------------------------------------------
	Demo -------------------------------------------------------------- */
	$('a[@href^=/demo/]').click(function () {
		var url = $(this).attr('href');
		pageTracker._trackPageview(url);
		pageTracker._trackPageview('/producteducation');
		
		// We want to prevent the popup for firefox II Mac
		if (($.browser.mozilla && mua('Firefox')) &&
			(mua('MacPPC') || mua('Mac68K') || mua('macintosh')) &&
			($.browser.version.substr(0,3) <= 1.8)
		) {
			return true;
		}
			
		$.ajax({
			type: "POST",
			url: url,
			data: {isAjax: true},
			success: function(resp){
				$popin = createPopin(resp);
				var flashvars = {
					path: '/flash/videos/'
					//,test_drive_actif: true
				};
				swfobject.embedSWF("/flash/demo_player.swf", "video_wrap", "780", "440", "9.0.0", null, flashvars, {wmode: 'transparent'}, attributes);
				
			},
			error: function(req) { }
		});
		return false;
	});
	

/*  -------------------------------------------------------------------
    Forms ------------------------------------------------------------- */
	// Generic
	$("form.frm_testdrive").formHandling({ ajax: false });
	$("#frm_contact, #frm_stf").formHandling();

	$('#frm_signup').formHandling({
		invalidMsg: 'Looks like you\'re email address is missing or is not valid. Please try again.',
		ajaxSuccess: function (resp, $form) {createPopin(resp.msg);}
	})

	// Popins (stf)
	$('#b_stf').click(function () {
		pageTracker._trackPageview('/stf');
		$.ajax({
			type: "POST",
			url: $(this).attr('href'),
			data: {
				stfPath: encodeURIComponent(location.href),
				isAjax: true
			},
			success: function(resp){
				
				$popin = createPopin_stf(resp);
				
				//Form handling
				$("form", $popin).formHandling({
					contentHandler: 'div.popin_content',
					formContainer: '#stf',
					extraData: 'path='+location.href
				});

				// Rollover on button
				$("input:image", $popin)
			        .bind('mouseover focus', function(){this.src = this.src.replace(/(?:_o)?\.([a-z]*)$/i,"_o.$1"); })
    			    .bind('mouseout blur',   function(){this.src = this.src.replace(/_o\./i,".");});
			},
			error: function(req) { }
		});
		return false;
	});

	// Software Updates 
	$('.b_update').click(function () {
		pageTracker._trackPageview('/update');
		$.ajax({
			url: $(this).attr('href'),
			data: {
				updatePath: encodeURIComponent(location.href),
				isAjax: true
			},
			success: function(resp){
				
				$popin = createPopin(resp);

			},
			error: function(req) { }
		});
		return false;
	});
	
	
/*  -------------------------------------------------------------------
	Test Drive -------------------------------------------------------- */	
	$('#timezone').bind('change', function () {
		//console.log('change');
		var date = new Date();
		$.getScript(
			'/testdrive/javascriptDatesArray/timezone/'+ $('#timezone').val(),
			function () 
			{
				var firstYear  = null;
				var firstMonth = null;
				var firstDay   = null;
				
				for (var i in special_days)
				{
					firstYear = i;
					
					for (var j in special_days[firstYear])
					{
						firstMonth = j;
						firstDay = special_days[firstYear][firstMonth][0];
						break;
					}
				}
				
	      if (firstYear && firstMonth && firstDay) 
	      {
	        date = new Date(firstYear,firstMonth,firstDay);
	      }
	      
				$('#date').val(date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate());
				$('.calendar').remove();
				
				Calendar.setup(
				{
		      ifFormat       : "%Y-%m-%d",
		      daFormat       : "%Y-%m-%d",
				  flat           : "calendar-container", 
				  date           : date,
				  flatCallback   : dateChanged,
				  dateStatusFunc : dateStatusHandler,
				  weekNumbers    : false,
				  range          : [date.getFullYear(), date.getFullYear()+1]
				});
			    
	      var fakeCalendar         = new Object();
	      fakeCalendar.dateClicked = true;
	      var dateArr              = $('#date').val().split('-');
	      
	      if (dateArr.length == 3) 
	      {
					fakeCalendar.date = new Date(dateArr[0],dateArr[1]-1,dateArr[2]);
					dateChanged(fakeCalendar);
	      }
	      
				$('#time_slot_id').empty().append('<option value="">Choose a day first</option>');	
			});
	});
	$('#b_reload_captcha').click(function () {
		var now = new Date();
		$('#cryptogram').attr('src', $('#cryptogram').attr('src').replace(/(\?\d+)?$/, '?'+now.getTime()));
		return false;
	})
	$('#b_nocode').click( function () {
		$('#code_info').show();
		return false;
	});
	
	
/*  -------------------------------------------------------------------
	Survey ------------------------------------------------------------ */	
	$('#frm_survey div.survey_comment textarea')
		.hide()
		.siblings('label')
			.addClass('toggler')
			.hover(
				function () { $(this).addClass('hover') },
				function () { $(this).removeClass('hover') }
			)
			.click(function () {
				$(this).siblings('textarea').toggle();
			});
	
	$('#frm_survey div.survey_custom').hide();
	$('#survey_q_6_24').click(function () {
		$('#frm_survey div.survey_custom').show();
	})
	$('#survey_q_6_25').click(function () {
		$('#frm_survey div.survey_custom').hide();
	})
	
	
	/*Contest Optin*/
	$("input#optin_contest").bind("click", function(){
		$("#survey_contactinfo").toggle();
	});
	
	
	$('#frm_survey').submit(function () {
		// Reset
		var error  = 0;
		$('#survey_errors', this).remove();
		$('strong.error', this).removeClass('error');
		$('label.error', this).removeClass('error');
		
		// Get errors
		var sError = '';
		$('ul.v-mandatory', this).each( function () {
			if (!$(':checked', this).size()) {
				$(this).siblings('div').children('strong').addClass('error');
				var target = '#' + $(this).parent().attr('id');//$('input', this).slice(0,1).attr('id');
				var question = $(this).siblings('div').children('strong').html();
				sError += '<li><small><a href="' + target + '">' + question + '</a></small></li>';
				error++;
			}
		});
		if (error>0) {
			sError = '<p>Oops! These questions are mandatory:</p><ul>' 
				+ sError 
				+ '</ul>';
		}
		
		optin_contest = document.getElementById("optin_contest");
		if(!optin_contest.checked){
			//add contest validation
			var country = $('input#rovio_subscription_country','#frm_survey').val();
			var sContestError = '';
			if (country == 'US' || country == 'CA') {
				first_name = $('input#rovio_subscription_first_name','#frm_survey').val();
				if (first_name.length == 0) {
					sContestError += '<li>First Name is a mandatory field</li>';
					$('label[@for="rovio_subscription_first_name"]','#frm_survey').addClass('error');
				}
				last_name = $('input#rovio_subscription_last_name','#frm_survey').val();
				if (first_name.length == 0) {
					sContestError += '<li>Last Name is a mandatory field</li>';
					$('label[@for="rovio_subscription_last_name"]','#frm_survey').addClass('error');
				}
				address1 = $('input#rovio_subscription_address1','#frm_survey').val();
				if (address1.length == 0) {
					sContestError += '<li>Address is a mandatory field</li>';
					$('label[@for="rovio_subscription_address1"]','#frm_survey').addClass('error');
				}
				city = $('input#rovio_subscription_city','#frm_survey').val();
				if (city.length == 0) {
					sContestError += '<li>City is a mandatory field</li>';
					$('label[@for="rovio_subscription_city"]','#frm_survey').addClass('error');
				}
				state_province = $(':input#rovio_subscription_state_province','#frm_survey').val();
				if (state_province == null || state_province == 0 || state_province.length == 0) {
					sContestError += '<li>State / Province is a mandatory field</li>';
					$('label[@for="rovio_subscription_state_province"]','#frm_survey').addClass('error');
				}
	
				zippostalcode = $('input#rovio_subscription_zip_postal','#frm_survey').val();
				if (zippostalcode.length == 0) {
					sContestError += '<li>Zip / Postal code is a mandatory field</li>';
					$('label[@for="rovio_subscription_zip_postal"]','#frm_survey').addClass('error');
				}
	
				phone1 = $('input#rovio_subscription_phone1','#frm_survey').val();
				phone2 = $('input#rovio_subscription_phone2','#frm_survey').val();
				if (phone1.length == 0 || phone2.length == 0) {
					sContestError += '<li>Phone number is a mandatory field</li>';
					$('label[@for="rovio_subscription_phone"]','#frm_survey').addClass('error');
				}
				if (sContestError.length > 0) {
					sError += '<p>Oops! These fields are mandatory:</p><ul>' + sContestError + '</ul>';
					error++;
				}
			}
		}
		
		if (error) {
			$('div.actions', this).before('<div class="error" id="survey_errors">' + sError + '</div>');
			return false;
		}
		
	});
	
	
/*  -------------------------------------------------------------------
    Gallery ----------------------------------------------------------- */
	ajaxGalleryNavigation();
	
	$('#gallery-download a').click(function () {
		which = $(this).attr("id").replace('b_', '');
		var size = {hires : 'width=1024,height=790', lowres:'width=310,height=240'}; 
		var my_popup = window.open($(this).attr("href"), "share_"+which, "scrollbars=yes,resizable=yes,toolbar=no,location=no,status=no,"+size[which]);
		if (my_popup) {my_popup.focus(); return false;}
	})

	
/*  -------------------------------------------------------------------
	Waiting page ------------------------------------------------------ */
	$('#count_down').each( function () {
		window.setTimeout(updateCounter, 200);
		var now = new Date();
		var end = now.getTime() + $('.delay_sec', this).html() * 1000;
		$(this).data('end_at', end);
	});
	
	//checkCanWait Ajax in waiting page
	$("span.checkurl","#count_down").each(function () {
		window.setTimeout(checkTestDrive, 5*60*1000);
	});

	// IE6 fix  
	redrawCorner();

	if (swfobject.hasFlashPlayerVersion('9.0.0')) {
		$('#features #content-head').remove();
	}
});


/*  -------------------------------------------------------------------
	Title Replacement - SIFR 3 ---------------------------------------- */
	var header = {src: '/js/meetrovio.swf'};
	
	sIFR.activate(header); // From revision 209 and onwards
	
	sIFR.replace(header, {
	  selector: '.sifr',
	  wmode: "transparent",
	  css: [
		'.sIFR-root {color: #FFFFFF; font-weight: normal; text-transform: uppercase; leading: -7; letter-spacing: 1;}',
		'.rovio {color: #56A4C0; leading: 0;}',
		'.right {text-align: right;}',
		'.trade {font-size: 22px;}',
		'.small {font-size: 86px;}'
	  ]
	});


/*  -------------------------------------------------------------------
	SWFObject 2.1 ----------------------------------------------------- */
	swfobject.embedSWF("/flash/head_home.swf", "swf_home", "985", "482", "9.0.0", null, flashvars, params, attributes);
	swfobject.embedSWF("/flash/tech_spec.swf", "size_wrap", "540", "390", "9.0.0", null, flashvars, params, attributes);
	swfobject.embedSWF("/flash/features.swf", "swf_features", "985", "820", "9.0.0", null, flashvars, params, attributes);


/*  -------------------------------------------------------------------
	Popin ------------------------------------------------------------- */
	function createPopin (html) {
		// Hover background
		var $bgcover = $('<div id="bgcover">&nbsp;</div>').appendTo('body');
		$bgcover.css({
			height: Math.max($('body').height(), $bgcover.height()),
			opacity: '0.90'
		});
	
		//Popin, center, corner and border, focus
		var $popin = $(html).appendTo('body');
		popupBorder.render($('.popin_wrap_test', $popin));
		$popin.animate({top: getCenteredPos($popin.height())}, 1200, 'backout', function () {
			$('input, select, textarea', $popin).slice(0,1).focus();
		});
		
		return $popin;
	}
	
	function createPopin_stf (html) {
		// Hover background
		var $bgcover = $('<div id="bgcover">&nbsp;</div>').appendTo('body');
		$bgcover.css({
			height: Math.max($('body').height(), $bgcover.height()),
			opacity: '0.90'
		});
	
		//Popin, center, corner and border, focus
		var $popin = $(html).appendTo('body');
		popupBorder.render($('.popin_wrap', $popin));
		$popin.animate({top: getCenteredPos($popin.height())}, 1200, 'backout', function () {
			$('input, select, textarea', $popin).slice(0,1).focus();
		});
		
		return $popin;
	}
		
	function closePopin(){
		var popin = $('div.popin').get(0);
		$('#bgcover, div.popin-content, div.popin a').remove(); // unbind events, avoid memory leak
		popin.parentNode.removeChild(popin); // 1113 div for the border, too much for jQuery
	}
	
	function getCenteredPos(objheight){
		var ScrollTop = document.body.scrollTop;
		if (ScrollTop == 0){
			if (window.pageYOffset){
				ScrollTop = window.pageYOffset;
			}else{
				ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
			}
		}
	
		var myHeight = 0;
		if( typeof( window.innerWidth ) == 'number' ) {
			//Non-IE
			myHeight = window.innerHeight;
		} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
			//IE 6+ in 'standards compliant mode'
			myHeight = document.documentElement.clientHeight;
		} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
			//IE 4 compatible
			myHeight = document.body.clientHeight;
		}
		
		return ScrollTop + (myHeight/2)-(objheight/2);
	}
	
	
/*  -------------------------------------------------------------------
	StF --------------------------------------------------------------- */
	function addFriend() {
		var $fieldsets = $('fieldset.info_friends');
		var count = $fieldsets.size() + 1;
		var $newFriend = $fieldsets.slice(0,1).clone();
		
			$('label',$newFriend).removeClass('error'); //remove error class if any 
			$newFriend.prepend('<a class="b_removefriend" href="" onclick="removeFriend(this); return false;">Remove this friend</a>');
		$('label', $newFriend).each(function() {
			$(this).attr('for', $(this).attr('for')+'_'+count)
			       .find('span').remove();
		});
		$('input', $newFriend).each(function() {
			$(this).attr('id', $(this).attr('id')+'_'+count)
				   .removeClass('v-mandatory')
				   .val('');
		});
		$('#addfriends').before($newFriend);
	}
	
	function removeFriend(el) {
		$(el).parent('fieldset').remove();
	}


/*  -------------------------------------------------------------------
	Page Specifics ---------------------------------------------------- */
	function ajaxGalleryNavigation() {
		$('#b_next_item, #b_prev_item, #gallery-paging a').click(function() {
			$.ajax({
				type: "POST",
				url: $(this).attr('href'),
				data: {isAjax: true},
				success: function(resp){
					$('#gallery-selector, #gallery-paging').remove();
					$('#gallery-nav').append($(resp));
					ajaxGalleryNavigation();
				},
				error: function(req){
				}
			});
			return false;
		});
	}

	function dateChanged(calendar) {
		// Beware that this function is called even if the end-user only
		// changed the month/year.  In order to determine if a date was
		// clicked you can use the dateClicked property of the calendar:
		if (calendar.dateClicked) {
		  var y = calendar.date.getFullYear();
		  var m = calendar.date.getMonth()+1;   // integer, 1..12
		  var d = calendar.date.getDate();      // integer, 1..31
		  
		  $('#date').val(y+"-"+m+"-"+d);
		  
		  $.ajax({
				type: "POST",
				url: '/testdrive/timeSelectTag',
				data: {
					timezone: $('#timezone').val(),
					date: $('#date').val()
				},
				success: function(resp){
					$('#time_slot_id').empty().append($('option', resp)).val('');
				}
		   });
		}
	}
	
	function updateCounter() {
		var now   = new Date();
		var end   = $('#count_down').data('end_at');
		var delay = Math.round((end - now.getTime())/1000);
		if (delay <= 0) {
			
			if ($('#count_down .url').html() && $('#count_down .url').html() != '') {
				location.href = $('#count_down .url').html();
				return;
			} 
		}
		
		window.setTimeout(updateCounter, 200);
		var hours   = Math.floor(delay/3600);
		var minutes = Math.floor((delay % 3600)/60);
		var seconds = delay % 60;
		if (hours   < 10) {hours   = '0' + hours;}
		if (minutes < 10) {minutes = '0' + minutes;}
		if (seconds < 10) {seconds = '0' + seconds;}
		
		var timer = hours+':'+minutes+'.'+seconds;
		
		if ($('#count_down .counter').html() != timer) {
			$('#count_down .counter').html(timer);
		}
		
	}
	
	$.easing.backout = function(x, t, b, c, d){
		var s=1.20158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	};

	function checkTestDrive() {
		var checkUrl = $("span.checkurl","#count_down").html();
		//ajax call with
		$.ajax({
			type: "GET",
			url: checkUrl,
			//data: {isAjax: true},
			success: function(resp){
				if (resp == '') {
					location.href = location.href;
				} 
			},
			error: function(req){
			}
		});
		window.setTimeout(checkTestDrive, 5*60*1000);
		//return false;
		
	}

	
	function mua(s) {
		var ua = navigator.userAgent.toLowerCase();
		return (ua.indexOf(s.toLowerCase()) > -1);
	}


/*  -------------------------------------------------------------
    IE 6 Fix ----------------------------------------------------
	This function fix the odd/even size trouble under IE6 ------- */
	function redrawCorner () {
		if($.browser.msie && ($.browser.version<7)){
			$("div.corner.bottom").each(function(){
				if ($(this).parent().height()%2) { $(this).css("bottom", "-1px");/* alert('resize');*/}
				else { $(this).css("bottom", "0"); }
			});
			$('div.corner').hide().show();
		}
	}var smallBorder = RUZEE.ShadedBorder.create({ corner:12, shadow:0, border:2, edges:'tbr' }); // 
var rightBlock  = RUZEE.ShadedBorder.create({ corner:16, shadow:0, border:0, edges:'tbl' }); // 
var leftBlock   = RUZEE.ShadedBorder.create({ corner:16, shadow:0, border:0, edges:'tbr' }); // 
var popupBorder = RUZEE.ShadedBorder.create({ corner:20, shadow:0, border:6, edges:'tbrl', borderOpacity:0.3});

var flashvars = {path: '/flash/videos/'};
var params = {wmode: 'opaque'};
var attributes = {};

try {
  document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}

$(function() {

	
/*  -------------------------------------------------------------------
	Document Ready ---------------------------------------------------- */
	// FAQ collapse
	$('dt').prepend('<div></div>').addClass('close').css('cursor', 'pointer').toggle(
		function () { $(this).removeClass('close').addClass('open').next('dd').show(); redrawCorner(); },
		function () { $(this).removeClass('open').addClass('close').next('dd').hide(); redrawCorner(); }
	).bind('mouseover', function () {$(this).addClass('hover')})
	 .bind('mouseout', function () {$(this).removeClass('hover')});
	$('dd').hide();

	// Rounded Corder
	smallBorder.render($('div.subcontent, div.faq-section, div.block'));
	rightBlock.render($('#contact, div.content-block.right-block'));
	leftBlock.render($('div.content-block', '#home-know, #home-forum'));
	leftBlock.render($('#form-wrap'));

	// Custom checkbox
	$('#frm_step3 :checkbox')
		.bind('focus.cssized', function () { $(this).parent().addClass('focus'); })
		.bind('blur.cssized',  function () { $(this).parent().removeClass('focus'); })
		.bind('click.cssized', function () { $(this).parent().toggleClass('selected'); })
		.parent('label')
			.addClass('cssized')
			.bind('mouseover.cssized', function () { $(this).addClass('focus'); })
			.bind('mouseout.cssized',  function () { $(this).removeClass('focus'); })
		.end().filter(':checked').parent().addClass('selected'); /**/

	// Rollover on table row & Stripe table
	$("#content tbody tr")
		.hover(function(){ $(this).addClass("hover"); },
			   function(){ $(this).removeClass("hover"); })
		.filter(':odd').addClass("odd");

	// Rollover on button
	$("input:image")
        .bind('mouseover focus', function(){this.src = this.src.replace(/(?:_o)?\.([a-z]*)$/i,"_o.$1"); })
	    .bind('mouseout blur',   function(){this.src = this.src.replace(/_o\./i,".");});

	// External link in popup
	$('a[@rel=external]')
		.click(function(){
			pageTracker._trackPageview('/external/'+this.href);
			return !window.open(this.href);
		})
		.attr('title', 'will open in new window');
	
	
/*  -------------------------------------------------------------------
    Utilities --------------------------------------------------------- */
	$("#backtop").click(function(){
		window.scroll(0,0);
		return false;
	});

	$('#share').addClass('show').hover (
		function () { $('ul', this).show() },
		function () { $('ul', this).hide() }
	).find('a').bind("click", function(event){
		event.preventDefault();
		var size, which = $(this).attr("id").replace('b_', '');
		switch (which) {
			case 'facebook': size = "width=620,height=436"; break;
			case 'delicious': size = "width=725,height=400"; break;
			case 'digg': size = "width=962,height=500"; break;
			default: size = "width=500,height=500";
		}
		pageTracker._trackPageview('/share/'+which);
		var my_popup = window.open($(this).attr("href"), "share_"+which, "scrollbars=yes,resizable=yes,toolbar=no,location=no,status=no,"+size);
		if (my_popup) {my_popup.focus();}
		return !my_popup;
	});
	
	$('#b_print').css('display', 'block');


/*  -------------------------------------------------------------------
	Demo -------------------------------------------------------------- */
	$('a[@href^=/demo/]').click(function () {
		var url = $(this).attr('href');
		pageTracker._trackPageview(url);
		pageTracker._trackPageview('/producteducation');
		
		// We want to prevent the popup for firefox II Mac
		if (($.browser.mozilla && mua('Firefox')) &&
			(mua('MacPPC') || mua('Mac68K') || mua('macintosh')) &&
			($.browser.version.substr(0,3) <= 1.8)
		) {
			return true;
		}
			
		$.ajax({
			type: "POST",
			url: url,
			data: {isAjax: true},
			success: function(resp){
				$popin = createPopin(resp);
				var flashvars = {
					path: '/flash/videos/'
					//,test_drive_actif: true
				};
				swfobject.embedSWF("/flash/demo_player.swf", "video_wrap", "780", "440", "9.0.0", null, flashvars, {wmode: 'transparent'}, attributes);
				
			},
			error: function(req) { }
		});
		return false;
	});
	

/*  -------------------------------------------------------------------
    Forms ------------------------------------------------------------- */
	// Generic
	$("form.frm_testdrive").formHandling({ ajax: false });
	$("#frm_contact, #frm_stf").formHandling();

	$('#frm_signup').formHandling({
		invalidMsg: 'Looks like you\'re email address is missing or is not valid. Please try again.',
		ajaxSuccess: function (resp, $form) {createPopin(resp.msg);}
	})

	// Popins (stf)
	$('#b_stf').click(function () {
		pageTracker._trackPageview('/stf');
		$.ajax({
			type: "POST",
			url: $(this).attr('href'),
			data: {
				stfPath: encodeURIComponent(location.href),
				isAjax: true
			},
			success: function(resp){
				
				$popin = createPopin_stf(resp);
				
				//Form handling
				$("form", $popin).formHandling({
					contentHandler: 'div.popin_content',
					formContainer: '#stf',
					extraData: 'path='+location.href
				});

				// Rollover on button
				$("input:image", $popin)
			        .bind('mouseover focus', function(){this.src = this.src.replace(/(?:_o)?\.([a-z]*)$/i,"_o.$1"); })
    			    .bind('mouseout blur',   function(){this.src = this.src.replace(/_o\./i,".");});
			},
			error: function(req) { }
		});
		return false;
	});

	// Software Updates 
	$('.b_update').click(function () {
		pageTracker._trackPageview('/update');
		$.ajax({
			url: $(this).attr('href'),
			data: {
				updatePath: encodeURIComponent(location.href),
				isAjax: true
			},
			success: function(resp){
				
				$popin = createPopin(resp);

			},
			error: function(req) { }
		});
		return false;
	});
	
	
/*  -------------------------------------------------------------------
	Test Drive -------------------------------------------------------- */	
	$('#timezone').bind('change', function () {
		//console.log('change');
		var date = new Date();
		$.getScript(
			'/testdrive/javascriptDatesArray/timezone/'+ $('#timezone').val(),
			function () 
			{
				var firstYear  = null;
				var firstMonth = null;
				var firstDay   = null;
				
				for (var i in special_days)
				{
					firstYear = i;
					
					for (var j in special_days[firstYear])
					{
						firstMonth = j;
						firstDay = special_days[firstYear][firstMonth][0];
						break;
					}
				}
				
	      if (firstYear && firstMonth && firstDay) 
	      {
	        date = new Date(firstYear,firstMonth,firstDay);
	      }
	      
				$('#date').val(date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate());
				$('.calendar').remove();
				
				Calendar.setup(
				{
		      ifFormat       : "%Y-%m-%d",
		      daFormat       : "%Y-%m-%d",
				  flat           : "calendar-container", 
				  date           : date,
				  flatCallback   : dateChanged,
				  dateStatusFunc : dateStatusHandler,
				  weekNumbers    : false,
				  range          : [date.getFullYear(), date.getFullYear()+1]
				});
			    
	      var fakeCalendar         = new Object();
	      fakeCalendar.dateClicked = true;
	      var dateArr              = $('#date').val().split('-');
	      
	      if (dateArr.length == 3) 
	      {
					fakeCalendar.date = new Date(dateArr[0],dateArr[1]-1,dateArr[2]);
					dateChanged(fakeCalendar);
	      }
	      
				$('#time_slot_id').empty().append('<option value="">Choose a day first</option>');	
			});
	});
	$('#b_reload_captcha').click(function () {
		var now = new Date();
		$('#cryptogram').attr('src', $('#cryptogram').attr('src').replace(/(\?\d+)?$/, '?'+now.getTime()));
		return false;
	})
	$('#b_nocode').click( function () {
		$('#code_info').show();
		return false;
	});
	
	
/*  -------------------------------------------------------------------
	Survey ------------------------------------------------------------ */	
	$('#frm_survey div.survey_comment textarea')
		.hide()
		.siblings('label')
			.addClass('toggler')
			.hover(
				function () { $(this).addClass('hover') },
				function () { $(this).removeClass('hover') }
			)
			.click(function () {
				$(this).siblings('textarea').toggle();
			});
	
	$('#frm_survey div.survey_custom').hide();
	$('#survey_q_6_24').click(function () {
		$('#frm_survey div.survey_custom').show();
	})
	$('#survey_q_6_25').click(function () {
		$('#frm_survey div.survey_custom').hide();
	})
	
	
	/*Contest Optin*/
	$("input#optin_contest").bind("click", function(){
		$("#survey_contactinfo").toggle();
	});
	
	
	$('#frm_survey').submit(function () {
		// Reset
		var error  = 0;
		$('#survey_errors', this).remove();
		$('strong.error', this).removeClass('error');
		$('label.error', this).removeClass('error');
		
		// Get errors
		var sError = '';
		$('ul.v-mandatory', this).each( function () {
			if (!$(':checked', this).size()) {
				$(this).siblings('div').children('strong').addClass('error');
				var target = '#' + $(this).parent().attr('id');//$('input', this).slice(0,1).attr('id');
				var question = $(this).siblings('div').children('strong').html();
				sError += '<li><small><a href="' + target + '">' + question + '</a></small></li>';
				error++;
			}
		});
		if (error>0) {
			sError = '<p>Oops! These questions are mandatory:</p><ul>' 
				+ sError 
				+ '</ul>';
		}
		
		optin_contest = document.getElementById("optin_contest");
		if(!optin_contest.checked){
			//add contest validation
			var country = $('input#rovio_subscription_country','#frm_survey').val();
			var sContestError = '';
			if (country == 'US' || country == 'CA') {
				first_name = $('input#rovio_subscription_first_name','#frm_survey').val();
				if (first_name.length == 0) {
					sContestError += '<li>First Name is a mandatory field</li>';
					$('label[@for="rovio_subscription_first_name"]','#frm_survey').addClass('error');
				}
				last_name = $('input#rovio_subscription_last_name','#frm_survey').val();
				if (first_name.length == 0) {
					sContestError += '<li>Last Name is a mandatory field</li>';
					$('label[@for="rovio_subscription_last_name"]','#frm_survey').addClass('error');
				}
				address1 = $('input#rovio_subscription_address1','#frm_survey').val();
				if (address1.length == 0) {
					sContestError += '<li>Address is a mandatory field</li>';
					$('label[@for="rovio_subscription_address1"]','#frm_survey').addClass('error');
				}
				city = $('input#rovio_subscription_city','#frm_survey').val();
				if (city.length == 0) {
					sContestError += '<li>City is a mandatory field</li>';
					$('label[@for="rovio_subscription_city"]','#frm_survey').addClass('error');
				}
				state_province = $(':input#rovio_subscription_state_province','#frm_survey').val();
				if (state_province == null || state_province == 0 || state_province.length == 0) {
					sContestError += '<li>State / Province is a mandatory field</li>';
					$('label[@for="rovio_subscription_state_province"]','#frm_survey').addClass('error');
				}
	
				zippostalcode = $('input#rovio_subscription_zip_postal','#frm_survey').val();
				if (zippostalcode.length == 0) {
					sContestError += '<li>Zip / Postal code is a mandatory field</li>';
					$('label[@for="rovio_subscription_zip_postal"]','#frm_survey').addClass('error');
				}
	
				phone1 = $('input#rovio_subscription_phone1','#frm_survey').val();
				phone2 = $('input#rovio_subscription_phone2','#frm_survey').val();
				if (phone1.length == 0 || phone2.length == 0) {
					sContestError += '<li>Phone number is a mandatory field</li>';
					$('label[@for="rovio_subscription_phone"]','#frm_survey').addClass('error');
				}
				if (sContestError.length > 0) {
					sError += '<p>Oops! These fields are mandatory:</p><ul>' + sContestError + '</ul>';
					error++;
				}
			}
		}
		
		if (error) {
			$('div.actions', this).before('<div class="error" id="survey_errors">' + sError + '</div>');
			return false;
		}
		
	});
	
	
/*  -------------------------------------------------------------------
    Gallery ----------------------------------------------------------- */
	ajaxGalleryNavigation();
	
	$('#gallery-download a').click(function () {
		which = $(this).attr("id").replace('b_', '');
		var size = {hires : 'width=1024,height=790', lowres:'width=310,height=240'}; 
		var my_popup = window.open($(this).attr("href"), "share_"+which, "scrollbars=yes,resizable=yes,toolbar=no,location=no,status=no,"+size[which]);
		if (my_popup) {my_popup.focus(); return false;}
	})

	
/*  -------------------------------------------------------------------
	Waiting page ------------------------------------------------------ */
	$('#count_down').each( function () {
		window.setTimeout(updateCounter, 200);
		var now = new Date();
		var end = now.getTime() + $('.delay_sec', this).html() * 1000;
		$(this).data('end_at', end);
	});
	
	//checkCanWait Ajax in waiting page
	$("span.checkurl","#count_down").each(function () {
		window.setTimeout(checkTestDrive, 5*60*1000);
	});

	// IE6 fix  
	redrawCorner();

	if (swfobject.hasFlashPlayerVersion('9.0.0')) {
		$('#features #content-head').remove();
	}
});


/*  -------------------------------------------------------------------
	Title Replacement - SIFR 3 ---------------------------------------- */
	var header = {src: '/js/meetrovio.swf'};
	
	sIFR.activate(header); // From revision 209 and onwards
	
	sIFR.replace(header, {
	  selector: '.sifr',
	  wmode: "transparent",
	  css: [
		'.sIFR-root {color: #FFFFFF; font-weight: normal; text-transform: uppercase; leading: -7; letter-spacing: 1;}',
		'.rovio {color: #56A4C0; leading: 0;}',
		'.right {text-align: right;}',
		'.trade {font-size: 22px;}',
		'.small {font-size: 86px;}'
	  ]
	});


/*  -------------------------------------------------------------------
	SWFObject 2.1 ----------------------------------------------------- */
	swfobject.embedSWF("/flash/head_home.swf", "swf_home", "985", "482", "9.0.0", null, flashvars, params, attributes);
	swfobject.embedSWF("/flash/tech_spec.swf", "size_wrap", "540", "390", "9.0.0", null, flashvars, params, attributes);
	swfobject.embedSWF("/flash/features.swf", "swf_features", "985", "820", "9.0.0", null, flashvars, params, attributes);


/*  -------------------------------------------------------------------
	Popin ------------------------------------------------------------- */
	function createPopin (html) {
		// Hover background
		var $bgcover = $('<div id="bgcover">&nbsp;</div>').appendTo('body');
		$bgcover.css({
			height: Math.max($('body').height(), $bgcover.height()),
			opacity: '0.90'
		});
	
		//Popin, center, corner and border, focus
		var $popin = $(html).appendTo('body');
		popupBorder.render($('.popin_wrap_test', $popin));
		$popin.animate({top: getCenteredPos($popin.height())}, 1200, 'backout', function () {
			$('input, select, textarea', $popin).slice(0,1).focus();
		});
		
		return $popin;
	}
	
	function createPopin_stf (html) {
		// Hover background
		var $bgcover = $('<div id="bgcover">&nbsp;</div>').appendTo('body');
		$bgcover.css({
			height: Math.max($('body').height(), $bgcover.height()),
			opacity: '0.90'
		});
	
		//Popin, center, corner and border, focus
		var $popin = $(html).appendTo('body');
		popupBorder.render($('.popin_wrap', $popin));
		$popin.animate({top: getCenteredPos($popin.height())}, 1200, 'backout', function () {
			$('input, select, textarea', $popin).slice(0,1).focus();
		});
		
		return $popin;
	}
		
	function closePopin(){
		var popin = $('div.popin').get(0);
		$('#bgcover, div.popin-content, div.popin a').remove(); // unbind events, avoid memory leak
		popin.parentNode.removeChild(popin); // 1113 div for the border, too much for jQuery
	}
	
	function getCenteredPos(objheight){
		var ScrollTop = document.body.scrollTop;
		if (ScrollTop == 0){
			if (window.pageYOffset){
				ScrollTop = window.pageYOffset;
			}else{
				ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
			}
		}
	
		var myHeight = 0;
		if( typeof( window.innerWidth ) == 'number' ) {
			//Non-IE
			myHeight = window.innerHeight;
		} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
			//IE 6+ in 'standards compliant mode'
			myHeight = document.documentElement.clientHeight;
		} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
			//IE 4 compatible
			myHeight = document.body.clientHeight;
		}
		
		return ScrollTop + (myHeight/2)-(objheight/2);
	}
	
	
/*  -------------------------------------------------------------------
	StF --------------------------------------------------------------- */
	function addFriend() {
		var $fieldsets = $('fieldset.info_friends');
		var count = $fieldsets.size() + 1;
		var $newFriend = $fieldsets.slice(0,1).clone();
		
			$('label',$newFriend).removeClass('error'); //remove error class if any 
			$newFriend.prepend('<a class="b_removefriend" href="" onclick="removeFriend(this); return false;">Remove this friend</a>');
		$('label', $newFriend).each(function() {
			$(this).attr('for', $(this).attr('for')+'_'+count)
			       .find('span').remove();
		});
		$('input', $newFriend).each(function() {
			$(this).attr('id', $(this).attr('id')+'_'+count)
				   .removeClass('v-mandatory')
				   .val('');
		});
		$('#addfriends').before($newFriend);
	}
	
	function removeFriend(el) {
		$(el).parent('fieldset').remove();
	}


/*  -------------------------------------------------------------------
	Page Specifics ---------------------------------------------------- */
	function ajaxGalleryNavigation() {
		$('#b_next_item, #b_prev_item, #gallery-paging a').click(function() {
			$.ajax({
				type: "POST",
				url: $(this).attr('href'),
				data: {isAjax: true},
				success: function(resp){
					$('#gallery-selector, #gallery-paging').remove();
					$('#gallery-nav').append($(resp));
					ajaxGalleryNavigation();
				},
				error: function(req){
				}
			});
			return false;
		});
	}

	function dateChanged(calendar) {
		// Beware that this function is called even if the end-user only
		// changed the month/year.  In order to determine if a date was
		// clicked you can use the dateClicked property of the calendar:
		if (calendar.dateClicked) {
		  var y = calendar.date.getFullYear();
		  var m = calendar.date.getMonth()+1;   // integer, 1..12
		  var d = calendar.date.getDate();      // integer, 1..31
		  
		  $('#date').val(y+"-"+m+"-"+d);
		  
		  $.ajax({
				type: "POST",
				url: '/testdrive/timeSelectTag',
				data: {
					timezone: $('#timezone').val(),
					date: $('#date').val()
				},
				success: function(resp){
					$('#time_slot_id').empty().append($('option', resp)).val('');
				}
		   });
		}
	}
	
	function updateCounter() {
		var now   = new Date();
		var end   = $('#count_down').data('end_at');
		var delay = Math.round((end - now.getTime())/1000);
		if (delay <= 0) {
			
			if ($('#count_down .url').html() && $('#count_down .url').html() != '') {
				location.href = $('#count_down .url').html();
				return;
			} 
		}
		
		window.setTimeout(updateCounter, 200);
		var hours   = Math.floor(delay/3600);
		var minutes = Math.floor((delay % 3600)/60);
		var seconds = delay % 60;
		if (hours   < 10) {hours   = '0' + hours;}
		if (minutes < 10) {minutes = '0' + minutes;}
		if (seconds < 10) {seconds = '0' + seconds;}
		
		var timer = hours+':'+minutes+'.'+seconds;
		
		if ($('#count_down .counter').html() != timer) {
			$('#count_down .counter').html(timer);
		}
		
	}
	
	$.easing.backout = function(x, t, b, c, d){
		var s=1.20158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	};

	function checkTestDrive() {
		var checkUrl = $("span.checkurl","#count_down").html();
		//ajax call with
		$.ajax({
			type: "GET",
			url: checkUrl,
			//data: {isAjax: true},
			success: function(resp){
				if (resp == '') {
					location.href = location.href;
				} 
			},
			error: function(req){
			}
		});
		window.setTimeout(checkTestDrive, 5*60*1000);
		//return false;
		
	}

	
	function mua(s) {
		var ua = navigator.userAgent.toLowerCase();
		return (ua.indexOf(s.toLowerCase()) > -1);
	}


/*  -------------------------------------------------------------
    IE 6 Fix ----------------------------------------------------
	This function fix the odd/even size trouble under IE6 ------- */
	function redrawCorner () {
		if($.browser.msie && ($.browser.version<7)){
			$("div.corner.bottom").each(function(){
				if ($(this).parent().height()%2) { $(this).css("bottom", "-1px");/* alert('resize');*/}
				else { $(this).css("bottom", "0"); }
			});
			$('div.corner').hide().show();
		}
	}