var selectedHelpItemIndex = '';
var totalResults = 0;

// Late bind some functions
$(document).ready(function () {
	// searchField
	var searchFieldText = 'je zoekopdracht...';
	resetValue('search_field', searchFieldText);
	$('#search_field').bind('focus', function(event) {
		emptyValue('search_field', searchFieldText);
	});
	$('#search_field').bind('blur', function(event) {
		resetValue('search_field', searchFieldText);
	});
	$('#search_form').bind('submit', function(event) {
		emptyValue('search_field', searchFieldText);
	});
	
	var helpFieldText = 'typ hier een onderwerp, bijvoorbeeld hoest';
	resetValue('help_field', helpFieldText);
	$('#help_field').bind('focus', function(event) {
		emptyValue('help_field', helpFieldText);
		expandHelp();
	});
	$('#help_field').bind('blur', function(event) {
		resetValue('help_field', helpFieldText);
	});
	$('#help').bind('mouseleave', function(event) {
		collapseHelp();
	});
	
	
	var newsletterFieldText = 'uw e-mailadres';
	resetValue('newsletter_field', newsletterFieldText);
	$('#newsletter_field').bind('focus', function(event) {
		emptyValue('newsletter_field', newsletterFieldText);
	});
	$('#newsletter_field').bind('blur', function(event) {
		resetValue('newsletter_field', newsletterFieldText);
	});
	$('#newsletter_form').bind('submit', function(event) {
		emptyValue('newsletter_field', newsletterFieldText);
	});


	var postcodeFieldText = 'uw postcode';
	resetValue('postcode_field', postcodeFieldText);
	$('#postcode_field').bind('focus', function(event) {
		emptyValue('postcode_field', postcodeFieldText);
	});
	$('#postcode_field').bind('blur', function(event) {
		resetValue('postcode_field', postcodeFieldText);
	});
	$('#locator_form').bind('submit', function(event) {
		emptyValue('postcode_field', postcodeFieldText);
	});
	
	externalLinks();
	//centerAlignPackshots();
	
	// Slideshows
	if($.browser.msie) { // if IE then speed = 0 so there is no fading transition
		mySpeed = 0;
	}else{
		mySpeed = 'fast';
	}
	
	
	// Slideshow selfcare page
	$('#slideshowSelfcareItems').cycle({ 
	    fx:     'fade', 
	    speed:  mySpeed, 
	    timeout: 5000,
	    cleartypeNoBg: true,
	    prev:   '#slideshowPrev',
	    next:   '#slideshowNext'
	});
	
	$('#homeCarrouselItems').cycle({ 
	    fx:     'fade', 
	    speed:  mySpeed, 
	    timeout: 5000,
	   	cleartype: true,
	    cleartypeNoBg: true,
	    prev:   '#slideshowHomePrev',
	    next:   '#slideshowHomeNext'
	});
	
	
	
	// Overlay lightbox
	try {
		$("#overlay").overlay({
			close: 'a.close' ,
	
			speed: 50,
			// start exposing when overlay starts to load
			onBeforeLoad: function() {
				
				// this line does the magic. it makes the background image sit on top of the mask
				this.getBackgroundImage().expose({opacity: 0.75 ,color: '#000000'});
			}, 
					
			// when overlay is closed take the expose instance and close it as well
			onClose: function() {
				$.expose.close();
			}
		});
	}catch(e){}
	
	// Ajaxify search in footer  
	$('#help_field').keyup(function(event) {
		if(!$('#help_uitklap').hasClass('active')){
			document.getElementById('help_uitklap').className = 'active';
		}
		searchKeywords($('#help_field').val(),event);
	}); 
	
	// Attach key events for searchfield in helpfield
	$('input#help_field').keydown(function(event) {	// Key down on input field
		if(event.keyCode == 40) {	// Down, focus on first element in overview element
			if(selectedHelpItemIndex == 0) {
				$('#searchResults a').removeClass('selected');
				$('a#helpitem_0').addClass('selected');
				selectedHelpItemIndex = 0;
			}
			//$('input#help_field').blur();
			$('a#helpitem_0').focus();	// Focus can only be applied to a small set of elements - so set on the a
		}
	});
	// Attach key events for helpfield results
	$('div#searchResults').keydown(function(event) {	// Key down on input field
		if(event.keyCode == 40) {	// DOWN
			// If not already on last item
			if((selectedHelpItemIndex+1)<totalResults) {
				$('#searchResults a').removeClass('selected');
				$('a#helpitem_'+(selectedHelpItemIndex+1)).addClass('selected');
				selectedHelpItemIndex++;
			}
		}else if(event.keyCode == 38){	// UP
			// If not already on first item
			if(selectedHelpItemIndex>0) {
				$('#searchResults a').removeClass('selected');
				$('a#helpitem_'+(selectedHelpItemIndex-1)).addClass('selected');
				selectedHelpItemIndex--;
			}
		}else if(event.keyCode == 13){	// ENTER
			// If not already on first item
			var gotoUrl = $('a#helpitem_'+selectedHelpItemIndex).attr('href');
			if(gotoUrl.substring(0,7) == 'http://') {
				top.location.href = gotoUrl;
			}
		}
		return false;
	});
	
	$('#productFAQ ul li').bind('click', function() {
		$('ul', this).toggle();
		return false;
	});
	
});



/**
 * Empty the value string of an inputfield, but only if the value equals a certain (standard) text
 */
function emptyValue(elm, text){
	if($('#'+elm).val()==text)
		$('#'+elm).val('');	
}

/**
 * Set the value string of an inputfield to a certain (standard) text, but only if the value is empty
 */
function resetValue(elm, text){
	if($('#'+elm).val()=='')
		$('#'+elm).val(text);
}

/**
 * Adds target="_blank" to links with rel="external" and rel="erternal nofollow"
 */
function externalLinks() {
	$('a[rel*="external"]').attr('target', '_blank');
}


// define function that opens the overlay
function openOverlay() {
	
	// get access to the overlay API
	var api = $("#overlay").overlay();

	// call it's open() method		
	api.load();			
}


function openOverlay2(filename) {
	$('#overlayContent').html('<img src="'+filename+'"/>');
	// get access to the overlay API
	var api = $("#overlay").overlay();

	// call it's open() method		
	api.load();	
}
/**
* Search functionality for footer
**/
function searchKeywords(searchWords,event) {
	if(event.keyCode != 40 && event.keyCode != 38 && event.keyCode != 13) {	// Not on keys down, up, enter
		if(searchWords.length > -1) {	// Start searching from 1 characters and up
			var ajaxOutput = '';
			// Ajax search the keyword(s)
			$.ajax({
				type: "GET",
				url: rootPath + "pages/ajax_functions.ajax.php",
				data: "action=searchKeywords&searchWords="+searchWords,
				success: function(msg){
					processKeywordResults(msg);// Update found results
				},
				beforeSend: function(httpRequest) {
					$('#ajaxLoader1').show();
				},
				complete: function(httpRequest) {
					$('#ajaxLoader1').hide();
				}			
			});
		}
	}
}

/**
* Put ajax result in found results box
**/
function processKeywordResults(result) {
	var arrResults = result.split('||');
	totalResults = arrResults.length;
	var output = '';
	
	for(var i=0;i<totalResults;i++) {
		var currentResult = arrResults[i];
		var arrResultSplit = currentResult.split('|');
		output += '<a href="'+arrResultSplit[1]+'" id="helpitem_'+i+'">'+arrResultSplit[0]+'</a>';
	}
	$('#searchResults').html(output);
	// Reset selection
	$('#searchResults a').removeClass('selected');
	selectedHelpItemIndex = 0;
}

/**
* Show TAF-form
**/
function openTAF() {
	$('#taf').show();
}

/**
* Hide form 
**/
function closeTAF() {
	$('#taf').hide();
}

/**
* Send taf
**/
function sendTAF() {
	// Remove error classes from all labels
	$('#form label').removeClass('error');
	
	var postString = $('#frmTAF').serialize();

	var ajaxOutput = '';
	// Ajax search the keyword(s)
	$.ajax({
		type: "POST",
		url: rootPath + "pages/ajax_functions.ajax.php",
		data: "action=submitTAF&"+postString,
		success: function(msg){
			processTAFAjaxResult(msg);	// Update found results
		},
		beforeSend: function(httpRequest) {
			$('#ajaxLoader2').show();
		},
		complete: function(httpRequest) {
			$('#ajaxLoader2').hide();
		}			
	});
}

function processTAFAjaxResult(result) {
	var arrResult = result.split('||');
	if(arrResult[0] == 'success') {	// Succesfully sent
		$('#form').html(arrResult[1]);
	}else if(arrResult[0] == 'error') {	// Errors found
		var arrErrors = arrResult[1].split('|');
		var totalErrors = arrErrors.length;
		for(var i=0;i<totalErrors;i++) {
			// Add error class to label
			$('#lbl_'+arrErrors[i]).addClass('error');
		}
	}
}

/** FAQ **/

function openFAQPopup(questionId) {
	$('#faq1').show();
	if(questionId != '') {	// Ajaxify the question
		// Ajax search the keyword(s)
		$.ajax({
			type: "GET",
			url: rootPath + "pages/ajax_functions.ajax.php",
			data: "action=loadProductgroupQuestion&questionId="+questionId,
			success: function(msg){
				var FAQresult = msg.split('|');
				var faqTitle = FAQresult[0];
				var faqContent = FAQresult[1];
				var faqPrevLink = FAQresult[2];
				var faqNextLink = FAQresult[3];
				
				$('#faqPopupText').html('<h5>'+faqTitle+'</h5>'+faqContent);
				sifrPopup();
				$('#faqPopupPrevLink').html(faqPrevLink);
				$('#faqPopupNextLink').html(faqNextLink);	
			}		
		});
	}
}

/**
* Hide FAQ popup 
**/
function hideFAQPopup() {
	$('#faq1').hide();
}

/** WHEN VISIT DOCTOR **/
function hideVisitDoctorPopup() {
	$('#whenVisitDoctor').hide();
}

function openVisitDoctorPopup() {
	$('#whenVisitDoctor').show();
}

/* Navigation open/close with delay */

/* Show the submenu - pass main A-tag id */
var menuTimeout;
function showDelayedSubmenu(MainATagId) {
	clearTimeout(menuTimeout);
	$('#submenuMouseTrigger').show();
	menuTimeout = setTimeout("reallyDisplaySubmenu('"+MainATagId+"');", 250);
}

function reallyDisplaySubmenu(MainATagId) {
	clearTimeout(menuTimeout);
	hideDelayedAllSubmenus();
	$('#submenuMouseTrigger').show();
	$('li#'+MainATagId+' div.subsubmenu').show();
}

function hideDelayedAllSubmenus() {
	clearTimeout(menuTimeout);
	$('div.subsubmenu').hide();
	$('#submenuMouseTrigger').hide();
}

function toggleSitemap(id, aId) {
	if($('#'+id).css('display') == 'none') {
		$('#'+id).css('display','block');
		$('a#'+aId+' img.toggleButton').attr('src',imgPath+'sitemap/min.png');
	}else{
		$('#'+id).css('display','none');
		$('a#'+aId+' img.toggleButton').attr('src',imgPath+'sitemap/plus.png');
	}
}


var totalDissolveProducts = 0;
var currentActiveDissloveProduct = 0;

function startProductDissolve() {
	// How many are there in total?
	totalDissolveProducts = $('#packshotDissolve a').size();
	
	// Fade out current one
	//alert('out: a#img_'+currentActiveDissloveProduct);
	$('#packshotDissolve a#img_'+currentActiveDissloveProduct).fadeOut(500,function() {
	    // Which is the next image?
		currentActiveDissloveProduct++;
		if(currentActiveDissloveProduct > (totalDissolveProducts-1)) {
			currentActiveDissloveProduct = 0;
		}
		
		// Fade in next one
		//alert('in: a#img_'+currentActiveDissloveProduct);
		$('#packshotDissolve a#img_'+currentActiveDissloveProduct).fadeIn(500);	
	  });

	// Restart timer
	setTimeout("startProductDissolve();", 5000);
}
