$(document).ready(function(){
	// flash inladen
	// als een div aangemaakt wordt met als class "js_flash",
	// en als inhoud het absolute pad naar de flash en de variable
	// wordt deze automatisch ingeladen
	$('.js_flash').each(function(){
		slideshowvars = $(this).find('.js_flashlink').html();
        //strip HTML comment from flash vars
		slideshowvars = slideshowvars.replace(/^<!--/, "");
		slideshowvars = slideshowvars.replace(/-->$/, "");
		slideshowheight = $(this).css('height');
		slideshowwidth = $(this).css('width');
		var altcontent = $(this).html();
		$(this).html('');
		$(this).flash({
	    	src: slideshowvars,
	    	width: slideshowwidth,
	    	height: slideshowheight,
			wmode: 'transparent'
		},
		{
			version: '9', // flash versie checken (9 of hoger)
			update: false // niet upgraden (maar alt. inhoud tonen)
		});
		if (0 == $(this).find('embed').length && 0 == $(this).find('object').length) // niet juiste versie of geen flash, dan inhoud weer tonen
		{
			$(this).html(altcontent);
		}
	});

	// png fix op document
	// edaarna colorboxinladen (ivm conflict)
    if (typeof $().colorbox != 'function')
    {
        // png fix op document
        // edaarna colorboxinladen (ivm conflict)
        $(document).pngFix().getScript('/public/js/jquery.colorbox-min.js', function() {


            /**
             *	-- Gebruik --
             *	Geef een anchor de class .js_colorbox en de href de locatie van de afbeelding
             *	Voor een slideshow:
             *	Geef meerdere anchor's met .js_colorbox dezelfde rel="" waarde
             *	Voorbeeld slideshow:
             *	<a class="js_colorbox" rel="testblaat" href="/public/img/video2.jpg">klik</a>
             *	<a class="js_colorbox" rel="testblaat" href="/public/img/banner.jpg">klik</a>
             */
            //set
            $('.js_colorbox').colorbox({
                transition:'elastic',
				current: false
            });

            /**
            * Html tonen in colorbox:
            * <a class="js_htmlcolorbox" rel="idvanjehtmldiv">Klik</a>
            */
            $('.js_htmlcolorbox').click(function(){
                var targetid = $(this).attr('rel');
                if (typeof targetid == 'undefined' || targetid == '') return ;

                $(this).colorbox({
                    open: true,
                    inline:true,
                    transition:'none',
                    href:"#" + targetid
                });
            });

            /**
            * Contact form tonen in colorbox:
            * Verschil met htmlcolorbox is
            * dat deze de pagina herlaadt als hij sluit
            * (om form te resetten)
            * <a class="js_contactcolorbox" rel="idvanjehtmldiv">Klik</a>
            */
            $('.js_contactcolorbox').click(function(){
                var targetid = $(this).attr('rel');
                if (typeof targetid == 'undefined' || targetid == '') return ;

                $(this).colorbox({
                    open: true,
                    inline:true,
                    transition:'none',
                    href:"#" + targetid,
                    onClosed:function(){
                        // pagina herladen
                        if(ajaxFormChanged) {
                            window.location.href = window.location.href;
                        }
                    }
                });
            });

            /**
            * Youtube movie tonen in colorbox:
             *	Voor een slideshow:
             *	Geef meerdere anchor's met .colorbox dezelfde rel="" waarde
             *	Voorbeeld slideshow:
            * <a class="js_youtubecolorbox" rel="testblaat" href="http://www.youtube.com/v/[movie-id]">Klik</a>
            */
            $('.js_youtubecolorbox').colorbox({
                iframe:true,
                innerWidth: 640,
                innerHeight:505,
                transition:'elastic'
            });
        });
    }

	//## Klapblokken ##

	if (0 < $('.js_uitklapblokken').length)
	{
		$('.js_uitklaplink').click(function ()
		{
			var obj = $(this).parents('.js_uitklapblok:first').find('.js_uitklapdetail:first');

			if (!$(this).hasClass('js_keepothers')) //andere blokken sluiten
			{
				$(this).parents('.js_uitklapblokken').find('.js_uitklapdetail').each(function(){
					if (!$(this).hasClass('js_dontclose')) //dit blok niet altijd open houden
					{
						$(this).slideUp();
						$(this).find('.js_uitklaplink').removeClass('open');
					}
				})
			}

			//overal active verwijderen
			$(this).parents('.js_uitklapblokken').find('.js_uitklaplink').removeClass('active');

			if (obj.css('display')=='none') //geklikt item openen
			{
				obj.slideDown('fast', function(){$(this).css('display', 'block');}); //callback zodat het in IE8 nog steeds werkt
				$(this).addClass('active');
				$(this).addClass('open');
			}
			else //geklikt item sluiten
			{
				obj.slideUp('fast');
				$(this).removeClass('open');
			}
		});
	}

	//field hints
	$(".js_hintfield").each(function(i) {
        var beginStyle = $(this).attr("style");
		$(this).addClass("js_hint");
		$(this).val($(this).attr("title"));

        $(this).bind("focus", function(e) {
            if ($(this).val() == $(this).attr("title")) {
                $(this).val("");
				$(this).removeClass("js_hint");
            }
        });
        $(this).bind("blur", function(e) {
            if ($(this).val() == "") {
				$(this).addClass("js_hint");
				$(this).val($(this).attr("title"));
            } else {
				$(this).removeClass("js_hint");
			}
        });
    });

	//submit form link
	$('.js_submitform').click(function(){
		$(this).parents('form:first').submit();
		return false;
	})

	//AJAX FORMS automatisch
	if (typeof $().ajaxForm == 'function')
	{
		$('form.js_ajaxform').each(function(){
			$(this).append('<input type="hidden" name="ajax_post" value="oke" />');
			var form = $(this);
			$(this).ajaxForm({
				dataType: 'json',
				beforeSerialize: function(){
					form.find('.js_hint').val('');
					$('.js_cleartext').each(function(){
						if($(this).val() == $(this).attr("data-value"))
						{
							$(this).val("");
						}
					});
				},
				beforeSubmit: function(){
					form.parent().find('.js_errormelding').remove();
					form.find('.js_submitform').hide();
				},
				success: function(response){
					if (response.success)
					{
						form.html('<p>'+response.message+'</p>');
						
						if ( typeof _gaq == 'object' )
							_gaq.push(['_trackPageview', location.pathname + '-bedankt']);
						else if ( typeof pageTracker == 'object' )
							pageTracker._trackPageview( location.pathname + '-bedankt' );
					}
					else if (response.message)
					{
						form.before($('<p class="foutmelding js_errormelding">'+response.message+'</p>'));
						$('.js_cleartext').each(function(){
							if($(this).val() == '')
							{
								$(this).val($(this).attr("data-value"));
							}
						});
					}
					form.find('.js_hint').trigger('blur');
					form.find('.js_submitform').show();
				}
			})
		});

		$('form.js_reserverenform').each(function(){
			$(this).append('<input type="hidden" name="ajax_post" value="oke" />');
			var form = $(this);
			$(this).ajaxForm({
				dataType: 'json',
				beforeSubmit: function(){
					$('.js_tabcontent li').each(function(){
						$(this).find('.js_errormelding').remove();
					});
					form.find('.js_hidesubmit').hide();
				},
				success: function(response){
					if (response.success)
					{
						if(response.stap == 'complete')
						{
							$('.js_formreplace').html('<p>'+response.message+'</p>');

							if ( typeof _gaq == 'object' )
								_gaq.push(['_trackPageview', location.pathname + '-bedankt']);
							else if ( typeof pageTracker == 'object' )
								pageTracker._trackPageview( location.pathname + '-bedankt' );
						}
						else
						{
							var clicked = $('input[name="clicked"]').val();
							
							setReserverenOverzicht();

							$('.js_tabnav a').removeClass('active');
							$('.js_tabnav a').each(function(){
								if($(this).attr('alt') == clicked)
								{
									$(this).addClass('active');
								}
							});
							$('input[name="stap"]').val(clicked);
							$('.js_tabcontent li').slideUp();
							$('.js_tabcontent').find('.'+clicked).slideDown();
						}
					}
					else if (response.message && response.stap)
					{
						$('.js_tabcontent').find('.'+response.stap).prepend('<p class="foutmelding js_errormelding">'+response.message+'</p>');
					}
					form.find('.js_hint').trigger('blur');
					form.find('.js_hidesubmit').show();
				}
			})
		});
	}

	$('.js_photoslider li').css('display','block');

	$('.js_photoslider').sudoSlider({
        prevNext: false,
		speed:'400',
		fade: true,
        crossFade: false,
        customLink:'a.js_photosliderlink'
    });

	$(".js_next").click(function(){
		// breedte van de ul bepalen aan de hand van li's (sudoslider doet dat niet goed)
		var ul = $(this).siblings(".js_detailthumbslider").find("ul"); // juiste ul bepalen aan de hand van positie knop
		var ulbreedte = 0;

		ul.find("li").each(function(){
			ulbreedte += Math.round($(this).width());
		});
		// ul iets grotere breedte geven, zodat li's passen
		ul.css('width', ulbreedte+10);

		// sliden
		if(!ul.hasClass('animating') && ulbreedte > 390){ // alleen scrollen als dat niet nog bezig is en niet alles in beeld is

			// status op animating zetten middels class aan ul
			ul.addClass('animating');

			// nog niet bijna aan het einde? Dan hele 350pixels scollen (iets minder als breedte)
			if(ul.css('margin-left').replace('px','') > 780 - ulbreedte)
			{
				ul.animate(
					{marginLeft: '-=350px'},
					750,
					function() {
   						ul.removeClass('animating');
  					});

			}
			else // anders scrollen naar het einde
			{
				ul.animate(
					{marginLeft: 395 - ulbreedte + 'px'},
					500,
					function() {
   						ul.removeClass('animating');
  					});
			}
		}
	});

	$(".js_prev").click(function(){

		// juiste ul bepalen aan de hand van positie knop
		var ul = $(this).siblings(".js_detailthumbslider").find("ul");

		// sliden
		if(!ul.hasClass('animating')){ // alleen scrollen als dat niet nog bezig is

			// status op animating zetten middels class aan ul
			ul.addClass('animating');

			// nog niet bijna aan het einde? Dan hele 350pixels scollen (iets minder als breedte)
			 if(ul.css('margin-left').replace('px','') <= -390)
			{
				ul.animate(
						{marginLeft: '+=330px'},
						750,
						function() {
							ul.removeClass('animating');
						});
			}
			else // anders scrollen naar 0
			{
				ul.animate(
					{marginLeft: '0px'},
					500,
					function() {
   						ul.removeClass('animating');
  					});
			}
		}
	});

	rotate('.js_banners', '.dynamischebanner',6000,3000);
	if ( 0 < $('.js_twitterlist').length  )
	{
		var maxTweets = 3;

		$.ajax({
			url: "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=oldheino&count="+maxTweets,
			success: function(data) {
				for(var i=0;i<maxTweets;i++)
				{
					if(typeof(data[i]) != 'undefined')
						$('.js_twitterlist').append("<div class='twittercontent'>"+data[i].text+"<br /><span class='date'>"+relative_time(data[i].created_at)+"</span></div>");
				}
				rotate('.js_twitterlist', '.twittercontent',10000,2000);
			},
			dataType: 'jsonp'
		});
	}
	
	$('.js_tabcontent li:first').show();
	$('.js_tabnav a').click(function(){
		var clicked =$(this).attr('alt');
		$('input[name="clicked"]').val(clicked);

		$('.js_reserverenform').submit();
	});
	
	$('.js_bungalowtype').change(function() {
		if( 'De Colckhof' == $(this).val() ) {
			$('.js_aantalpersonen').attr('disabled','disabled');
		}
		else {
			$('.js_aantalpersonen').attr('disabled','');
		}
	});
	
	$('.js_besteloverzicht p:odd').css('background-color','#f7f9f6');

	var setReserverenOverzicht = function(){
		$('.js_reserverenform').find('input, select, textarea').each(function(){
			if($(this).attr('name') != 'opties[]')
			{
				if($(this).attr('data-value') != $(this).val())
					$('span[data-name='+$(this).attr('name')+'_value]').html(nl2br(htmlentities($(this).val())));
			}
			else
			{
				var id_parts = $(this).attr("id").split("_");
				if($(this).attr("checked") == true)
					$('span[data-name=optie_'+id_parts[1]+'_value]').html(yes);
				else
					$('span[data-name=optie_'+id_parts[1]+'_value]').html(no);
			}
		});

		$('span[data-name=aankomstdatum_value]').html($('select[name="aankomstdatum_dag"]').val() + "-" + $('select[name="aankomstdatum_maand"]').val() + "-" + $('select[name="aankomstdatum_jaar"]').val());
		$('span[data-name=vertrekdatum_value]').html($('select[name="vertrekdatum_dag"]').val() + "-" + $('select[name="vertrekdatum_maand"]').val() + "-" + $('select[name="vertrekdatum_jaar"]').val());
	}
	
	$('.js_bungalowinfo').hide();
	$('.js_plattegrond area').click(function(){
		currentBungalow = $(this).attr('alt');
		$('.js_bungalowinfo').hide();
		$('.js_bungalowinfo.'+currentBungalow).show();
	});

	$('.js_cleartext').focus(function(){
		if($(this).val() == $(this).attr("data-value"))
			$(this).val("");
	});

	$('.js_cleartext').blur(function(){
		if($(this).val() == "")
			$(this).val($(this).attr("data-value"));
	});

        $('.js_addfile').click(function(){
            var index =  $('.js_files p input').length;
            $('.js_files p').append('<input type="file" class="file" name="file_'+index+'">');
        });
});


function rotate(holder,block,showtime,fadetime)
{
	var h = $(holder);
	if ( h.find(block+'.activerotate').length == 0 )
	{
		h.find(block).hide().css('position','absolute').css('top',0).css('left',0).css('z-index',1);
		h.find(block+':first').addClass('activerotate').css('z-index',10).show();
		h.css('height', h.find(block+':first').height());
		setTimeout("rotate('"+holder+"','"+block+"',"+showtime+","+fadetime+");",showtime);
	}
	else
	{
		var active = h.find(block+'.activerotate');
		var nextactive = active.next(block);

		if ( nextactive.length == 0 )
			nextactive = h.find(block+':first');

		active.css('z-index',10).removeClass('activerotate').fadeOut(fadetime);
		nextactive.css('z-index',20).addClass('activerotate').fadeIn(fadetime);
		h.animate({height:nextactive.height()+'px'}, fadetime);
		setTimeout("rotate('"+holder+"','"+block+"',"+showtime+","+fadetime+");",showtime);
	}
}

function htmlentities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

function nl2br(str) {
  return String(str).replace(/\n/g, '<br />');
}
