/*
* Custom jQuery functions
**/

$(document).ready(function() {
	$('#bcSubmit').bind('click', function(event) {
		startBiologicalClockApp('submit');
		return false;
	});
	$('.closeOverlay').live('click', function(event) {
		$('#bcOverlay').hide();
		return false;
	});
	$('.closeOverlayVideo').live('click', function(event) {
		$('#bcOverlayVideo').hide();
		$('#bcOverlayVideo').html('');
		return false;
	});
	$('#btnBcInfo').bind('click', function(event) {
		//showOverlay('<h5>Hoe werkt de biologische klok?</h5><p>Je kunt na het invullen van een paar eenvoudige gegevens een eigen persoonlijke kalender aanmaken waarin je complete cyclus overzichtelijk wordt weergegeven. </p><p>Hierin staan al de belangrijke dagen, zoals ovulatie, vruchtbare periode en wanneer je een bepaalde zwangerschapstest of ovulatietest kunt doen. </p><p>Altijd jouw biologische klok bij je hebben?<br /><a href="#" target="_blank">Download dan hier de speciale iPhone app</a>!</p>');
		showOverlay('<h5>Hoe werkt de biologische klok?</h5><p>In je persoonlijke kalender zie je wanneer je vruchtbare periode, ovulatie en menstruatie plaats gaat vinden.</p><p>Als je graag je gegevens wilt bewaren, is het mogelijk om jouw persoonlijke kalender op te slaan. Zo krijg je over een langere periode inzicht in je cyclus.</p><p>Wil je je biologische altijd bij je hebben? Download dan de <a href="#" target="_blank">gratis iPhone app</a>, de inloggegevens voor de app en de online versie van \'Mijn Biologische Klok\' zijn gelijk.</p><p>Wil je een bericht ontvangen wanneer je vruchtbare periode begint? Stel dan de berichtgeving in en ontvang iedere maand automatisch en discreet een bericht.</p>');
		return false;
	});
	
	// selectbox styling
	$('#bcForm select').uniform();
//	$('#bcSelectStartMonth').uniform();
	
	$('a#adviseAppClose').live('click',function(){hideAdviseApp();});
	var t=setTimeout("showAdviseApp()",2000);
});

function showAdviseApp() {
	$('#adviseApp').fadeIn(400);
}

function hideAdviseApp() {
	$('#adviseApp').fadeOut(400);
}


/* Sitemap */
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');
	}
}

function fillSearchValue(defaultValue) {
	if($('input#search_field').val() == '') {
		$('input#search_field').val(defaultValue);
	}
}

function emptySearchValue(defaultValue) {
	if($('input#search_field').val() == defaultValue) {
		$('input#search_field').val('');
	}
}

var slideshowCurrentSlide = 0;
var slideshowTotalSlides = 0;
var slideshowInterval = 6000;
var slideshowTimeoutObject;

function slideshowInit() {
	// Count total items
	slideshowTotalSlides = $('#homeCarrousel img').size();
	slideshowCurrentSlide = slideshowTotalSlides-1;	// Set current visible item to last img
	$('#slideshowPagination a#slideshowMoveTo_'+(slideshowTotalSlides-1)).addClass('active');
	slideshowActivate();
}

function slideshowActivate() {
	slideshowTimeoutObject = setTimeout('slidehowMoveNext();',slideshowInterval);
}

function slideshowStop() {
	clearTimeout(slideshowTimeoutObject);
}

function slidehowMoveNext() {
	if(slideshowCurrentSlide == (slideshowTotalSlides-1)) {
		moveToSlide = 0;
	}else{
		moveToSlide = slideshowCurrentSlide + 1
	}
	
	slideshowMoveTo(moveToSlide);
}

function slideshowMoveTo(index) {
	// Fade out current
		$('#slide_'+slideshowCurrentSlide).fadeOut();
	// Fade in new
		$('#slide_'+index).fadeIn();
	
	// Set current slide to faded to slide
		slideshowCurrentSlide = index;
	// Activate correct link
		$('#slideshowPagination a').removeClass('active');
		$('#slideshowPagination a#slideshowMoveTo_'+slideshowCurrentSlide).addClass('active');
	// Reset timer
		slideshowTimeoutObject = setTimeout('slidehowMoveNext();',slideshowInterval);
}

function moveSlideshowByClick(index) {
	slideshowStop();
	slideshowMoveTo(index);
}

/* Save test day functions **************************************************/

/* Show reminder form */
function showReminder() {
	$('#reminder').show();
}

/* Hide reminder form */
function hideReminder() {
	$('#reminder').hide();
}

/**
* This function is called by the flash app
*
* @param	String	testDate	Date on which the remindermail should be sent. Format d(d)-m(m)-yyyy
*
* It should cover all further handling.
*/
function saveTestDay(testDate, testInDays) {
	if(testDate != '') {
	
		// Show reminder form
		$('#reminder').show();
		
		// Split the date to dd, mm, yyyy
		/*var arrDate = new Array();
		arrDate = testDate.split('-');
		
		var dateDay = arrDate[0];
		var dateMonth = arrDate[1];
		var dateYear = arrDate[2];*/
		
		// Set in form
		$('#reminderDate').val(testDate);
		
		// Show number of days
		testInDays = parseInt(testInDays) + 1;
		
		$('#numberDays').html(testInDays);
	}
}

/*
* Send the reminder mail via ajax. The ajax call does some checks too.
**/
function saveReminder() {
	var name = $('#reminderYourName').val();
	var email = $('#reminderYourEmail').val();
	var testDate = $('#reminderDate').val();
		
	// Reset error classes
	 $('#labelReminderYourName').removeClass('error');
	 $('#labelReminderYourEmail').removeClass('error');
	
	// Ajax it
	$.ajax({
		type: "POST",
		url: rootPath+"include/functions.ajax.php",	
		data: "name="+name+"&email="+email+"&date="+testDate+"&ajaxAction=saveReminder",		
		success: function(msg){
		//alert(msg);
			// Process return value
			var arrResult = msg.split('|||');
			if (arrResult[0] == 'OK') {	// Everything OK. Result saved.
				$('#reminderReplaceableContent').html('<strong>Je e-mailadres is opgeslagen.<br>U ontvangt binnenkort een herinneringsmail.</strong>');			
			}else if(arrResult[0] == 'ERROR') {	// An error occured.
				// Split all error fields and make 'em red
				var arrErrors = arrResult[1].split('||');
				var errLength = (arrErrors.length)-1;
				for(var i=0;i<errLength;i++) {
					$('#'+arrErrors[i]).addClass('error');
				}
			}
		}
	});
}

function startBiologicalClockApp(method){
	
	var todayDate = $('#todayDate').val();
	var startDate = $('#bcSelectStartYear').val()+'-'+$('#bcSelectStartMonth').val()+'-'+$('#bcSelectStartDay').val();
	var endDate = $('#bcSelectEndYear').val()+'-'+$('#bcSelectEndMonth').val()+'-'+$('#bcSelectEndDay').val();
	var cycleLength = $('#bcSelectCycleLength').val();
	var error = false;
	
	if(startDate >= endDate){
		error = 'De eerste dag van je menstruatie mag niet na de laatste dag zijn.';
	}else if(endDate > todayDate){
		error = 'De laatste dag van je menstruatie mag niet in de toekomst zijn';
	}else {
		var startDate = new Date($('#bcSelectStartYear').val(),($('#bcSelectStartMonth').val() -1),$('#bcSelectStartDay').val())
		
		var endDate = 	new Date($('#bcSelectEndYear').val(), ($('#bcSelectEndMonth').val()-1), $('#bcSelectEndDay').val())
		
		//if (startDate.getMonth()==11 && startDate.getDate()>25){ //if endDate has passed already
		//	endDate.setFullYear(endDate.getFullYear()+1) //calculate next year's endDate
		//}
		
		//Set 1 day in milliseconds
		var one_day=1000*60*60*24;
		
		var totalDaysBetweenDates = Math.ceil((endDate.getTime()-startDate.getTime())/(one_day));
		
		// aantal dagen tussen menstruatie moet groter zijn dan (cycle length - 18) 
		//if( (cycleLength - 19) <  totalDaysBetweenDates){
		if( (cycleLength - 15) <  totalDaysBetweenDates){
			error = 'Je cyclus lengte is te kort t.o.v. je menstruatie lengte';
		}
			
		//error = Math.ceil((endDate.getTime()-startDate.getTime())/(one_day))+" days left until endDate!";
	}
	
	
	
	if(error == false || method == 'login'){
		var flashvars = {};
		if(method=='submit'){
			flashvars.startDate = $('#bcSelectStartDay').val()+'-'+$('#bcSelectStartMonth').val()+'-'+$('#bcSelectStartYear').val();
			flashvars.endDate = $('#bcSelectEndDay').val()+'-'+$('#bcSelectEndMonth').val()+'-'+$('#bcSelectEndYear').val();
			flashvars.cycle = $('#bcSelectCycleLength').val();
		}
	
		flashvars.path = rootPath+'webservice/biological_clock.wsdl';
		flashvars.appStoreUrl = 'http://itunes.apple.com/app/mijn-biologische-klok/id482014442';
		
		var params = {};
		params.play = "true";
		params.menu = "false";
		params.wmode = "transparent";
		swfobject.embedSWF(flashPath+"biologischeklok.swf", "bcContent", "911", "536", "9.0.0", false, flashvars, params);
	}else{
		alert(error);
	}	
}

/**
 * Create the 'remember me' cookie
 */
function createBiologicalClockAppRememberMeCookie() {
	$.ajax({
		type: "GET",
		url: rootPath+"pages/ajax.inc.php",	
		data: "action=createBiologicalClockAppRememberMeCookie"
	});
}

/**
 * Check if the 'remember me' cookie exists. If so, it starts the app
 * 
 */
function checkBiologicalClockAppRememberMeCookie() {
	$.ajax({
		type: "GET",
		url: rootPath+"pages/ajax.inc.php",
		async: false,
		data: "action=checkBiologicalClockAppRememberMeCookie",		
		success: function(msg){
			if(msg == '1') {
				startBiologicalClockApp('login');
			}
		}
	});
}

/**
 * Remove the 'remember me' cookie
 */
function removeBiologicalClockAppRememberMeCookie() {
	$.ajax({
		type: "GET",
		url: rootPath+"pages/ajax.inc.php",	
		data: "action=removeBiologicalClockAppRememberMeCookie"
	});
}

function showOverlay(content){
	if(content!=''){
		$('#bcOverlay').html(content);
		$('#bcOverlay').append('<a href="#" class="closeOverlay"></a>');
	}
	$('#bcOverlay').show();
	sIFR.replace(fPredictor, {
		selector: '#bcOverlay h5'
		,css: ['.sIFR-root { color: #000000; font-size: 24px;}, a {color: #000000; text-decoration: none;},  a:hover {color: #666666;}']
		,wmode: 'transparent'
		,selectable: true
	});
	return false;
}

function openVideoOverlay(videoUrl){
	if(content!=''){
		$('#bcOverlayVideo').html('<iframe width="560" height="349" src="'+videoUrl+'?rel=0" frameborder="0" allowfullscreen></iframe>');
		$('#bcOverlayVideo').append('<a href="#" class="closeOverlayVideo"></a>');
	}
	$('#bcOverlayVideo').show();
	
	return false;
}

function calculateFertility(){
	// hide form
	$('#fertilityForm').hide();
	// get data
	var Date_Day= $('#fertilityDay').val();
	var Date_Month= $('#fertilityMonth').val();
	var Date_Year= $('#fertilityYear').val();
	var cyclus= $('#fertilityCycle').val();

	// Ajax it
	$.ajax({
		type: "GET",
		url: rootPath+"pages/calculate_ajax.php",	
		data: "action=checkFertility&Date_Day="+Date_Day+"&Date_Month="+Date_Month+"&Date_Year="+Date_Year+"&cyclus="+cyclus+"",		
		success: function(msg){
			$('#fertilityResult').html(msg);		
		}
	});
}

function restartFertility(){
	$('#fertilityResult').html('');
	$('#fertilityForm').show();
}

function calculateDueDate(){
	// hide form
	$('#dueDateForm').hide();
	// get data
	var Date_Day= $('#dueDateDay').val();
	var Date_Month= $('#dueDateMonth').val();
	var Date_Year= $('#dueDateYear').val();
	var cyclus= $('#dueDateCyclus').val();

	// Ajax it
	$.ajax({
		type: "GET",
		url: rootPath+"pages/calculate_ajax.php",	
		data: "action=checkDueDate&Date_Day="+Date_Day+"&Date_Month="+Date_Month+"&Date_Year="+Date_Year+"&cyclus="+cyclus+"",		
		success: function(msg){
			$('#dueDateResult').html(msg);
		}
	});
}

function restartDueDate(){
	$('#dueDateResult').html('');
	$('#dueDateForm').show();
}

function saveStats(locationId){
	// Ajax it
	$.ajax({
		type: "GET",
		url: rootPath+"pages/calculate_ajax.php",	
		data: "action=saveStats&locationId="+locationId+"",		
		success: function(msg){
			$('#fertilityResult').html(msg);		
		}
	});
}
