function strpos (haystack, needle, offset) {
    var i = (haystack + '').indexOf(needle, (offset || 0));
    return i === -1 ? false : i;
}

$(document).ready(function() {
	
	noProducts = true;
	noProductsLine = '';
	
	function currentStep(step)
	{
		var step = step;

		if(($.cookie("step") != null) && (typeof step == 'undefined'))
		{
			step = $.cookie("step");	
		}

		if(($.cookie("step") == null) && (typeof step == 'undefined'))
		{
			step = 1;
		}
		
		if(step == 1)
		{
			loadstep1();
			
			$.cookie("step",'1');
		}
		else if(step == 2)
		{
			loadstep2();
			
			$.cookie("step",'2');
		}
		else if(step == 3)
		{
			loadstep3();
			
			$.cookie("step",'3');
		}
	}
	
	function productSubTotal()
	{
		var subtotal = 0;
		
		$('#productOverviewChart tr .totalProductPrice').each(function()
		{
			subtotal += parseFloat($(this).html());
		})
		
		subtotal = subtotal.toFixed(2)
		
		$('#subtotal').html(subtotal);
	}
	
	function removeProduct(element)
	{
		$(element).parent().remove();
		
		i = 0;
		
		$('#productOverviewChart tr .totalProductPrice').each(function()
		{
			i++;	
		})
		
		if(i == 0)
		{
			$('#productOverviewChart').append('<tr id="noProducts">'+noProductsLine+'</tr>');
			
			noProducts = true;	
		}
		
		id = $(element).parent().attr('id').split('_');
		
		$.post('/ajax/session.php',{productId:id[1], type:'remove'}, function(data) {
		});
		
		productSubTotal();
	}
	
	function chartHashProducts()
	{
		var i = 0;
		
		$('#productOverviewChart tr').each(function()
		{
			i++;
		})
		
		if(i != 1)
		{
			noProductsLine = $('#noProducts').html();
			$('#noProducts').remove();
			noProducts = false;
		}
	}
	
	function loadstep1()
	{			
		$('#step_1 .reservationNumber').css('background-image',"url(/img/circleBlue.png)");
		$('#step_2 .reservationNumber').css('background-image',"url(/img/circleGray.png)");
		$('#step_3 .reservationNumber').css('background-image',"url(/img/circleGray.png)");
		
		$.post('/ajax/step1.php', function(data) {
			$('#reservationProgress').html(data);
			productSubTotal();
			chartHashProducts();
		});
		
		$('#productGroup ul li').die('click');
		
		$('#productGroup ul li').live('click', function() {
			id = $(this).attr('id').split('_');
					
			if(id[1] == 0)
			{
				$.post('/ajax/arrangementen.php',function(data) {
					$('#products').html(data);
				});	
			}
			else
			{
				$.post('/ajax/products.php',{id:id}, function(data) {
					$('#products').html(data);
				});
			}
		
		});
		
		$('.removeProduct').die("click");
		
		$('.removeProduct').live('click', function() {
			removeProduct(this);
		})

                $('.specialproductAdd').die("click");

                $('.specialproductAdd').live('click', function() {

                        id = $(this).attr('id').split('_');

                        id = id[1];
                        element = this;

                        found = false;
                        
         
                        $.post('/ajax/productoptions.php',{product:id}, function(data) {

                            $( "#dialog-modal" ).html(data);

                        });

                        $( "#dialog-modal" ).dialog({

                                width: 500,
                                modal: true
                        });

                 
                        
                        $('#productOverviewChart tr').each(function()
                        {
                                if($(this).hasClass($(element).attr('id')))
                                {
                                        found = true;
                                }
                        })

                        price = $(this).find('.productPrice').html();

                        var children = $(this).find('.productChildren').html();

                        if(found == false)
                        {
                                $('#productOverviewChart').append('<tr id ="productChart_'+id+'" class="'+$(element).attr('id')+'">'+$(element).html()+'<td class="totalProductPrice">'+price+'</td><td class="removeProduct"></td></tr>');
                                $('#productChart_'+id+' .productNumber').html(1);
                                $('#productChart_'+id+' .productPrice').html(price);

                                if(noProducts == true)
                                {
                                        noProductsLine = $('#noProducts').html();

                                        numberProducts = 1;

                                        $('#noProducts').remove();

                                        noProducts = false;
                                }

                            $.post('/ajax/session.php',{productId:id,productNumber: 1}, function(data) {
                            });

                        }
                        else
                        {
                                numberProducts = $('#productChart_'+id+' .productNumber').html();

                                numberProducts ++;

                                price = price * numberProducts;

                                price = price.toFixed(2);

                                $('#productChart_'+id).find('.totalProductPrice').html(price);

                                $('#productChart_'+id+' .productNumber').html(numberProducts);

                            $.post('/ajax/session.php',{productId:id,productNumber: numberProducts}, function(data) {
                            });

                        }


                        productSubTotal();

                });

		
		$('.productAdd').die("click");

		$('.productAdd').live('click', function() {

			id = $(this).attr('id').split('_');
			
			id = id[1];
			
			element = this;
			
			found = false;


			
			$('#productOverviewChart tr').each(function()
			{
				if($(this).hasClass($(element).attr('id')))
				{
					found = true;
				}
			})
			
			price = $(this).find('.productPrice').html();

                        var children = $(this).find('.productChildren').html();
			
			if(found == false)
			{				
				$('#productOverviewChart').append('<tr id ="productChart_'+id+'" class="'+$(element).attr('id')+'">'+$(element).html()+'<td class="totalProductPrice">'+price+'</td><td class="removeProduct"></td></tr>');
				$('#productChart_'+id+' .productNumber').html(1);
				$('#productChart_'+id+' .productPrice').html(price);
				
				if(noProducts == true)
				{
					noProductsLine = $('#noProducts').html();
					
					numberProducts = 1;
					
					$('#noProducts').remove();
					
					noProducts = false;
				}

                            $.post('/ajax/session.php',{productId:id,productNumber: 1}, function(data) {
                            });

			}
			else
			{
				numberProducts = $('#productChart_'+id+' .productNumber').html();
				
				numberProducts ++;
				
				price = price * numberProducts; 
				
				price = price.toFixed(2);
				
				$('#productChart_'+id).find('.totalProductPrice').html(price);
				
				$('#productChart_'+id+' .productNumber').html(numberProducts);

                            $.post('/ajax/session.php',{productId:id,productNumber: numberProducts}, function(data) {
                            });

			}
			
			
			
			productSubTotal();
			
		});
	}
	
	$('.reservationStep').die("click");
	
	$('.reservationStep').live('click', function() {
		
		step = $(this).attr('id').split('_');
		
		currentStep(step[1]);
	});
	
	$('#createAccount').die("click");
	
	$('#createAccount').live('click', function() {
		$.post('/ajax/createAccount.php', function(data) {
			$('#loginOrSubsribe').html(data);
			
			$("#registrateForm").validate({
				rules: 
				{
					username: "required",
					firstname: "required",
					lastname: "required",
					sex: "required",
					adres: "required",
					houseNumber: "required",
					zipcode: "required",
					city: "required",
					phonenumber: "required",
					birthday: "required",
					email: {
						required: true,
						email: true
					},
					username: {
						required: true,
						minlength: 2
					},
					password: {
						required: true,
						minlength: 5
					},
					password2: {
						required: true,
						minlength: 5,
						equalTo: "#password"
					}
				},
				messages:
				{
					username: 	"Gebruikersnaam is verplicht",
					firstname:	"Voornaam is verplicht",
					lastname:	"Uw achternaam is verplicht",
					sex: "Verplichte keuze",
					adres: "Verplicht veld",
					houseNumber: "Uw huisnummer",
					zipcode: "Uw postcode",
					city: "Uw woonplaats",
					phonenumber: "Uw telefoonnummer",
					birthday: "Uw verjaardag",
					email: {
						required : "Uw emailadres",
						email : "graag een geldig emailadres"
					},
					username:	{
						required: "Gebruikersnaam is verplicht",
						minlength: "Minimale lengte is 2"
					},
					password: {
						required: "Een wachtwoord is verplicht",
						minlength: "Het wachtwoord moet 5 tekens lang zijn"
					},
					password2: {
						required: "Vul uw wachtwoord nogmaals in",
						minlength: "Het wachtwoord moet 5 tekens lang zijn",
						equalTo: "Uw wachtwoorden zijn niet het zelfde"
					}
				}
			});
			
			$("#timeForm").validate({
				rules: 
				{
					arrivalDate: "required",
					arrivalTime: "required",
					leavingTime: "required"
				},
				messages:
				{
					arrivalDate: 	"Datum",
					arrivalTime:	"Aankomst tijd",
					leavingTime:	"Vertrek tijd"
				}
			});
		});
	});
	
	$('#createAccountDB').die("click");
	
	$('#createAccountDB').live('click', function() {
		$("#timeForm").validate().form();
		
		$("#registrateForm").validate({
			rules: 
			{
				username: "required",
				firstname: "required",
				lastname: "required",
				sex: "required",
				adres: "required",
				houseNumber: "required",
				zipcode: "required",
				city: "required",
				phonenumber: "required",
				birthday: "required",
				email: {
					required: true,
					email: true
				},
				username: {
					required: true,
					minlength: 2
				},
				password: {
					required: true,
					minlength: 5
				},
				password2: {
					required: true,
					minlength: 5,
					equalTo: "#password1"
				}
			},
			messages:
			{
				username: 	"Gebruikersnaam is verplicht",
				firstname:	"Voornaam is verplicht",
				lastname:	"Uw achternaam is verplicht",
				sex: "Verplichte keuze",
				adres: "Verplicht veld",
				houseNumber: "Uw huisnummer",
				zipcode: "Uw postcode",
				city: "Uw woonplaats",
				phonenumber: "Uw telefoonnummer",
				birthday: "Uw verjaardag",
				email: {
					required : "Uw emailadres",
					email : "graag een geldig emailadres"
				},
				username:	{
					required: "Gebruikersnaam is verplicht",
					minlength: "Minimale lengte is 2"
				},
				password: {
					required: "Een wachtwoord is verplicht",
					minlength: "Het wachtwoord moet 5 tekens lang zijn"
				},
				password2: {
					required: "Vul uw wachtwoord nogmaals in",
					minlength: "Het wachtwoord moet 5 tekens lang zijn",
					equalTo: "Uw wachtwoorden zijn niet het zelfde"
				}
			}
		});
		
		if(($("#timeForm").validate().form()) && ($("#registrateForm").validate().form()))
		{
			$.post('/ajax/createAccountDB.php',$("#registrateForm").serialize(), function(data){
			
				saveTime();
			
				currentStep(3);	
			})
		}
	});
	
	$('#loginSubmit').die("click");
	
	$('#loginSubmit').live('click', function() {
		loginName = $('#loginName').attr('value');
		password = $('#password').attr('value');
		
		$.post('/ajax/login.php', {loginName:loginName,password:password}, function(data) {
			if(data == 1)
			{
				saveTime()
				currentStep(3);
			}
			else
			{
				$('#loginScreen').append('<tr class="loginError"><td colspan="3">Verkeerde gebruikersnaam en/of wachtwoord</td></tr>');
				
				$('.loginError').delay(2000).fadeOut();
				$('.loginError').delay(1000).remove();	
			}
		});
	});
	
	
	$('#buttonNextStep').die("click");
	
	$('#buttonNextStep').live('click', function() {
		
		$.cookie("step", "2");
		
		currentStep(2);
	})
	
	$('#processOrder').die("click");
	
	$('#processOrder').live('click', function() {
		$.post('/ajax/processOrder.php', function(data) {
			$('#reservationProgress').html(data);
			$.cookie("arrivalTime", null);
			$.cookie("leavingTime", null);
			$.cookie("step", null);
		});
	});
	
	function saveTime()
	{
		arrivalDate = $('#arrivalDate').attr('value');
		arrivalTime = $('#arrivalTime').attr('value');
		leavingTime = $('#leavingTime').attr('value');
		personAmount = $('#personAmount').attr('value');
		
		$.post('/ajax/sessionTime.php', {arrivalDate:arrivalDate,arrivalTime: arrivalTime,leavingTime:leavingTime,personAmount:personAmount}, function(data) {
			$.cookie('arrivalDate',arrivalDate);
			$.cookie('arrivalTime',arrivalTime);
			$.cookie('leavingTime',leavingTime);
			$.cookie('personAmount',personAmount);
		});	
	}
	
	function loadstep2()
	{	
		$('#step_1 .reservationNumber').css('background-image',"url(/img/circleGray.png)");
		$('#step_2 .reservationNumber').css('background-image',"url(/img/circleBlue.png)");
		$('#step_3 .reservationNumber').css('background-image',"url(/img/circleGray.png)");
		
		$.post('/ajax/step2.php', function(data) {
			$('#reservationProgress').html(data);
			if($.cookie('arrivalTime') != null)
			{
				$('#arrivalTime').val($.cookie('arrivalTime'));
			}
			
			if($.cookie('leavingTime') != null)
			{
				$('#leavingTime').val($.cookie('leavingTime'));
			}
			$( "#arrivalDate" ).datepicker({
				showOn: "button",
				buttonImage: "images/calendar.gif",
				buttonImageOnly: true,
				showOtherMonths: true,
				selectOtherMonths: true,
				dateFormat: 'dd-mm-yy',
				firstDay: 1,
				dayNamesMin: ['Zo', 'Ma', 'Di', 'Wo', 'Do', 'Vr', 'Za'],
				monthNames: ['Januari','Februari','Maart','April','Mei','Juni','Juli','Augustus','September','Oktober','November','December']
			});
			$( "#birthday" ).datepicker({
				showOn: "button",
				buttonImage: "images/calendar.gif",
				buttonImageOnly: true,
				showOtherMonths: true,
				selectOtherMonths: true,
				dateFormat: 'dd-mm-yy',
				changeYear: true,
				firstDay: 1,
				dayNamesMin: ['Zo', 'Ma', 'Di', 'Wo', 'Do', 'Vr', 'Za'],
				monthNames: ['Januari','Februari','Maart','April','Mei','Juni','Juli','Augustus','September','Oktober','November','December']
			});
		});
	}
	
	function loadstep3()
	{	
		$('#step_1 .reservationNumber').css('background-image',"url(/img/circleGray.png)");
		$('#step_2 .reservationNumber').css('background-image',"url(/img/circleGray.png)");
		$('#step_3 .reservationNumber').css('background-image',"url(/img/circleBlue.png)");
		
		$.post('/ajax/step3.php', function(data) {
			$('#reservationProgress').html(data);
		});
	}
	
	currentStep();
});

function close_box()
{

	for(x = 0; x < 4; x++) {

		
	    for(i = 0; i < 10; i++) {
	
	        if($('#' + x + '_product_option_' + i).length > 0 ) {
	            var name = $('#' + x + '_product_option_' + i).find("option:selected").text();
	
	            var id = $('#' + x + '_product_option_' + i).val();
	            var price = 0;
	            //var name = $("#product_option_' + i + ' option:selected").text();
	
	            $('#productOverviewChart').append('<tr id ="productChart_'+id+'"><td>'+name+'</td><td class="totalProductPrice">'+price+'</td><td>1</td><td>0</td><td class="removeProduct"></td></tr>');
	
	            $.post('/ajax/add_special_product.php',{productId:id,productNumber: 1, free: true}, function(data) {
	
	
	
	            });
	
	        }
	    }

    }

    

    $( "#dialog-modal" ).dialog('close');

    return true;
}

function add_page_product(id)
{
     $.post('/ajax/add_page_product.php',{productId:id,productNumber: 1}, function(data) {

        window.location = '/reserveren.html';

     });



}
