$(document).ready(function(){
	// links in "_blank" i.p.v. via HTML i.v.m. valid XHTML (vereist voor cms)
	$('.blankwindow').attr('target','_blank');


	// 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: 'transparent',
			allowfullscreen: 'true'
		});
	});
	
//	$('#topmenu').hover(function(){
//		$('.dropdown').show();
//	});
//	
//	$('#topmenu').mouseleave(function(){
//    	$('.dropdown').hide();
//  	});
	
//	$('li.headlink').hover(
//			function() { $('ul', this).css('display', 'block'); },
//			function() { $('ul', this).css('display', 'none'); });
//
//	
	//## colorbox ##

	/**
	 *	-- Gebruik --
	 *	Geef een anchor de class .colorbox en de href de locatie van de afbeelding
	 *	Voor een slideshow:
	 *	Geef meerdere anchor's met .colorbox dezelfde rel="" waarde
	 *	Voorbeeld slideshow:
	 *	<a class="colorbox" rel="testblaat" href="/public/img/video2.jpg">klik</a>
     *	<a class="colorbox" rel="testblaat" href="/public/img/banner.jpg">klik</a>
	 */
	//set
	$('.colorbox').colorbox({
		transition:'elastic'
	});
	
	/**
	* Html tonen in colorbox:
	* <a class="htmlcolorbox" rel="idvanjehtmldiv">Klik</a>
	*/	
	$('.htmlcolorbox').click(function(){
		var targetid = $(this).attr('rel');
		if (typeof targetid == 'undefined' || targetid == '') return ;
		
		$(this).colorbox({
			open: true,
			inline:true,
			transition:'none',
			href:"#" + targetid
		});
	});

    $('.submitlink').click(function(){
    	$(this).parents('form:first').append('<input type="hidden" name="javascriptsubmit" value="true" />').trigger('submit');
        $(this).removeClass( 'submitlink' );
		return false;
	});

	    //AJAX FORMS automatisch
	$('form.ajaxform').each(function(){

        $(this).append('<input type="hidden" name="javascriptsubmit" value="true" />');

		var form = $(this);
		$(this).ajaxForm({
			dataType: 'json',
			beforeSubmit: function(){
				form.parent().find('p.foutmelding').remove();
			},
			success: function(response){
				if (response.success)
				{
                    if( response.redirect )
                    {
                        $(location).attr( 'href', response.redirect );
                        return false;
                    }
                    else
                    {
                        form.html('<p class="feedback">'+response.message+'</p>');
                    }
				}
				else {
					form.before($('<p class="foutmelding">'+response.message+'</p>'));
				}
			}
		})
	});

	// ## MIDDELBURG ##
	
	//cookies opslaan bij verlaten van pagina
	$(window).unload(function(){
		$('.uitklapblokken').each(function(){
			if ($(this).hasClass('enablecookie'))
			{
				$(this).find('.uitklaplink').each(function()
				{
					var id = $(this).attr('id');
					if (id != undefined && id)
					{
						if ($(this).hasClass('open'))
							$.cookie(id, 1);
						else
							$.cookie(id, 0);
					}
				});
			}
		});
	});
	
	//cookies uitlezen
	$('.uitklapblokken').each(function(){
		if ($(this).hasClass('enablecookie'))
		{
			$(this).find('.uitklaplink').each(function()
			{
				var id = $(this).attr('id');
				if (id != undefined && id)
				{
					if ($.cookie(id) == 1) //was uitgeklapt
					{
						if (!$(this).hasClass('open'))
							$(this).trigger('click'); //uitklappen
					}
				}
			});
		}
	});

	// links in "_blank" i.p.v. via HTML i.v.m. valid XHTML
	$('.blankwindow').attr('target','_blank');

	//field hints
	$(".hintfield").each(function(i) {
        var beginStyle = $(this).attr("style");
		$(this).addClass("hint");
		$(this).val($(this).attr("title"));

        $(this).bind("focus", function(e) {
            if ($(this).val() == $(this).attr("title")) {
                $(this).val("");
				$(this).removeClass("hint");
            }
        });
        $(this).bind("blur", function(e) {
            if ($(this).val() == "") {
				$(this).addClass("hint");
				$(this).val($(this).attr("title"));
            } else {
				$(this).css("border-color", "");
				$(this).removeClass("hint");
			}
        });
    });

	//submit form link
	$('.submitform').click(function(){
		$(this).parents('form:first').submit();
	});

	// h1 automatisch omzetten in flash
	$('.paarsheader').each(function(){
		title = $(this).html();
		subsite = $(this).attr('title');
		title = title.replace('&amp;','%26');
		$(this).html("");
		$(this).flash({
			src: '/framework/public/flash/h1.swf?titel=' + title + '&amp;subsite=' + subsite,
	    	width: '450',
	    	height: '30',
			wmode: 'transparent'
		});
	});
	
	$('.paarsheaderklein').each(function(){
		title = $(this).html();
		subsite = $(this).attr('title');
		title = title.replace('&amp;','%26');
		$(this).html("");
		$(this).flash({
			src: '/framework/public/flash/h1klein.swf?titel=' + title + '&amp;subsite=' + subsite,
	    	width: '215',
	    	height: '30',
			wmode: 'transparent'
		});
	});

	// h1 automatisch omzetten in flash
	$('.paarsheaderstap').each(function(){
		title = $(this).html();
		title = title.replace('&amp;','%26');
		$(this).html("");
		$(this).flash({
	    	src: '/framework/public/flash/h1stap.swf?titel=' + title,
	    	width: '215',
	    	height: '21',
			wmode: 'transparent'
		});
	});

	$('.videoplayer').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,
			allowFullScreen: 'true',
			wmode: 'transparent'
		});
	});

	$('.audioplayer').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,
			allowFullScreen: 'true',
			wmode: 'transparent'
		});
	});
});

/**
 * Use colorbox to display a slideshow
 */
function showPhoto(path, items, index)
{
	if (typeof $().colorbox != "function" || typeof path != "string" || typeof items != "object")
		return false;
	
	if (typeof index == "undefined")
		index = 0;
	index = parseInt(index);
	if (index == NaN)
		index = 0;
	if (index >= items.length)
		return false;

	var container = $('<div/>').hide();
	$('body').append(container);
	var photolinks = new Array();
	var colorboxConfig = {
		previous: 'Vorige',
		next: 'Volgende',
		current: 'Afbeelding {current} van {total}',
		onClosed: function(){
			container.remove();
		}
	};
	
	for (var i = 0; i < items.length; i++)
	{
		photolinks[i] = $('<a rel="openalbum" href="' + path + items[i] + '">Afbeelding ' + (i+1) + '</a>').colorbox(colorboxConfig);
		container.append(photolinks[i]);
	}

	//open item of index
	photolinks[index].trigger('click');
}

// Return value rounded to two decimal places
function display_value( param )
{
	stringvalue     = param.toString();
  	stringvalue     = stringvalue.replace(/\,/, ".");
	value           = round_decimals( stringvalue, 2);
	stringvalue     = value.toString();
	stringvalue     = stringvalue.replace(/\./, ",");
	return stringvalue;
}


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
}

// Finds position of first occurrence of a string within another
function strpos (haystack, needle, offset) {
    var i = (haystack+'').indexOf(needle, (offset ? offset : 0));
    return i === -1 ? false : i;
}
