$(document).ready(function() {
	// Standard datepicker settings
	var dateObj = new Date;
	$.datepicker.setDefaults({
		showAnim: 'slideDown',
		minDate: dateObj.getDate()+'-'+dateObj.getMonth()+'-'+dateObj.getFullYear(),
		onSelect: setDate,
		mandatory: true
	});

	window.focus();
});



/*
*
* STEP 1
*
*/
function step1() {
	$(document).ready(function() {
		// Add the date picker
		$(":input.searchTime").attachDatepicker();

		if('' != $("#jsError").val())
		{
			addError($("#jsError").val());
			showError();
		}

		$("#searchButton").click(function() {
			clearErrors();
			var error = 0;
			var bookCode = "";
			var advpaymentnew = 0;
			var advpaymentexist = 0;

			var value = $("#priBookType").val();
			var child = $("#secBookType").val();

			if("none" == value) {
				addError(l('Please select bookingtype'));
				error++;
			}

			if("none" == child) {
				addError(l('Please select subtype'));
				error++;
			}

			if('' == $(":input#day").val() && '' == $(":input#month").val() && '' == $(":input#year").val()) {
				date = new Date();
				var day = date.getDate();
				var month = date.getMonth()+1;
				var year = date.getFullYear();

				if( 10 > day ) {
					day = '0'+day;
				}
				
				if( 10 > month ) {
					month = '0'+month;
				}

				$(":input#day").val(day);
				$(":input#month").val(month);
				$(":input#year").val(year);
			} else {
				if('' == $(":input#day").val()) {
					addError(l('Please select proper day'));
					error++;
				}
				if('' == $(":input#month").val()) {
					addError(l('Please select proper month'));
					error++;
				}
				if('' == $(":input#year").val()) {
					addError(l('Please select proper year'));
					error++;
				}
			}
			if(error == 0) {
				hideError();
				if(undefined == selectData[value]["children"])
				{
					bookCode = selectData[value]["code"];
					advpaymentnew = selectData[value]["advpaymentnew"];
					advpaymentexist = selectData[value]["advpaymentexist"];
					regCustOnly = selectData[value]["onlyregcust"];
				} else {
					var secvalue = $("#secBookType").val();
					bookCode = selectData[value]["children"][secvalue]["code"];
					advpaymentnew = selectData[value]["children"][secvalue]["advpaymentnew"];
					advpaymentexist = selectData[value]["children"][secvalue]["advpaymentexist"];
					regCustOnly = selectData[value]["children"][secvalue]["onlyregcust"];
				}

				$("#bookingRegCustOnly").val(regCustOnly);
				$("#bookingTypeCode").val(bookCode);
				$("#advpaymentnew").val(advpaymentnew);
				$("#advpaymentexist").val(advpaymentexist);
				
				$("#step1form").submit();
			} else {
				showError();
			}
		});

		$("#priBookType").change(function() {
			var value = $("#priBookType").val();
			if("none" == value || undefined == selectData[value]["children"])
			{
				if("none" == value) {
					$("#secBookType").attr("disabled", "disabled").empty();
					$("#bookingTypeInfo").html('');
				} else {
					$("#secBookType").attr("disabled", "disabled").empty().prepend("<option>"+l("no options available")+"</option>");
					$("#bookingTypeInfo").html(selectData[value]['info']);
				}
			} else {
				var children = selectData[value]["children"];

				var $x = $("#secBookType"); 
				var y = $x.get(0);
				y.options[0] = new Option;
				y.options[0].text = l("select");
				y.options[0].value = 'none';
				y.options[0].selected = 'selected';
				var index = 0;
				for(var cnt in children)
				{
					index++;
					y.options[index] = new Option;
					y.options[index].value = cnt;
					y.options[index].text = children[cnt]["caption"];
				}
				$("#secBookType").removeAttr("disabled");
				$("#bookingTypeInfo").html(selectData[value]['info']);

			}
		});

		$("#secBookType").change(function() {
			var value = $("#priBookType").val();
			var child = $("#secBookType").val();
			if('none' == child) {
				$("#bookingTypeInfo").html(selectData[value]['info']);
			} else {
				$("#bookingTypeInfo").html(selectData[value]['children'][child]['info']);
			}
		});

	});
}

/*
*
* STEP 2
*
*/
var ajaxSem = 0;		
function step2() {
	$(document).ready(function() {
	
		setHandlersOnBookingtype();	
	
		// Paging control
		$(".pagingControl")
		.mouseover(function() {
			$(this).addClass('hover');
		})
		.mouseout(function() {
			$(this).removeClass('hover');
		});
		
		$("#pagingPrev").click(function() {
			var prev = $('#bookingTimeListLeft .hiddenPrev').html();
			if(0 == ajaxSem && '' != prev && null != prev) {
				ajaxSem++;
				var bookingType = $('#bookingTypeCode').val();
				$('#bookingTimeListRight').empty().html($('#bookingTimeListCenter').html());
				$('#bookingTimeListCenter').empty().html($('#bookingTimeListLeft').html());
				$('#bookingTimeListLeft div').remove();
				$('#bookingTimeListLeft h3').html('');
				populateLeft(prev, bookingType);
			}
		});
		
		$("#pagingNext").click(function() {
			var next = $('#bookingTimeListRight .hiddenNext').html();
			if(0 == ajaxSem && '' != next && null != next) {
				ajaxSem++;
				var bookingType = $('#bookingTypeCode').val();
				$('#bookingTimeListLeft').empty().html($('#bookingTimeListCenter').html());
				$('#bookingTimeListCenter').empty().html($('#bookingTimeListRight').html());
				$('#bookingTimeListRight div').remove();
				$('#bookingTimeListRight h3').html('');
				populateRight(next, bookingType);
			}
		});
		
		// Submitting and validation
		$("#bookTimeButton").click(function() {
			clearErrors();
			var error = 0;
			if('' == $(":input#bookingTimeData").val()) {
				addError(l('Please select a timeslot'));
				error++;
			}
			if(error == 0) {
				hideError();
				$("#step2form").submit();
			} else {
				showError();
			}
		});
		
	});
	
}


/*
*
* STEP 3
*
*/
function step3() {
	$(document).ready(function() {
		
		// The value of the radio buttons
		var petRegistration = false;
		
		$("#patientRegistrationTrueRadio").click(function() {
			hideError();
			$("#patientRegistrationContainer").show();
			$("#patientRegistrationFalse").hide();
			$("#patientRegistrationTrue").show();
			petRegistration = true;
		});
		$("#patientRegistrationFalseRadio").click(function() {
			hideError();
			$("#patientRegistrationContainer").show();
			$("#patientRegistrationTrue").hide();
			$("#patientRegistrationFalse").show();
			petRegistration = false;
		});

		$(":input#step3submit").click(function() {
			clearErrors();
			var error = 0;
		
			if("true" == $('#regCustOnly').val()) {
				petRegistration = true;
			} 
	
			if(true == petRegistration ) {
				if('' == $(":input#customerNumber").val()) {
					addError(l('Please fill out your customer number'));
					error++;
				}
				if('' == $(":input#patientNumber").val()) {
					addError(l('Please fill out the patient number'));
					error++;
				}
				if('' == $(":input#controlCode").val()) {
					addError(l('Please enter the control code'));
					error++;
				}
			}
			else
			{
				// No current pet registration
				if('' == $(":input#firstName").val()) {
					addError(l('Please enter your first name'));
					error++;
				}
				if('' == $(":input#lastName").val()) {
					addError(l('Please enter your last name'));
					error++;
				}
				if('' == $(":input#address").val()) {
					addError(l('Please fill out your address'));
					error++;
				}
				if('' == $(":input#zipCode").val()) {
					addError(l('Please enter your zip code'));
					error++;
				}
				if('' == $(":input#city").val()) {
					addError(l('Please fill out the city'));
					error++;
				}
				if('' == $(":input#phonePrivate").val()) {
					addError(l('Please enter your private phone number'));
					error++;
				}
				if('' == $(":input#cellphone").val()) {
					addError(l('Please cellphone number'));
					error++;
				}
				if('' == $(":input#email").val()) {
					addError(l('Please fill out your emailaddress'));
					error++;
				}
				if('' == $(":input#petname").val()) {
					addError(l('Please enter your pets name'));
					error++;
				}
				if('' == $(":input#species").val()) {
					addError(l('Please fill out your pets species'));
					error++;
				}
			}
			
			if(error == 0) {
				hideError();
				$("#step3form").submit();
			} else {
				showError();
			}
		});
	});
}

/*
*
* STEP 4
*
*/
function step4() {
	$(document).ready(function() {
//		$("#payment").click(function() {
//			alert('Dibs betalingen sker her');
//			location.href = '/step5';
//		});

	});
}

/*
*
* STEP 5
*
*/
function step5() {
	$(document).ready(function() {
		$(".printButton").click(function() {
			window.print();
		});

	});
}

step1(); /* FIXME only call the current step*/
step2(); /* FIXME */
step3(); /* FIXME */
step4(); /* FIXME */
step5(); /* FIXME */

/*******************
*
* Common functions 
*
*******************/

function toggleLoader(on)
{
	if(on) {
		$('#ajaxLoader').show();
	} else {
		$('#ajaxLoader').hide();
	}
}

function setHandlersOnBookingtype() {
	$(".bookingTime")
		.mouseover(function() {
		$(this).addClass("hover");
	})
	.mouseout(function() {
		$(this).removeClass("hover");
	})
	.click(function() {
		$(".bookingTime").removeClass("selected");
		$("#bookingTimeData").val($(".bookingTimeDataHidden", this).html());
		$(this).addClass("selected");
	});
}


function populateLeft(queryDate, bookingType) {
	toggleLoader(1);
	$.ajax({
		type: "POST",
		url: "step2/getTimes",
		async: true,
		data: "date="+queryDate+"&bookingType="+bookingType,
		cache: false,
		success: function(html){
			$('#bookingTimeListLeft').append(html);
			$('#bookingTimeListLeft h3').html($('#bookingTimeListLeft .hiddenCurDateFormatted').html());
			setHandlersOnBookingtype();
			ajaxSem--;
			if(0 > ajaxSem)
				ajaxSem = 0; 
		},
		complete: function() {
			toggleLoader(0);
		}
	});
}

function populateRight(queryDate, bookingType) {
	toggleLoader(1);
	$.ajax({
		type: "POST",
		url: "step2/getTimes",
		async: true,
		data: "date="+queryDate+"&bookingType="+bookingType,
		cache: false,
		success: function(html){
			$('#bookingTimeListRight').append(html);
			$('#bookingTimeListRight h3').html($('#bookingTimeListRight .hiddenCurDateFormatted').html());
			setHandlersOnBookingtype();
			ajaxSem--;
			if(0 > ajaxSem)
				ajaxSem = 0; 
		},
		complete: function() {
			toggleLoader(0);
		}
	});
}


function popWindow(wName){
	window.name = "VetvisionMain";
	features = 'width=580,height=450,toolbar=no,location=no,directories=no,menubar=no,scrollbars=no,copyhistory=no,resizable=yes';
	pop = window.open('',wName,features);
	if(pop.focus){ pop.focus(); }
	return true;
}	

function showError(errorMsg) {
	$("#errorContainer").slideDown(1000);
}

function hideError(errorMsg) {
	$("#errorContainer").slideUp(1);
}

function addError(errorMsg) {
	$("div.errorContent").append('- '+errorMsg+'<br />');
}

function clearErrors() {
	$("div.errorContent").empty();
}

function l(mes) {
	return jsLanguage[mes];
}

function setDate() {
	// Split the string into day, month and year
	var inputArr = this.value.split('-');
	
	// Set the input fields to the right values
	$(":input#day").val(inputArr[0]);
	$(":input#month").val(inputArr[1]);
	$(":input#year").val(inputArr[2]);
}


