var paginanummer;

$(document).ready(function(){
	
	$("body").contextMenu({
		menu: 'myList'
	});
	$('body').disableContextMenu();
	
	if ($('#paginanummer').html())
	{
		paginanummer = $('#paginanummer').val;
	}

    //bijhouden hoevaak er op een dame wordt geclicked.
    $(".counter").click(function(){
        var aId = $(this).attr('id').split("_");
        var id = aId[1];


        if($(this).hasClass('active') || !$(this).hasClass('mainitem'))
        {

            $.ajax({
                type: "POST",
                async: false,
                url: "/ajax/addVisited.php",
                data: "medId=" + id ,
                dataType: "html",
                success: function(response)
                {}
            });
        }

    });

    $('input.checkfield').each(function(){
    	$(this).val('massagewereld');
    });

	// 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'
		});
	});


	// h1 automatisch omxetten in flash
	$('h1.flashHead').each(function(){
		title = $(this).find('.white').html();
		title = title.replace('&amp;','%26');
		title2 = $(this).find('.color').html();
		title2 = title2.replace('&amp;','%26');
		filiaal = $(this).find('.vestiging').html();
		$(this).html("");
		$(this).flash({
	    	src: '/public/flash/h1.swf?titel=' + title + '&amp;titel2=' + title2 + '&amp;vestiging=' + filiaal,
	    	width: '625',
	    	height: '35',
			wmode: "transparent"
		});
	});

	// h1 automatisch omxetten in flash
	$('h2.flashHead').each(function(){
		title = $(this).html();
		title = title.replace('&amp;','%26');
		$(this).html("");
		$(this).flash({
	    	src: '/public/flash/h2.swf?titel=' + title,
	    	width: '525',
	    	height: '40',
			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'
		});
	});


	//Shadowbox.init();
	Shadowbox.init({
		skipSetup:		true,
		players:		['swf','img']
	});



	// subs in/uitklappen
	$('.mainitem .itemtitel').click(function () {
		var obj = $(this).parents('.mainitem').find('span.itemcontent');

		$(this).parents('#items').find('span.itemcontent').slideUp('fast');
		$(this).parents('#items').find('.mainitem').removeClass('active');

		if (obj.css('display')=='none')
		{
			obj.slideDown('fast');

			$(this).parents('.mainitem').addClass('active');
		}

	});

	// links in "_blank" i.p.v. via HTML i.v.m. valid XHTML
	$('.blankwindow').attr('target','_blank');


	//##### OVERZICHTPAGINA'S #####
	$('#paginanummer').blur(openPagina);

	$('#paginanummer').bind('keypress', function(e) {
        if(e.keyCode==13){
                openPagina();
        }
	});
	$('#categorieselect').change(function(){
		if ($('#categorieselect').val() != 0)
		{
			document.location = overzichtURL + $('#categorieselect').val();
		}
		else
		{
			document.location = overzichtURL;
		}
	});

	$('#subcategorieselect').change(function(){
		if ($('#subcategorieselect').val() != 0)
		{
			document.location = overzichtURL + $('#categorieselect').val() + '/' + $('#subcategorieselect').val();
		}
		else
		{
			document.location = overzichtURL + $('#categorieselect').val();
		}
	});


	//##### MIJN MENU KNOPPEN (VIDEO OVERZICHT) #####
	$('#menuAdd').click(function(){

		videoId; //global var, set in template

		$.ajax({
			type: "POST",
			url: "/mijn_menu",
			data: "add=" + videoId,
			dataType: "json",
			success: function(response){ //START VULLEN
				if (typeof(response.success) != "undefined" && response.success)
				{
					$('#menuAdd').hide();
					$('#menuDel').show();
				}
			},
			error: function(reqObject, error, ex){
				alert("De video kon niet aan uw menu worden toegevoegd.");
			}
		});
		return false; //link niet openen
	});

	$('#menuDel').click(function(){

		videoId; //global var, set in template

		$.ajax({
			type: "POST",
			url: "/mijn_menu",
			data: "del=" + videoId,
			dataType: "json",
			success: function(response){ //START VULLEN
				if (typeof(response.success) != "undefined" && response.success)
				{
					$('#menuDel').hide();
					$('#menuAdd').show();
				}
			},
			error: function(reqObject, error, ex){
				alert("De video kon niet uit uw menu worden verwijderd.");
			}
		});
		return false; //link niet openen
	});

	//##### REACTIE PLAATSEN #####
	//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");
			}
        });
    });

	$('#reactie_send').click(function(){
		videoId; //global, set in view
		var vereist = new Array("naam", "email", "bericht");

		var regex = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
		var dataQuery;
		var form = document.getElementById('reactie');
		var fout = new Array(); //array met fout ingevulde velden

		for (var i = 0; i < vereist.length; i++)
		{
			if (getHintfield(eval("form." + vereist[i])) == "")
			{ //controleer op lege of standaard waarde
				eval("form." + vereist[i] + ".blur()");
				fout.push(vereist[i]);
			}
		}
		if (fout.length) alert("Vul aub alle velden in.");

		if (!regex.test(getHintfield(form.email)) && fout.length == 0)
		{
			alert("Het ingevoerde emailadres is geen geldig adres.");
			form.email.focus();
			fout.push("email");
		}

		if (fout.length)
		{
//			for (var i = 0; i < fout.length; i++)
//			{
//				var veld = eval("form." + fout[i]);
//				veld.style.borderColor = "#FF6C00";
//				//$(veld).addClass("fielderror");
//			}
			return false;
		}

		dataQuery = "&video=" + videoId + "&naam=" + getHintfield(form.naam) + "&email=" + getHintfield(form.email) + "&bericht=" + getHintfield(form.bericht);

		$.ajax({
			type: "POST",
			url: "/public/ajax/reactie.php",
			data: dataQuery,
			dataType: "json",
			success: function(response){ //START VULLEN
				if (typeof(response.success) != "undefined")
				{
					if (response.success)
					{
						$('#reactie').hide();
						$('#reactiebedankt').show();
					}
					else {
						if (response.error == 'requiredfields')
							alert("Vul aub alle velden in.");
						else if (response.error == 'email')
							alert("Het ingevoerde emailadres is geen geldig adres.");
						else alert("Uw reactie kon niet worden verwerkt, probeer het aub later nogmaals.")
					}
				}
			},
			error: function(reqObject, error, ex){
				alert("Uw reactie kon niet worden geplaatst, probeer het aub later nogmaals.");
			}
		});
		return false; //form niet submitten
	});

		//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();
	})


	//contactform
	$('form.ajaxform').each(function(){
		$(this).append('<input type="hidden" name="ajax_post" value="oke" />');
		var form = $(this);
		$(this).ajaxForm({
			dataType: 'json',
			beforeSubmit: function(){
				form.parent().find('.errormelding').remove();

				//vereiste velden
				var ok = true;
				form.find('.required').each(function(){
					if ($(this).val().replace(' ', '') == '' || $(this).hasClass('hint')) //leeg of bevat nog de hint
					{
						ok = false;
						$(this).addClass('formerror');
					}
					else
						$(this).removeClass('formerror');
				});
				form.find('.required.email').each(function(){
					var regex = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
					if (!regex.test($(this).val()))
					{
						ok = false;
						$(this).addClass('formerror');
					}
				});

				if (ok)
				{
					//de hints niet meesturen
					form.find('input.hint').each(function(){
						$(this).val('');
					});
				}
				else
					return false;
			},
			success: function(response){
				if (response.success)
				{
					form.html('<p>'+response.melding+'</p>');
				}
				else if (response.melding){
					form.before($('<p class="errormelding">'+response.melding+'</p>'));
				}
			}
		})
	})

	//nieuws
	$('#nieuws .openitem').click(function(){
		var attrid = $(this).attr('id').split('_');
		var url = $(this).attr('href');
		var id = parseInt(attrid.pop());
		if (url && !isNaN(id) && id > 0)
		{
			var form = $('<form method="post" action="'+url+'"><input type="hidden" name="openid" value="'+id+'"/></form>')
			$('body').append(form);
			form.submit();
			return false; //niet naar de url gaan
		}
	});
});

function validateForm(formData, jqForm, options)
{
	for (var i=0; i < formData.length; i++) {
        if (!formData[i].value) {
        	return false;
        }
    }

	return true;
}

function showImageLightbox(img_array, img_id, img_path)
{
	var foto_arr = img_array.split(',');
	var img_arr = new Array();

	for (var i in foto_arr)
	{
	    var img = {
	        player:     'img',
	        content:    img_path+foto_arr[i]
	    };
	    img_arr.push(img);
	}
    Shadowbox.open(img_arr);
	Shadowbox.change(parseInt(img_id));
}

function showFlashLightbox(inhoud, breedte, hoogte)
{
	Shadowbox.open({
		player:		'swf',
		content:	inhoud,
		width:		breedte,
		height:		hoogte
	});
}

function openPagina()
{
	var nieuw = $('#paginanummer').val();
	if (typeof(baseURL) == 'undefined' || typeof(pages) == 'undefined' || isNaN(parseInt(pages))) return false;
	if (!isNaN(nieuw) && 0 < nieuw && nieuw <= parseInt(pages) )
	{
		document.location = baseURL + '/' + nieuw;
		return true;
	}
	//alert('De ingevoerde pagina kon niet worden gevonden');
	$('#paginanummer').val(paginanummer);
}

/**
 * Haal de waarde op van een hintfield (een veld met klasse fieldhint, waar het title attribuut als hint wordt gebruikt)
 * @param {Object} veld
 */
function getHintfield(veld)
{
	if (veld.value == "" || veld.value == veld.title) return "";
	else return veld.value
}

