/* Vars for BMI Calculator */
var filled = new Array();
filled["length"] = false;
filled["weight"] = false;
var result = 0;
var type = "";
var uniq_code="";
var upload;

/* Vars for Calcium inname */
var totalCalcium = 0;
var minAmount = 0;
var age = -1;

/* Vars for Wedstrijd */
var form_block = "";

google.setOnLoadCallback(function() {	
	/**
	 * Set navigation for recipes
	 */
	if($('#recipe_list').length){
		if(String(param_id) != "0"){
			$('#recipe_'+String(param_id)).addClass("selected");
		}
	}
	
	/**
	 * BMI Calculation
	 */
	if($("#bmi_calculator").length){
		
		$("#bmi_calculator input").keypress(function (e)
		{
		  //if the letter is not digit then display error and don't type anything
		  if( e.which!=8 && e.which!=0 && e.which!=13 && (e.which<48 || e.which>57))
		  {
		    //display error message
		    $("#errmsg").html("Digits Only").show().fadeOut("slow");
		    return false;
		  }else if(e.which == 13){
		  	calculateResult();
			}
		});
	
		$("#bmi_calculator input").change(function(){
			if($(this).val() > 0){
				filled[$(this).attr("id")] = true;
			}else{
				filled[$(this).attr("id")] = false;
			}
			 calculateResult();
		});
		
	}
	
	/**
	 * Calcium inname
	 */
	if($("#calcium_inname").length){
	
		/* only permit numbers for age */
		$("#tbl_calcium_first input#leeftijd").keypress(function (e)
		{
		  if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57))
		  {
		    return false;
		  }
		});
	
		/* only permit numbers and comma for porions */
		$("#tbl_calcium_second input").keypress(function (e)
		{
		  if( e.which!=8 && e.which!=0 && e.which!=44 && (e.which<48 || e.which>57))
		  {
		    return false;
		  }
		});
		
		/* Highlight the focussed row */
		$("#tbl_calcium_second input").focus(function(){
			$(this).parent("td").parent("tr").addClass("focus");
		})
		
		$("#tbl_calcium_second input").blur(function(){
			$(this).parent("td").parent("tr").removeClass("focus");
		})
		
		/* Update Calcium field after input change */
		$("#tbl_calcium_second input").change(function(){
			var portion = Number($(this).val().replace(",", "."));
			var id = $(this).attr("id").replace("input_", "");
			var calcium = Number($("span#value_"+id).text());
			var total = portion * calcium;
			$("#result_"+id).html(total);
		});
		
		/* Calculate the result */
		$("#calcium_btn").click(function(){
			age = $("input#leeftijd").val();
			totalCalcium = 0;
			if(age > 0){
				$("#errMsg").hide();
				
				/* Calculate total calcium */
				$.each($("td div.calcium_holder"), function(){
					totalCalcium += Number($(this).html());
				});
				
				if($("input[name='zwanger']:checked").val() == "ja" || $("input[name='borstvoeding']:checked").val() == "ja" || $("input[name='menopauze']:checked").val() == "ja"){
					minAmount = 1200;
				}else{
					/* Check minimum amount */ 
					if(age <= 10){
						minAmount = 800;
					}else if(age <= 14){
						minAmount = 1000;
					}else if(age <= 18){
						minAmount = 1200;
					}else if(age <= 60){
						minAmount = 900;
					}else{
						minAmount = 1200;
					}
				}
				callGA('/melktest/calciuminname/bereken');
				$("#result").removeClass("hide");
				$("#result_nr span").html(totalCalcium);
				
				if(totalCalcium < minAmount){
					$("#result_low").removeClass("hide");
					$("#result_good").addClass("hide");
				}else{
					$("#result_good").removeClass("hide");
					$("#result_low").addClass("hide");
				}
			}else{
				$("#errMsg").show();
				$.scrollTo($("#top"), {duration:600});
			}
		});
	}
	
	/**
	 * Vote Movie
	 */
	$("#btn_vote").click(function(){	
		$(this).attr("disabled", true);
		$.post(root+"dans/stem/", {yt_code: $("input#yt_code").val(), video_id: $("input#video_id").val()},
			function (data){
				$("div#vote_wrapper").html("<img src='"+root+"images/btn_vote_thanks.png' alt='Bedankt voor je stem' title='Bedankt voor je stem' id='btn_vote_thanks' />");
				
			}, "json");
	});
	
	
	/**
	 * Send chosen song
	 */
	$("form#song_form").submit(function(){
		if($("input#songName").val() == ""){
			$("#error_song").show();
			return false;
		}else{
			return true;
		}
	});
	
	/*
	$("#btn_next_step1").click(function(){
		if($("input#songName").val() == ""){
			$("#error_song").show();
		}else{
			$("form#song_form").submit();
		}
	});
	*/
	
	/**
	 * Show explanation
	 */
	$("#start_help dl dt").click(function(){
		$(this).next("dd").slideToggle("fast");									  
	});

	
	/**
	 * General Ajax settings
	 */
	$.ajaxSetup({
		type:		"post",
		dataType:	"json",
		error:		"postError"
	});
	
	$("form").ajaxStart(function(){
		$("#"+form_block+" .loader").fadeIn("fast");
		if(form_block == "film_link"){
			$("#film_upload .overlay").show();
		}
		if(form_block == "film_upload"){
			$("#film_link .overlay").show();
		}
	});
	
	$("form").ajaxStop(function(){
		$("#"+form_block+" .loader").fadeOut("fast");
		if(form_block == "film_link"){
			$("#film_upload .overlay").hide();
		}
		if(form_block == "film_upload"){
			$("#film_link .overlay").hide();
		}
	});
	
	
	/**
	 * Register user
	 */
	$("form#register_form").submit(function(){
		form_block = "add_data";
		$.ajax({
			url:$("form#register_form").attr("action"),
			data:$("form#register_form").serialize(),
			success:registerSuccess
		});
		return false;
	});
	
	$("form#register_form input").focus(function(){
		$(this).next("span.error").html("");
		$(this).next("span.error").hide();
	});

	
	/**
	 * Send Film Link
	 */
	$("input#link").focus(function(){resetError();});
	$("input#film").focus(function(){resetError();});
	
	$("input#link").blur(function(){
		//$("#film_upload .overlay").hide();
	});
	
	$("form#link_form").submit(function(){
		var rx = new RegExp("http://www.youtube.com/watch");
		if(rx.exec($("input#link").val()) == null){
			$("#msg_link").show();
			$("#msg_link").html("Dit is geen geldige youtube url");
		}else{
			form_block = "film_link";
			$.ajax({
				url: root+'dans/youtube_link',
				data: {'link': $("input#link").val(), 'code':$("input#code").val()},
				success: uploadComplete
			});
		}
		return false;
	});

	/*
	$("#link_button").click(function(){
		var rx = new RegExp("http://www.youtube.com/watch");
		if(rx.exec($("input#link").val()) == null){
			$("#msg_link").show();
			$("#msg_link").html("Dit is geen geldige youtube url");
		}else{
			form_block = "film_link";
			$.ajax({
				url: root+'dans/youtube_link',
				data: {'link': $("input#link").val(), 'code':$("input#code").val()},
				success: uploadComplete
			});
		}
	});
	*/
	
	/**
	 * Upload Film
	 */
	$("form#upload_form").submit(function(){
		var arr = $("input#film").val().split(".");
		var extension = arr[arr.length-1];
		
		if (!(extension && /^(avi|3gp|wmv|mov|mp4|mpeg|mpg|flv|swf|mkv)$/.test(extension))){
			$("#msg_upload").show().html("Dit is geen geldig bestandsformaat");
			return false;
		}else if($("input#code").val() == ""){
			$("#msg_upload").show().html("Dit is geen geldige code");
			return false;
		}else{
			$("#film_upload .loader").show();
			$("#film_link .overlay").show();
			return true;
		}
	});
	
	
	/**
	 * Upload movies
	 */
	/*
	if($("#upload_button").length > 0){
		upload = new AjaxUpload('#upload_button', {
			action: root+'dans/upload',
			name: 'film',
			autoSubmit: true,
			onChange: function(file, extension){},
			onSubmit: function(file, extension) {
				if (! (extension && /^(avi|3gp|wmv|mov|mp4|mpeg|flv|swf|mkv)$/.test(extension))){
					$("#msg_upload").html("Dit is geen geldig bestandsformaat");
					return false;
				}else if($("input#code").val() == ""){
					$("#msg_upload").html("Dit is geen geldige code");
					return false;
				}else{
					$("#film_upload .loader").fadeIn("fast");
					$("#film_link .overlay").show();
				}
			},
			onComplete: function(file, response) {
				var arr = response.split("|");
				var data = new Object();
				
				for(var i in arr){
					var part = new Array();
					part = arr[i].split("=");
					data[part[0]] = part[1];
				}
				
				uploadComplete(data);
			}
		});
	}
	*/
	
	
	$("select#video_order_list").change(function(){
		var obj = {order_parameter:$(this).val(), method:"setOrder"}
		loadList(obj);
	});
	
	
	/**
	 * Contact Form
	 */
	$("form#contact_form").submit(function(){
		form_block = "form_wrapper_contact";
		$.ajax({
			url:$("form#contact_form").attr("action"),
			data:$("form#contact_form").serialize(),
			success:contactSuccess
		});
		return false;
	});
	
	$("form#contact_form input").focus(function(){
		$(this).next("span.error").html("");
		$(this).next("span.error").hide();
	});
	
	$("form#contact_form textarea").focus(function(){
		$(this).next("span.error").html("");
		$(this).next("span.error").hide();
	});
	
	
	/**
	 * Admin functionality
	 */
	$("form#approve_video").submit(function(){
		$.ajax({
			url:$("form#approve_video").attr("action"),
			data:$("form#approve_video").serialize(),
			success:approveSuccess
		});
		return false;
	});
	
	 
	$("#btn_online").click(function(){setVideoStatus("approved");});
	$("#btn_offline").click(function(){setVideoStatus("declined");});
	
	
	$('#id11').change(function(){
		 $.ajax({
		  url: "/twisterform/getshops",
		  global: false,
		  type: "POST",
		  data: ({provincie : $('#id11').val()}),
		  dataType: "json",
		  success: function(msg){
			 var options = '';
			 for(var i in msg){
				var shop = msg[i];
				if(shop.id){
					options += '<option value="' + shop.id + '">' + shop.naam + '</option>';
				}
			 }
			 $('#id12').html(options);
		  }
		})
	});
	
	
});

/**
 * Reset Error messages for the "add Film" block
 */
function resetError(){
	$("#msg_link").hide();
	$("#msg_link").html("");
	$("#msg_upload").hide();
	$("#msg_upload").html("");
}


/**
 * Administrator functies
 */
function approveSuccess(data){
	if(data.result == 1){
		if(data.online == 1){
			$(".online").show();
			$(".offline").hide();
		}else{
			$(".online").hide();
			$(".offline").show();
		}
		
		if(data.notified == 1){
			$("#no_mail_sent").html("");
		}
	}
	$("#msg").html(data.msg);
}

/**
 * Wedstrijd functies
 */
function registerSuccess(data){
	$("span.error").hide();
	$("span.error").html("");
	$("#msg_step1").html("");

	if(data.result == 1){
		showStep2(data.film_data.code); 
	}else{
		$("#msg_step1").addClass("error");
		$("#msg_step1").html(data.error_msg);	
		
		$.each(data.error_fields, function(i, val){
			var el = $("input#"+i);
			if(el.length){
				el.next("span.error").html(val);
				el.next("span.error").show();
			}
		});
		
		
	}
}

/** 
 * Jump immediately to step 2 of the form 
 * Called when file uploading failed
 */
function skipStep1(error_msg, code, type){
	if(code != ""){
		showStep2(code);
		$("#msg_upload").show().html(error_msg);
	}	
	
	/*
	$(".form_row input").attr("disabled", "true").addClass("disabled");
	$("#register_button").hide();
	
	$("input#code").val(data.film_data.code);
	$("input#link_code").val(data.film_data.code);
	//$("input#film_id").val(data.film_data.film_id);
	
	//upload.setData({'code': data.film_data.code, 'titel': data.film_data.titel, 'film_id': data.film_data.film_id});
	$("#msg_step1").html(data.msg);
	

	$("#add_film .overlay").hide();
	*/
}

/* Show the add_film block */
function showStep2(code){
	/* Set New data and disable input fields */
	$(".form_row input").attr("disabled", "true").addClass("disabled");
	$("#register_button").hide();
	
	$("input#code").val(code);
	$("input#link_code").val(code);
	
	/* Enable add_film block */
	$("#add_film .overlay").hide();
	
	$.scrollTo($("#add_film"), {duration:300});
}

/* Uploadformulier */
function uploadComplete(data){
	$("#msg_link").hide();
	$("#msg_upload").hide();
	$("#msg_link").html("");
	$("#msg_upload").html("");
	
	if(data.result == 1 && data.msg == "ok"){
		$("#step3_wrapper").load(root+"dans/success", null, function(){
			pageTracker._trackPageview("/dans/bedankt"); 
		});
	}else{
		var output = "";
		output += String(data.error_msg);
		
		if(data.type == "link"){
			$("#msg_link").show();
			$("#msg_link").html(output);
		}else{
			$("#msg_upload").show();
			$("#msg_upload").html(output);
		}
	}
}

/* Contact Formulier */
function contactSuccess(data){
	$("span.error").hide();
	$("span.error").html("");
	$("#msg_contact").html("");
	
	if(data.result == 1){
		/* Enable add_film block */
		$("#form_wrapper_contact").html(data.msg);
	}else{
		var output = "";
		$.each(data.error_msg, function(e){
			output += String(data.error_msg[e]);
		}); 
		
		$.each(data.error_fields, function(i, val){
			var el = $("#"+i);
			if(el.length){
				el.next("span.error").html(val);
				el.next("span.error").show();
			}
		});
		$("#msg_contact").addClass("error");
		$("#msg_contact").html(output);	
	}
}


function postError(data){
	alert(data);
}


/* Paginator */
function setPageList(nr){
	if(nr == null) nr = 1;
	var obj = {page_number: nr, method:"setPage"}
	loadList(obj);
}


function loadList(obj){
	$.post(root+"dans/lijst", obj,
		function(data){
			if(data.result == 1){
				$("#galerij_lijst").html(data.lijst);
			}else{
				alert("fout");
			}
		}, "json");
}

/* Galerij */
function setTotalSpots(total){
	$("#total_spots").html(total);
}

/* Stap 1 */
function setChosenSong(title, url){
	$("#error_song").hide();
	$("input#songName").val(title);
	$("input#songLink").val(url);
}


/**
 * BMI calculator functies
 */

function calculateResult(){
	resetResult();	
	if(filled["length"] == true && filled["weight"] == true){

		var l = $("input#length").val();
		var w = $("input#weight").val();
		result = Math.round((w/(l * l))*1000000)/100;
		$("#result_number").html(result);
		$("#bmi_calculator_result").show();
		
		if(result < 18.5){
			type = "light";
			$("#result_text").html("<span></span>ondergewicht");
		}else if(result < 25){
			type = "good";
			$("#result_text").html("<span></span>een gezond gewicht");
		}else if(result < 30){
			type = "heavy";
			$("#result_text").html("<span></span>overgewicht");
		}else{
			type = "obesitas";
			$("#result_text").html("<span></span>obesitas");
		}
		
		$("#bmi_calculator_result").addClass(type);
		$("#result_explanation li#bmi_"+type).show();
	}
}

function resetResult(){
	$("#bmi_calculator_result").removeClass(type);
	$("#result_text").html("<span></span>");
	$("#result_number").html("");
	$("#result_explanation li#bmi_"+type).hide();
}


function callGA(page){
	pageTracker._trackPageview(page);
}