/* jquery mini easing */

jQuery.extend( jQuery.easing, {
		def: 'easeInElastice',
		easeInQuad: function (x, t, b, c, d) {
			return c*(t/=d)*t + b;
		},
		easeOutQuad: function (x, t, b, c, d) {
			return -c *(t/=d)*(t-2) + b;
		},
		easeInOutQuad: function (x, t, b, c, d) {
			if ((t/=d/2) < 1) return c/2*t*t + b;
			return -c/2 * ((--t)*(t-2) - 1) + b;
		},
		easeOutBack: function (x, t, b, c, d, s) {
			if (s == undefined) s = 10;
			return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
		}
});


$(document).ready(function(){


	/* adjust scroll widths to screen */
	var window_width = $(window).width();
	if (window_width <= 480) {
		var scroll_width = '280';
		var scroll_week = '246';
	} else {
		var scroll_width = '620';
		var scroll_week = '570';
	}


	/* Toggle items in map search */
	$(".controls h3").click(function(){
		$("#mapsearch").slideToggle();
	});

	$(".controls span.toggle").click(function(){
		$("#maplisting").slideToggle();
	});

	/* menu */

	$("#menu a").mouseover(function(){
		if($(this).hasClass("active")){ /* do nothing */ } else { $(".icon", this).stop().animate({top: "0px"}, 200); }
	}).mouseout(function(){
		$(".icon", this).stop().animate({top: "-50px"}, 200);  
	});

	/* index katsastus badge */

	$("#badge").mouseover(function(){
		$(this).animate({marginRight: "-=5px", marginTop: "-5px", width: "+=10px", height: "+=10px"}, {duration: 200, easing: "easeOutBack"});
	}).mouseout(function(){
		$(this).animate({marginRight: "+=5px", marginTop: "+=5px", width: "-=10px", height: "-=10px"}, {duration: 100, easing: "easeInOutQuad"});
	});

	/* calenderi */

	var weeks = 0;
	var currentWeek = "1";

	function checkWeeks(){

		$("#calendar .weeks .prev, #calendar .weeks .next").show();
		if(currentWeek=="1"){ $("#calendar .weeks .prev").hide(); }
		if(currentWeek==weeks){ $("#calendar .weeks .next").hide(); }

		$('#calendar .dropdown').html('viikko '+ $('#calendar .weekscroller .week:eq('+(currentWeek-1)+') input.weekNum').val());
	}

	checkWeeks();

	function closeTimes(){
		$("#calendar .week li.hour.active").removeClass("active");
		$("#calendar .weekshadow").fadeOut(200);
		$("#showtimes").fadeOut(200).remove();
	}

	$("#calendar .weeks a.next").click(function(){
		$("#calendar .weekscroller").animate({marginLeft: "-="+scroll_week+"px"}, 400);
		currentWeek++;
		checkWeeks();
		return false;
	});

	$("#calendar .weeks a.prev").click(function(){
		$("#calendar .weekscroller").animate({marginLeft: "+="+scroll_week+"px"}, 400);
		currentWeek--;
		checkWeeks();
		return false;
	});

	$("#calendar .week li.hour a").live('click',function(){
		var minutes = $(this).next(".times").html();
		var pos = $(this).offset();
		var posLeft = pos.left+"px";
		var posTop = pos.top+"px";
		$(this).parent().addClass("active");
		$("#calendar .weekshadow").fadeIn(200);

		$('#showtimes').remove();
		$("body").append("<ul id='showtimes'>"+minutes+"</ul>");
		$("#showtimes").css("left", posLeft);
		$("#showtimes").css("top", posTop);
		return false;
	});

	$("#showtimes a").live("click", function(event){
		var date = $(this).attr("title");
		var price = $(this).next(".hinta").text();
		var discount = $(this).parent().find(".discount").val();
		
		closeTimes();
		
		var station_id = $('input.paikka:checked').val();
		var price_id = $('input.priceID:checked').val();
		$.post('/module.php?id=62&act=reserveTime',{date:date,station_id:station_id,price_id:price_id},function(response) {
			if(isNaN(response)) {
				$(".error.page2").text("Aikaa valitessa tapahtui virhe. Valitse aika uudestaan.");
				$.post('/module.php?id=helppokatsastus&act=getCalendar',{station_id:station_id},function(data) {
					$('#calendar .weekscroller').html(data);
				});
			}
			else {
				$('#varattuID').val(response);
				$("#varattuaika").empty().text(date);
				$("#varattuhinta").empty().text(price+"€" + ((discount > 0) ? ' (Happy Hour -'+discount+'%)' : ''));
			}
		});
		return false;
	});

	$(".weekshadow").live('click',function() {
		closeTimes();
	});

	/* varausjuttuloita */

	var usedate = $("#usedate").val();

	if(usedate != "DD.MM.YYYY"){ $("#usedate").removeClass("value"); }

	$("#usedate").focus(function(){
		$(this).val("").removeClass("value");
	});

	function nextPage(){
		$("#varaa-scroller").animate({left: "-="+scroll_width+""}, 500);
		$("#varaa-steps li.active").removeClass("active").next("li").addClass("active");
		return false;
	}

	$(".page .button.prev").click(function(){
		$("#varaa-scroller").animate({left: "+="+scroll_width+"px"}, 500);
		$("#varaa-steps li.active").removeClass("active").prev("li").addClass("active");
		closeTimes();
		return false;
	});

	$("#step1").click(function(){

		var rn1 = $("#rekno1").val(); var rn2 = $("#rekno2").val(); var rn = rn1+"-"+rn2;
		var tyyppi = $("input.a1:checked").parent().text();
		var kv = $("input.b1:checked").parent().text();
		// var vm = ($("input#usedate").val() == 'DD.MM.YYYY') ? '' : $("input#usedate").val();
		var place = $("input.paikka:checked").attr("title");
		var address = $("input.paikka:checked").parent().find('.info span').html();

		if($("input#usedate").val() == 'DD.MM.YYYY') {
			$("input#usedate").val('');
			var vm = '';
		}
		else {
			var vm = $("input#usedate").val();
		}

		$("body").data("rekno", rn);
		$("body").data("tyyppi", tyyppi);
		$("body").data("kayttovoima", kv);
		$("body").data("vuosimalli", vm);
		$("body").data("asema", place);
		$("body").data("osoite", address);

		if(rn1 != "" && rn2 != "" && tyyppi != "" && kv != "" && $("input.paikka").is(":checked")){  

			// oik. palstaan: 

			$("#info-step1, #info-palvelut").show();
			$("#info-palvelut .content").empty();

			$("#info-rn").text(rn1 + "-" + rn2);
			$("#info-t").text(tyyppi);
			$("#info-kv").text(kv);
			$("#info-vm").text(vm);
			$("#info-asema .content").html("<b>"+place+"</b><br/>"+address);
			var total = "0";

			if($("#bpm").is(":checked")){
				var bpmhinta = $("#bpm").next().val();
				total = parseInt(bpmhinta);
				$("#info-palvelut .content.palvelut").append("<b>Bensapäästömittaus:</b> <span>"+bpmhinta+"€</span><br/>");
			}
			if($("#dpm").is(":checked")){
				var dpmhinta = $("#dpm").next().val();
				total = parseInt(total) + parseInt(dpmhinta);
				$("#info-palvelut .content.palvelut").append("<b>Dieselpäästömittaus:</b> <span>"+dpmhinta+"€</span><br/>");
			}
			if($("#obd").is(":checked")){
				var obdhinta = $("#obd").next().val();
				total = parseInt(total) + parseInt(obdhinta);
				$("#info-palvelut .content.palvelut").append("<b>OBD-mittaus:</b> <span>"+obdhinta+"€</span><br/>");
			}

			// $("#info-palvelut .content.palvelut").append("<b>Yhteensä: "+obdhinta+"€</b>");

			$("body").data("summa", total);
			$("body").data("summa-orig", total);

			//

			$(".error.page1").empty();
			
			var station_id = $('input.paikka:checked').val();
			var price_id = $('input.priceID:checked').val();
			
			var priceTitle = (price_id == 2) ? 'Jälkitarkastus' : 'Määräaikaiskatsastus';
			$("#info-palvelut .content.katsastus").html("<b>"+priceTitle+"</b><br/>");

			$.post('/module.php?id=helppokatsastus&act=getCalendar',{station_id:station_id,price_id:price_id},function(data) {
				$("#calendar").show();
				$('#calendar .weekscroller').html(data);
				weeks = $("#calendar .week").length;
				checkWeeks();
				nextPage();
			});

			return false;

		} else {
			$(".error.page1").text("Täytä kaikki kohdat");
			return false;
		}

	});

	$("#step2").click(function(){

		var aika = $("#varattuaika").text();
		var hinta = $("#varattuhinta").text();

		$("body").data("aika", aika);
		$("body").data("hinta", hinta);

		$('#varattuInput').val(aika.replace(/kello /gi,''));

		if(aika != "" && hinta != "" && $('#varattuInput').val() != ""){
			
			total = $("body").data("summa-orig");
			total = parseInt(total) + parseInt(hinta);

			$("#info-aika").show();
			$("#info-aika .content").text(aika);
			
			var price_id = $('input.priceID:checked').val();
			var priceTitle = (price_id == 2) ? 'Jälkitarkastus' : 'Määräaikaiskatsastus';
			$("#info-palvelut .content.katsastus").html("<b>"+priceTitle+":</b> <span>"+hinta+"</span><br/>");
			$(".error.page2").empty();

			$("body").data("summa", total);

			$("#yhteystiedot").show();
			nextPage();
			return false;

		} else {

			$(".error.page2").text("Valitse katsastusaika kalenterista");
			return false;

		}

	});

	$("#step3").click(function(){

		var nimi = $("input#nimi").val();
		var email = $("input#email").val();
		var osoite = $("input#osoite").val();
		var postinumero = $("input#postinumero").val();
		var kaupunki = $("input#kaupunki").val();
		var puh = $("input#puh").val();

		$("body").data("nimi", nimi);
		$("body").data("email", email);
		$("body").data("osoite", osoite);
		$("body").data("postinumero", postinumero);
		$("body").data("kaupunki", kaupunki);
		$("body").data("puhnro", puh);

		if(nimi != "" && osoite != "" && postinumero != "" && kaupunki != "" && puh != "") {

			$("#yhteenveto").show();

			nextPage();

			$('#autontiedot .content').html($('#info-step1 .content').html());
			$('#yhteystiedot .content').html('<b>Nimi:</b> '+nimi+'<br /><b>Sähköposti:</b> '+email+'<br /><b>Osoite:</b> '+osoite+'<br /><b>Postinumero:</b> '+postinumero+'<br /><b>Kaupunki:</b> '+kaupunki+'<br /><b>Puhelin:</b> '+puh);
			$('#katsastustiedot .content').html('<b>Katsastusaika</b><br/>'+$('#info-aika div').html()+'<br/><br/>'+$('#info-asema .content').html());
			$('#palvelut .content').html('');
			$.each($('#info-palvelut .content'),function() {
				$('#palvelut .content').append($(this).html());
			});
			$('#palvelut .content').append('<b>Yhteensä : '+total+'&euro;');

			return false;

		} else {

			$(".error.page3").text("Täytä tarvittavat kentät");
			return false;

		}

	});

	$('#vahvista').live("click", function() {

		if($('input#ehdotCB:checked').length === 0) {
			$(".error.page3").text("Hyväksy varausehdot");
			return false;
		} else {
			$("form#varauslomake").submit();
			return false;
		}
	});
});  

function getServices() {
	if(!$('input.paikka:checked').length) { return; }

	var url = '/module.php?id=62&act=getServices';
	var station_id = $('input.paikka:checked').val();
	$.post(url,{station_id:station_id},function(response) {
		if(response.length == 0) { return; }
		$('#stationServices').html(response);
		$('#stationServices input').click(checkCampaign);
	});
}
function checkCampaign(isObj) {
	var input = $('input#campaign');
	
	if(isObj !== false && $(this).attr('id') == 'obd') { return; }
	
	var obj = ($('#bpm:checked').length) ? $('#bpm') : (($('#dpm:checked').length) ? $('#dpm') : false);
	if(!obj) {
		if(isObj !== false) {
			obj = $(this);
			var objInput = obj.parent().find('.price');
			var objValue = parseInt(objInput.val());
			if(objInput.data('orig') == undefined) {
				objInput.data('orig',objValue);
			}
		
			objValue = objInput.data('orig');
			obj.parent().find('.price').val(objValue);
			obj.parent().find('span').removeClass('green').html(obj.parent().find('span').html().replace(' -5€ alennus)',')'));
			$('#campaignText, #campaignCheck').hide();
		}
		return;
	}
	
	var objInput = obj.parent().find('.price');
	var objValue = parseInt(objInput.val());
	
	if(objInput.data('orig') == undefined) {
		objInput.data('orig',objValue);
	}
	
	if(input.val().toUpperCase() == 'FACEBOOK' || (input.val().toUpperCase() == 'VANTAA INFO') || (input.val().toUpperCase() == 'TURKU') || (input.val().toUpperCase() == 'MLL') || (input.val().toUpperCase() == 'LAHTI' && $('input.paikka:checked').val() == 4)) {
		if(!obj.parent().find('span').hasClass('green')) {
			objValue = objValue-5;
			obj.parent().find('.price').val(objValue);
			obj.parent().find('span').addClass('green').html(obj.parent().find('span').html().replace(')',' -5€ alennus)'));
			$('#campaignText, #campaignCheck').show();
		}
	}
	else {
		objValue = objInput.data('orig');
		obj.parent().find('.price').val(objValue);
		obj.parent().find('span').removeClass('green').html(obj.parent().find('span').html().replace(' -5€ alennus)',')'));
		$('#campaignText, #campaignCheck').hide();
	}
}
