function showMenu() {
	// Activate selected menu item
	var obj = $(this);
	obj.addClass('active');
	var menuPosition = obj.position();
	
	// Show menu
	var menuObj = obj.children('.dropmenu');
//	menuObj.fadeTo(200);
//	menuObj.fadeTo(200, 0.93);
//	menuObj.slideDown(200);
	menuObj.show();
	
	// Position menu horizontally on the left or on the right based on li item position
	var totalWidth = $('#menu').width();

	if(menuPosition.left+menuObj.width()>totalWidth) {
		menuObj.css('left', 'auto');
		menuObj.css('right', '0px');
	} else {
		menuObj.css('left', menuPosition.left+'px');
		menuObj.css('right', '0px');		
	}

}
function hideMenu() {
	$(this).removeClass('active');
//	$(this).children('.dropmenu').fadeOut(200);
	$(this).children('.dropmenu').hide();
}
function toggleDropMenuItem() {
	$(this).toggleClass('active');
}
function blurSearch() {
	if($(this).val()=='') {
		$(this).val('Haku'); // Empty box if default to allow user to enter their query
	}
}
function focusSearch() {
	if($(this).val()=='Haku') {
		$(this).val(''); // Empty box if default to allow user to enter their query
	}
	// Attach event for blur
	$(this).blur(blurSearch);
}
function operateTabs() {
	if (!$(this).hasClass('selected')) {    
		// Remove the selected class from all LI    
		$('.boxTabs > ul > li').removeClass('selected');
		
		// After cleared all the LI, reassign the class to the selected tab
		$(this).addClass('selected');
		
		// Hide all the DIV in .boxBody
		$('.boxBody div').hide();
		
		// Look for the right DIV index based on tabs LI index
		var ind = $('.boxTabs > ul > li').index(this);

		// Show the selected boxBody div
		$('.boxBody div:eq('+ind+')').show();
	}
	return false;
}
function addProductQty() {
	var inp = $('#pqty');
	if(inp) {
		var valToSet = parseInt(inp.val())+1;
		inp.val(valToSet); 
	}
	return false;
}
function removeProductQty() {
	var inp = $('#pqty');
	if(inp) {
		var valToSet = parseInt(inp.val())-1;
		if(valToSet<1) {
			valToSet = 1;
		}
		inp.val(valToSet); 
	}
	return false;
}
function toggleDivVisibility(id) {
	var ele = $(id);
	if(ele) {
		ele.toggleClass('hidden');
	}
	return false;
}
function setDivVisibility(id, isVisible) {
	var ele = $(id);
	if(ele) {
		if(isVisible && ele.hasClass('hidden')) {
			ele.removeClass('hidden');			
		} else if(!isVisible && !ele.hasClass('hidden')) {
			ele.addClass('hidden');
		}
	}
	return false;
}
function toggleCheckbox(id) {
	var ele = $(id);
	if(ele) {
		if(ele.attr('checked'))
			ele.attr('checked', false)
		else
			ele.attr('checked', true);
	}
	return false;
}
//Validates ssl/check_out.php form when submitted
function validateCheckOutForm() {

	// Check for basic address information
	if(!document.getElementById('billto_first_name').value || !document.getElementById('billto_last_name').value || !document.getElementById('billto_street_line_1').value || !document.getElementById('billto_postal_code').value || !document.getElementById('billto_city').value || !document.getElementById('billto_phone_number').value || !document.getElementById('billto_email').value) {
		alert('Ole hyvä ja anna kaikki pakolliset tiedot (punaisella tähdellä merkityt kentät)!');
		return false;		
	}

	// Check for delivery date selection
	if(document.getElementById('pvmtypeval2').checked && !document.getElementById('pvm').value) {
		alert('Ole hyvä ja määrittele toivottu toimituspäivä (valitse kalenterista)!');
		return false;
	}
	
	// Check for terms and conditions acceptance
	if(!document.getElementById('accept_terms_and_conditions').checked) {
		alert('Ole hyvä ja hyväksy toimitusehdot!');
		return false;
	}	
	
	return true;
}
//Validates ssl/submit_order.php form when submitted
function validateSubmitOrderForm() {

	// Validate and make sure one payment method is selected
	paymentSelected = false;
	for (var i=0; i<document.paymentform.payment_method.length; i++) {
		if (document.paymentform.payment_method[i].checked) {
			paymentSelected = true;
			break;
		}
	}
	
	if(paymentSelected)
		return true;
	else
		alert('Ole hyvä ja valitse jokin maksutapa tilaukselle!');
		
	return false;
}
function setCheckOutDeliveryWishFields() {
	if($("#pvmtypeval2").attr('checked')) {
		setDivVisibility('#additionalPvmSelectionFields', true);
	} else if($("#pvmtypeval1").attr('checked')) {
		setDivVisibility('#additionalPvmSelectionFields', false);
	}	
}
function openTermsWin(termsUrl) {
	var twin = window.open(termsUrl, 'Toimitusehdot', 'scrollbars=yes,menubar=no,height=700,width=800,resizable=yes,toolbar=no,location=no,status=no');	
	return false;
}

function focusSubscription() {
	if($(this).val()=='Sähköpostiosoitteesi') {
		$(this).val(''); // Empty box if default to allow user to enter their query
	}
	// Attach event for blur
	$(this).blur(blurSubscription);
}
function blurSubscription() {
	if($(this).val()=='') {
		$(this).val('Sähköpostiosoitteesi'); // set default if form input doesn't contain anything
	}
}


function doInit() {
	
	// Add hover action to menu li items
	var menuConfig = {    
		 sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)    
		 interval: 10, // number = milliseconds for onMouseOver polling interval    
		 over: showMenu, // function = onMouseOver callback (REQUIRED)    
		 timeout: 100, // number = milliseconds delay before onMouseOut    
		 out: hideMenu // function = onMouseOut callback (REQUIRED)    
	};
	
	$('#menu > li').hoverIntent(menuConfig);
	
	// Add hover class change for dropmenu li items
	$('.dropmenu ul li').hover(function() {$(this).addClass('movered');}, function() {$(this).removeClass('movered');});

	// Add onclick for dropmenu li items to follow containing anchor's href
	$('.dropmenu ul li').click(function() {window.location=$(this).find("a").attr("href"); return false;});

	// Add 'emptying' action to header search box
	$('#searchinputbox').focus(focusSearch);
	
	// Add active class for ul.activeNavi li items
	// $('ul.activeNavi li').hover(function() {$(this).addClass('active');}, function() {$(this).removeClass('active');});

	
	// Front page functionality
	if($('#frontpageTop').length) {
		// Add 'emptying' action to newsletter subscribtion form
		$('#newsletter_email').focus(focusSubscription);
	}
	
	// Product page functionality
	if($('#jProductPage').length) {

		// Add tabs functionality
		$('.boxTabs > ul > li').click(operateTabs);
		
		// Add cart qty button functionality
		$('a.plusQty').click(addProductQty);
		$('a.minusQty').click(removeProductQty);
	
		// Add colorbox
		$("a.zoomImage").colorbox({'photo':true, 'width':'800px', 'opacity':0.3, 'previous':'&lt;Edellinen', 'next':'&nbsp;&gt;Seuraava', 'close':'[x] Sulje', 'current':'(kuva {current}/{total})'});
		
		// Add show bonus calculation with colorbox
		$("a.showBonusCalculation").colorbox({opacity:0.3, inline:true, close: 'sulje', href:"#productBonusCalculation"});
	
		// Add option label details display
		$("label.optionLabel").hover(function() { var detailsId='#'+$(this).attr("for")+'details'; if($(detailsId).length>0) $(detailsId).removeClass('hidden'); }, function() { var detailsId='#'+$(this).attr("for")+'details'; if($(detailsId).length>0) $(detailsId).addClass('hidden'); });
	}

	// Cart page functionality
	if($('#jCartPage').length) {
		// Email cart contents
		$("a.sendCartToEmailLink").colorbox({opacity:0.3, inline:true, close: 'sulje', href:"#emailCart"});

		// Add delivery info tip box hover
		$("a.deliveryInfoLink").hover(function() { var tipId = '#'+$(this).attr("rel"); $(tipId).removeClass('hidden'); }, function() { var tipId = '#'+$(this).attr("rel"); $(tipId).addClass('hidden'); });
		
		// Cart rule input slider
		$("a#campaignCodeLink").click(function(){
			  $('#campaignCodeDiv').slideToggle('fast', function() {
				  // Animation complete.
				  var visibility = $(this).css("display");
				  if(visibility = 'block')
					  $("#cartRuleCode").focus();
				  else
					  $("#cartRuleCode").blur();
			    
			  });
			});
		//colorbox({opacity:0.3, inline:true, close: 'sulje', href:"#campaignCodeDiv"});
	}
	
	// Check out functionality
	if($('#jCheckOutPage').length) {

		$("#toggleCartContents").click(function() { $('#cartContents').slideToggle(300); });
		
		// Make sure that the correct delivery time fields are visible
		setCheckOutDeliveryWishFields();
		
		$("#pvmtypeval1").change(setCheckOutDeliveryWishFields);
		$("#pvmtypeval2").change(setCheckOutDeliveryWishFields);
	
		// hack for ie 
		if ($.browser.msie) { 
		  $("#pvmtypeval1").click(function() { 
		    this.blur(); 
		    this.focus(); 
		  });
		  $("#pvmtypeval2").click(function() { 
			    this.blur(); 
			    this.focus(); 
		  });
		}
	}
}

$(document).ready(function() {			
	doInit();
});
