var html_content_new;

$(document).ready(function(){
	var html_obj = $('#new_item_hidden');
	html_content_new = html_obj.html();
	html_obj.html("");

	// flash inladen
	// als een div aangemaakt wordt met als class "flash",
	// en als inhoud het absolute pad naar de flash en de variable
	// wordt deze automatisch ingeladen
	$('.flash').each(function(){
		slideshowvars = $(this).find('.flashlink').html();
		slideshowheight = $(this).css('height');
		slideshowwidth = $(this).css('width');
		$(this).html("");
		$(this).flash({
	    	src: slideshowvars,
	    	width: slideshowwidth,
	    	height: slideshowheight,
			wmode: "normal"
		});
	});

		$('.flashtransparant').each(function(){
		slideshowvars = $(this).find('.flashlink').html();
		slideshowheight = $(this).css('height');
		slideshowwidth = $(this).css('width');
		$(this).html("");
		$(this).flash({
	    	src: slideshowvars,
	    	width: slideshowwidth,
	    	height: slideshowheight,
			wmode: "transparent"
		});
	});

	//Shadowbox.init();

	$(".del_act").click(function(){

		switch(taal){
                    case 'nl':
                        alert("Weet u zeker dat u dit arrangement wilt verwijderen");
                        break;
                    case 'de':
                        alert("Sind Sie sicher, dass Sie dieses Arrangement entfernen möchten");
                }

		$.ajax({
			type: "POST",
			url: "/private/helpers/ajax_arrangementen.php",
			data: "action=del_arrangement",
			dataType: "html"

		});

		var del_act = $(this).attr("id");
		var del_act_split = del_act.split("_");
		$("#activiteit_"+del_act_split['2']).html("");
		$("#activiteit_"+del_act_split['2']).hide();
		calculate_new_total_price();
	});

	$(".edit_act").click(function(){
		var edit_act = $(this).attr("id");
		var edit_act_split = edit_act.split("_");
		edit_item(edit_act_split['2']);
	});


	// links in "_blank" i.p.v. via HTML i.v.m. valid XHTML
	$('.blankwindow').attr('target','_blank');

	$("#calendar_blue_from").one("mouseover", function(){setupCalendar("datepicker_from", "%d-%m-%Y", "calendar_blue_from", false);});
	$("#calendar_blue_from2").one("mouseover", function() {setupCalendar("datepicker_from2", "%d-%m-%Y", "calendar_blue_from2", false);});

	$(".number_persons").inputInteger();
	$(".number_persons").keyup(function(){
		$(".act_number_pers").val($(".number_persons").val());
	});


	var activiteit_aantal = 1;


	$(".voeg_item_toe").click(function(){
		html_content = '<div id="new_item">'+html_content_new+'</div>';
		var new_starttime = $('#new_start_time').val();
		Shadowbox.open({
	        player:     	["html"],
	        content:    	html_content,
	        width:			500,
			height:			450,
			options:		{
	    		onFinish:		function(){

	    		$('#new_item').children

				$('#new_item .new_item_start_time option[value='+new_starttime+']').attr('selected', 'selected');
	    		//vul aantal personen alvast in.
	    		$('#new_item .new_item_num_pers').val($('.number_persons').val());

	    		$('#new_item .submit_new_item').click(function(){
	    			if($('#new_item .new_item_act').val() == '0')
					{
						switch(taal){
                                                    case 'nl':
                                                        alert("Selecteer svp een activiteit");
                                                        break;
                                                    case 'de':
                                                        alert("Wählen Sie bitte eine Aktivität");
                                                }
						return false;
					}
	    			var options = '';
	    			$('#new_item .new_item_option').each(function(){
	    				if($(this).attr("checked"))
	    				{
	    					if(options != '')
	    						options += ','+$(this).val();
	    					else
	    						options += $(this).val();
	    				}
	    			});
	    			paste_act_code($('#new_item .new_item_act').val(), $('#new_item .new_item_num_pers').val(), activiteit_aantal, $('#new_item .new_item_start_time').val(), options);
					activiteit_aantal++;
					//setTimeout('Shadowbox.close()','400');
				}).removeClass('submit_new_item');



				$('#new_item .new_item_cat').change(function(){
					fill_new_item_act($(this).val(), '');
				});

				$('#new_item .new_item_act').change(function(){
					fill_new_item_act_omsch($(this).val());
				});
		  },
		  onClose:			function(){
		  		calculate_new_total_price();
		  		set_new_start_time();
		  	}
		}

		});

	});


	$('.time').click();

	$('#verder').click(function(){
		var error = true;
		//check aantal personen.
		var aantal_act = 0;
		$('.act_id').each(function(){
			aantal_act++;
		});
		if(aantal_act == 0)
		{
                    	switch(taal){
                            case 'nl':
                                alert("selecteer minimaal 1 activiteit.");
                                break;
                            case 'de':
                                alert("Mindestens 1 Aktivität wählen.");
                        }
//			return false;
			error = false;
		}
		if($('.number_persons').val() == '')
		{
                        switch(taal){
                            case 'nl':
                                alert("vult u aub het aantal personen in waarmee u komt.");
                                break;
                            case 'de':
                                alert('Geben Sie bitte die Anzahl Personen ein, mit denen Sie kommen');
                        }
//			return false;
			error = false;
		}

		if($('#datepicker_from').val() == '')
		{
                        switch(taal){
                            case 'nl':
                                alert("vult u aub een datum is.");
                                break;
                            case 'de':
                                alert('Geben Sie bitte ein Datum ein');
                        }
			
			//return false;
			error = false;
		}
		else
		{
			var aDate = $('#datepicker_from').val().split('-');
			var today = new Date();
			var myDate = new Date();
			var month = parseInt((((aDate[1]-1)*100)/100));
			var day = parseInt((((aDate[0])*100)/100));
			var year = parseInt(aDate[2]);

			myDate.setDate(day);
			myDate.setMonth(month);
			myDate.setFullYear(year);

			if (myDate<today)
			{
                                switch(taal){
                                    case 'nl':
                                        alert("vult u aub een datum in die in de toekomst ligt");
                                        break;
                                    case 'de':
                                        alert('Bitte geben Sie ein Datum in der Zukunft ist.');
                                }

				error = false;
			}
		}

		if(!error)
			return false;
		else
			return true;
	});
});


	
Shadowbox.init({
	language:   "en",
	players:    ["html"]
});

function paste_act_code(act_id, num_per, new_id, start_time, options)
{
	$.ajax({
			type: "POST",
			url: "/" + taal + "/private/helpers/ajax_arrangementen.php",
			data: 'act_id='+act_id+'&num_per='+num_per+'&new_id='+new_id+'&start_time='+start_time+'&options='+options+'&action=paste_act',
			dataType: "html",
			success: function(result)
			{
				if(result != '')
				{
					$('#arrangement_activiteit').append(result);

					//set the new starttime.
					var end_laatste_act = $('#act_end_'+new_id).val();
					$('#begin_time_helper').val(end_laatste_act);
					$('#new_item_hidden .new_item_start_time option[value='+end_laatste_act+']').attr('selected', 'selected');

					$(".del_act").click(function(){
                                                var delText = "";
                                                switch(taal){
                                                    case 'nl':
                                                        delText = 'Weet u zeker dat u deze activiteit wilt verwijderen?';
                                                        break;
                                                    case 'de':
                                                        delText = 'Sind Sie sicher, dass Sie diese Aktivität entfernen möchten?';
                                                }

						if(confirm(delText)== true)
						{
							var del_act = $(this).attr("id");
							var del_act_split = del_act.split("_");
							$("#activiteit_"+del_act_split['2']).html("");
							$("#activiteit_"+del_act_split['2']).hide();

                                                        // Set new start time
                                                        var last_act_end_hour       = 9;
                                                        var last_act_end_minutes    = 00;
                                                        $('[id^=act_end_]').each(
                                                            function(){
                                                               var timeparts = $(this).val().split(":");
                                                               if((timeparts[0] > last_act_end_hour) || ((timeparts[0] == last_act_end_hour) && (timeparts[1] > last_act_end_minutes)))
                                                               {
                                                                    last_act_end_hour = timeparts[0];
                                                                    last_act_end_minutes = timeparts[1];
                                                               }
                                                            }
                                                        );
                                                        var last_act_end_time = "09:00";
                                                        if(last_act_end_hour < 10) {
                                                            if(last_act_end_minutes == 0){
                                                                last_act_end_time = "0" + last_act_end_hour + ":0" + last_act_end_minutes;
                                                            }else{
                                                                last_act_end_time = "0" + last_act_end_hour + ":" + last_act_end_minutes;
                                                            }
                                                        }else{
                                                            last_act_end_time = last_act_end_hour + ":" + last_act_end_minutes;
                                                        }
                                                        $('#begin_time_helper').val(last_act_end_time);
                                                        $('#new_item_hidden .new_item_start_time option[value='+last_act_end_time+']').attr('selected', 'selected');
                                                        set_new_start_time();

							calculate_new_total_price();
						}
					});

					$(".edit_act").click(function(){
						var edit_act = $(this).attr("id");
						var edit_act_split = edit_act.split("_");
						edit_item(edit_act_split['2']);
					});
				}
				Shadowbox.close();
				var aantal_activiteiten = $('#arrangement_activiteit .activiteit').size();
				if (aantal_activiteiten > 0)
				{
					$('.voeg_item_toe').attr('src','/public/img/form/'+taal+'/voeg_nog_een_toe.gif');
				}
				else
				{
					$('.voeg_item_toe').attr('src','/public/img/form/voeg_toe.gif');
				}
			}
	});
}

function fill_new_item_act(head_cat, cat_id)
{
	$.ajax({
			type: "POST",
			url: "/"+taal+"/private/helpers/ajax_arrangementen.php",
			data: 'head_cat='+head_cat+'&cat_id='+cat_id+'&action=get_act',
			dataType: "html",
			success: function(result)
			{
				if(result != '')
				{
					$('.new_item_act').html(result);
				}
			}
	});
}


function fill_new_item_act_omsch(cat_id)
{
	$.ajax({
			type: "POST",
			url: "/"+taal+"/private/helpers/ajax_arrangementen.php",
			data: 'cat_id='+cat_id+'&action=get_act_omsch',
			dataType: "html",
			success: function(result)
			{
				if(result != '')
				{
					$('.act_omschrijving').html(result);
				}
			}
	});
}

//global functions
function setupCalendar(inputField, inputFormat, inputButton, showTime, onUpdateCallback)
{
	if (onUpdateCallback==undefined) onUpdateCallback = null;

	Calendar.setup({
				inputField     :    inputField,   //"datum",     // id of the input field
				ifFormat       :    inputFormat,  //"%d-%m-%Y",      // format of the input field
				button         :    inputButton,  //"i_datum",  // trigger for the calendar (button ID)
				showsTime	   :	showTime,
				onUpdate       :	onUpdateCallback,
				singleClick    :    true

		});
}

function calculate_new_total_price()
{
	var total = 0;
	var total_pp = 0;
	$('#arrangement_activiteit .act_totalp').each(function(){
		var ppa = $(this).val().replace(',','.');
		var sub_total = ppa * 1;
		total += sub_total;
	});

	$('#arrangement_activiteit .act_totalpp').each(function(){
		var ppa = $(this).val();
		var sub_total_pp = ppa * 1;
		total_pp += sub_total_pp;
	});

//	$('#totaal_prijs').html('&euro; '+display_bedrag(Math.round(total)));
	$('#totaal_prijs').html('&euro; '+display_bedrag(total));
//	$('#totaal_prijs_pp').html('&euro; '+display_bedrag(Math.round(total_pp)));
	$('#totaal_prijs_pp').html('&euro; '+display_bedrag(total_pp));

}

function display_bedrag(waarde)
{
  // return the total rounded to two decimal places
	stringbedrag = waarde.toString();
  	stringbedrag = stringbedrag.replace(/\,/, ".");
	bedrag = round_decimals(stringbedrag, 2);
	stringbedrag = bedrag.toString();
	stringbedrag = stringbedrag.replace(/\./, ",");
	return stringbedrag;
}

function round_decimals(original_number, decimals) {
    var result1 = original_number * Math.pow(10, decimals)
    var result2 = Math.round(result1)
    var result3 = result2 / Math.pow(10, decimals)
    return pad_with_zeros(result3, decimals)
}

function pad_with_zeros(rounded_value, decimal_places) {

    // Convert the number to a string
    var value_string = rounded_value.toString()

    // Locate the decimal point
    var decimal_location = value_string.indexOf(".")

    // Is there a decimal point?
    if (decimal_location == -1) {

        // If no, then all decimal places will be padded with 0s
        decimal_part_length = 0

        // If decimal_places is greater than zero, tack on a decimal point
        value_string += decimal_places > 0 ? "." : ""
    }
    else {

        // If yes, then only the extra decimal places will be padded with 0s
        decimal_part_length = value_string.length - decimal_location - 1
    }

    // Calculate the number of decimal places that need to be padded with 0s
    var pad_total = decimal_places - decimal_part_length

    if (pad_total > 0) {

        // Pad the string with 0s
        for (var counter = 1; counter <= pad_total; counter++)
            value_string += "0"
        }
    return value_string
}


function set_new_start_time()
{
	var new_start_time = $('#begin_time_helper').val();
	$('#new_start_time').val(new_start_time);// .new_item_start_time option[value='+new_start_time+']').attr('selected', 'selected');
}

function edit_item(item_id)
{


		html_content = '<div id="new_item">'+html_content_new+'</div>';
		var new_starttime = $('#activiteit_'+item_id+' #act_time_'+item_id).val();
		var hoofd_cat = $('#activiteit_'+item_id+' .hoofd_actid').val();
		var cat_id = $('#activiteit_'+item_id+' .act_id').val();
		var aantal_pers = $('#activiteit_'+item_id+' #act_pers_'+item_id).val();
		var options = $('#activiteit_'+item_id+' .act_options_'+item_id).val();
		var options_split = options.split(',');

		Shadowbox.open({
	        player:     	'html',
	        content:    	html_content,
	        width:			500,
			height:			450,
			options:
			   {
		    	onFinish:		function(){
					$('#new_item .new_item_start_time option[value='+new_starttime+']').attr('selected', 'selected');
					$('#new_item .new_item_cat option[value='+hoofd_cat+']').attr('selected', 'selected');
					fill_new_item_act(hoofd_cat, cat_id);

					$('#new_item .act_omschrijving .new_item_option').each(function(){
						if(in_array($(this).val(), options_split))
							$(this).attr('checked',"checked");
					});

					fill_new_item_act_omsch(cat_id);

					//vul aantal personen alvast in.
		    		$('#new_item .new_item_num_pers').val(aantal_pers);

		    		$('.submit_new_item').click(function(){
						if($('#new_item .new_item_act').val() == '0')
						{
                                                        switch(taal){
                                                            case 'nl':
                                                                alert("Selecteer svp een activiteit");
                                                                break;
                                                            case 'de':
                                                                alert("Wählen Sie bitte eine Aktivität");

                                                        }
							return false;
						}
		    			var options = '';
		    			$('.new_item_option').each(function(){
		    				if($(this).attr("checked"))
		    				{
		    					if(options != '')
		    						options += ','+$(this).val();
		    					else
		    						options += $(this).val();
		    				}
		    			});
		    			paste_act_code_edit($('#new_item .new_item_act').val(), $('#new_item .new_item_num_pers').val(), item_id, $('#new_item .new_item_start_time').val(), options);
						setTimeout('Shadowbox.close()','400');

					});

					$('.new_item_cat').change(function(){
						fill_new_item_act($(this).val(), '');
					});

					$('.new_item_act').change(function(){
						fill_new_item_act_omsch($(this).val());
					});

					$('.new_item_num_pers').change(function(){
						$("#number_persons").val($(this).val());
					});
			  },
			  onClose:			function(){
			  		calculate_new_total_price();
			  		set_new_start_time();

			  	}
			}

	    });
}


function paste_act_code_edit(act_id, num_per, new_id, start_time, options)
{
	$.ajax({
			type: "POST",
			url: "/"+taal+"/private/helpers/ajax_arrangementen.php",
			data: 'act_id='+act_id+'&num_per='+num_per+'&new_id='+new_id+'&start_time='+start_time+'&options='+options+'&action=paste_act',
			dataType: "html",
			success: function(result)
			{
				if(result != '')
				{
					$('#activiteit_'+new_id).html(result);

					//set the new starttime.
					var end_laatste_act = $('#act_end_'+new_id).val();
					$('#begin_time_helper').val(end_laatste_act);
					$('#new_item_hidden .new_item_start_time option[value='+end_laatste_act+']').attr('selected', 'selected');

					$(".del_act").click(function(){
						alert("delete");

						var del_act = $(this).attr("id");
						var del_act_split = del_act.split("_");
						$("#activiteit_"+del_act_split['2']).html("");
						$("#activiteit_"+del_act_split['2']).hide();
						calculate_new_total_price();
					});

					$(".edit_act").click(function(){
						var edit_act = $(this).attr("id");
						var edit_act_split = edit_act.split("_");
						edit_item(edit_act_split['2']);
					});
				}
			}
	});
}

function nolink(){

}

function in_array(what, where){
	var a=false;
	for(var i=0;i<where.length;i++){
		if(what == where[i])
		{
	   		a=true;
	   		break;
	   	}
	}
	return a;
}



	// subs in/uitklappen
$(document).ready(function(){
	$('.subkop').click(function () {
		var obj = $(this).parents('.subblok').find('.subtext');
		var deze = $(this);

		$(this).parents('#subblokken').find('.subtext').slideUp('fast');
		$(this).removeClass('active');

			if (obj.css('display')=='none')
			{
				obj.slideDown('fast');
				$(this).addClass('active');
			}

	});
});