var aantalCrumbs = 0;
var contactOntvanger;

$(document).ready(function(){
	// flash inladen
	$('.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').each(function(){
		title = $(this).html();
		title = title.replace('&amp;','%26');
		$(this).html("");
		$(this).flash({
	    	src: '/public/flash/h1.swf?titel=' + title,
	    	width: '675',
	    	height: '35',
			wmode: "transparent"
		});
	});

	// h1 automatisch omxetten in flash
	$('.testimonialkop').each(function(){
		title = $(this).html();
		title = title.replace('&amp;','%26');
		$(this).html("");
		$(this).flash({
	    	src: '/public/flash/kop_testimonials.swf?titel=' + title,
	    	width: '260',
	    	height: '25',
			wmode: "transparent"
		});
	});
	
	// h1 automatisch omxetten in flash
	$('.screenshotkop_groot').each(function(){
		title = $(this).find('.klant').html();
		title = title.replace('&amp;','%26');
		$(this).html("");
		$(this).flash({
	    	src: '/public/flash/kop_screenshots.swf?titel=' + title,
	    	width: '475',
	    	height: '25',
			wmode: "transparent"
		});
	});

	// uitklapblokken automatisch omxetten in flash
	$('.subblok > a').each(function(){
		title = $(this).html();
		title = title.replace('&amp;','%26');
		$(this).html("");
		$(this).flash({
	    	src: '/public/flash/uitklapblokken.swf?titel=' + title + '&id=' + $(this).attr('id'),
	    	width: '675',
	    	height: '25',
			wmode: "transparent"
		});
	});
	
	//Shadowbox.init();
	Shadowbox.init({
		skipSetup:		true,
		players:		['swf','img']
	});

	// teksten in/uitklappen
	$('.leesmeer').click(function () {
		var obj = $(this).parents('.uitklapblok').find('.vervolgtekst');

		if (obj.css('display')=='none')
		{
			obj.slideDown();
			$(this).find('a').addClass('active');
			virtualClick(document.location + "/leesmeer");
		}
		else
		{
			obj.slideUp();
			$(this).find('a').removeClass('active');
		}

	});

	// links in "_blank" i.p.v. via HTML i.v.m. valid XHTML
	$('.blankwindow').attr('target','_blank');

	// verzend links in formulieren maken
	$('.verzendlink').click(function(){
		$(this).parents('form').submit();
	});

	// route veld leegmaken on click
	$(".routeveld").click(function(){
		$(".routeveld").val('');
	});

	//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");
			}
        });
    });

	$("#hoofdCat").change(function (){
		var value = $("#hoofdCat").val();

		if (value != 0) {
			$.ajax({
				type: "POST",
				url: "/public/ajax/subDiensten.php",
				data: "id=" + value,
				dataType: "json",
				success: function(result){ //START VULLEN
					var subCat = document.getElementById("subCat");
					subCat.style.display = ""; //unhide
					for (var i = 0; i < subCat.options.length; i++){ //leegmaken
						if (subCat.options[i].value != "0") subCat.remove(_select.options[i].index);
					}
					for (var i = 0; i < result.length; i++){ //elke nieuwe waarde
						var option = document.createElement("option");
						option.value = result[i].id;
						option.innerHTML = result[i].titel;
						try
						{
							subCat.add(option,null); // standards compliant
						}
						catch(ex)
						{
							subCat.add(option); // IE only
						}
					}

				},
				error: function(reqObject, error, ex){
					alert("De subcategorieën konden niet worden opgehaald");
				}
			});
		}
	});

	//bij hover van een link binnen medewerker de foto 'draaien'
	$(".medewerker a").each(function(){
		$(this).hover(function(){
			parents = $(this).parents(".medewerker");
			foto = parents.find(".foto");
			foto.css("background-position", "bottom");
		},
		function(){
			parents = $(this).parents(".medewerker");
			foto = parents.find(".foto");
			foto.css("background-position", "");
		})
	})

	/**
	 * verstuur contactform of minicontactform
	 */
	$(".verstuur").click(function(){

		var vereist = new Array("naam", "email", "vraag");

		var regex = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
		var dataQuery;
		var form = document.getElementById("form");
		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 vereiste 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 = "#EE8C27";
				//$(veld).addClass("fielderror");
			}
			return false;
		}

		//data ok, verzenden:

		//kruimelpad meenemen:
		aantalCrumbs; //global
		var breadcrumbs = "";

		for (var i = aantalCrumbs; i >= 0; i--)
		{
			var waarde = getCookie("x-com.nl-crumb" + i + "url");
			//if (waarde != null) breadcrumbs += " >> <a href='http://www.x-com.nl" + encodeURI(waarde) + "'>" + encodeURI(waarde) + "</a>";
			if (waarde != null) breadcrumbs += "&crumb" + i + "=" + encodeURI(waarde);
		}

		breadcrumbs += "";

		dataQuery = "&naam=" + getHintfield(form.naam) + "&email=" + getHintfield(form.email) + "&tel=" + getHintfield(form.tel) + "&vraag=" + getHintfield(form.vraag) + breadcrumbs;
		if (typeof(contactOntvanger)=="string") dataQuery += "&aan=" + contactOntvanger;

		$(this).css("display", "none"); //knop verbergen

		$.ajax({
			type: "POST",
			url: "/public/ajax/sendForm.php",
			data: dataQuery,
			dataType: "json",
			success: function(response){
				if (typeof(response.success) != "undefined" && response.success)
				{
					var formDiv = document.getElementById("minicontact");
					if (!formDiv)
					{
						formDiv = document.getElementById("contact");
					}
					var successDiv = document.getElementById("minicontactbedankt");
					if (!successDiv)
					{
						successDiv = document.getElementById("contactbedankt");
					}

					formDiv.style.display = 'none';
					successDiv.style.display = 'block';
					virtualClick("/contact/bedankt");
				} else {
					alert ("Het formulier kon helaas niet worden verzonden, probeer het aub later nogmaals");
					$(this).css("display", "");
				}
			},
			error: function (reqObject, error, ex){
				alert ("Het formulier kon helaas niet worden verzonden, probeer het aub later nogmaals");
				$(this).css("display", "");
			}
		})
	})

	/**
	 * verstuur contactform of minicontactform
	 */
	$(".verstuur_inschrijving").click(function(){

		var vereist = new Array("bedrijf", "email", "aantal_personen");

		var regex = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
		var dataQuery;
		var form = document.getElementById("form");
		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 vereiste 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 = "#EE8C27";
				//$(veld).addClass("fielderror");
			}
			return false;
		}

		//data ok, verzenden:

		//kruimelpad meenemen:
		aantalCrumbs; //global
		var breadcrumbs = "";

		for (var i = aantalCrumbs; i >= 0; i--)
		{
			var waarde = getCookie("x-com.nl-crumb" + i + "url");
			//if (waarde != null) breadcrumbs += " >> <a href='http://www.x-com.nl" + encodeURI(waarde) + "'>" + encodeURI(waarde) + "</a>";
			if (waarde != null) breadcrumbs += "&crumb" + i + "=" + encodeURI(waarde);
		}

		breadcrumbs += "";

		dataQuery = "&bedrijf=" + getHintfield(form.bedrijf) + "&email=" + getHintfield(form.email) + "&aantal_pers=" + getHintfield(form.aantal_personen) + "&opmerking=" + getHintfield(form.opmerking) + breadcrumbs;
		if (typeof(contactOntvanger)=="string") dataQuery += "&aan=" + contactOntvanger;

		$(this).css("display", "none"); //knop verbergen

		$.ajax({
			type: "POST",
			url: "/public/ajax/sendInschrijving.php",
			data: dataQuery,
			dataType: "json",
			success: function(response){
				if (typeof(response.success) != "undefined" && response.success)
				{
					var formDiv = document.getElementById("inschrijven");
					if (!formDiv)
					{
						formDiv = document.getElementById("contact");
					}
					var successDiv = document.getElementById("inschrijvenbedankt");
					if (!successDiv)
					{
						successDiv = document.getElementById("inschrijvenbedankt");
					}


					formDiv.style.display = 'none';
					successDiv.style.display = 'block';
					virtualClick("/inschrijven/bedankt");
				} else {
					alert ("Het formulier kon helaas niet worden verzonden, probeer het aub later nogmaals");
					$(this).css("display", "");
				}
			},
			error: function (reqObject, error, ex){
				alert ("Het formulier kon helaas niet worden verzonden, probeer het aub later nogmaals");
				$(this).css("display", "");
			}
		})
	})
});

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));
}

/**
 * Dmv ajax een pagina projecten laden
 * @param {Object} pagina
 */
function laadProjecten(pagina){
	if (pagina == undefined || pagina < 1) pagina = 0;
	else setCookie("x-com_projectenpage", pagina);

	$.ajax({
		type: "POST",
		url: "/public/ajax/projecten.php",
		data: "page=" + pagina,
		dataType: "json",
		success: function(result){ //START VULLEN
			//navigatie
			var vorige = document.getElementById("vorige");
			var volgende = document.getElementById("volgende");

			if(result.vorige) vorige.style.display = '';
			else vorige.style.display = 'none';
			vorige.href = "javascript:laadProjecten(" + (pagina - 1) + ");";

			if(result.volgende) volgende.style.display = '';
			else volgende.style.display = 'none';
			volgende.href = "javascript:laadProjecten(" + (pagina + 1) + ");";

			//items tonen
			var view = document.getElementById("projecten_view");
			view.innerHTML = "";
			for (var i=0; i < result.result.length; i++){
				var row = result.result[i];
				klantnaam = row.klantnaam.length>17?row.klantnaam.substr(0,16) + "...":row.klantnaam;
				view.innerHTML += '<a href="/referenties/projecten/'+ encodeURI(row.titel.replace(" ", "-"))+'/'+row.id+'" onmouseover="showtrail(\'/public/flash/tooltip_projecten.swf?id='+row.id+'\');" onmouseout="hidetrail();"><img src="'+row.thumbnail+'" alt="'+row.titel+'" title="" /><br/>' + klantnaam + '</a>';
			}
			virtualClick("/referenties/projecten/pagina"+(pagina+1));
		},
		error: function(reqObject, error, ex){

		}
	});
}

	// subs in/uitklappen
openklappen = function (id) {
	var obj = $('#'+id).parents('.subblok').find('.vervolgtekst');

	$('#'+id).parents('#uitklapblokken').find('.vervolgtekst').slideUp();
	$('#'+id).parents('#uitklapblokken').find('a').removeClass('active');

	if (obj.css('display')=='none')
	{
		obj.slideDown();
		$('#'+id).addClass('active');
	}

};

/**
 * 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
};

/**
 * Een cookie uitlezen
 * @param {Object} check_name
 */
function getCookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

/**
 * Cookie wegschrijven
 * @param {Object} name
 * @param {Object} value
 * @param {Object} expires
 * @param {Object} path
 * @param {Object} domain
 * @param {Object} secure
 */

function setCookie( name, value, expires, path, domain, secure )
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

	/*
	if the expires variable is set, make the correct
	expires time in minutes*/
	if ( expires )
	{
		expires = expires * 1000 * 60;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

/**
 * Kruimelpad bijhouden en genereren
 *
 * @param {String} targetid
 * @param {Integer} aantal
 * @param {String} huidigTitel
 * @param {String} huidigURL
 */
function breadcrumbs(targetid, aantal, huidigTitel, huidigURL){
	aantalCrumbs = aantal; //global

	var target = document.getElementById(targetid);
	var doorschuiven = true; //cookies wel/niet doorschuiven
	var refresh = false; //zelfde pagina opgevraagd

	if (huidigURL == getCookie("x-com.nl-crumb0url") || huidigURL == "/home" || huidigURL == "/404") doorschuiven = false;
	if (huidigURL == getCookie("x-com.nl-crumb0url")) refresh = true;

	for (var i = aantal; i >= 0; i--) {
		var url = getCookie("x-com.nl-crumb" + i + "url");
		var rawTitel = getCookie("x-com.nl-crumb" + i);
		var titel = rawTitel;
		if (url && titel) {
			//Wanneer de titel langer is dan 13 tekens, deze na 12 tekens afknippen en ... toevoegen
			if (titel.length > 13){
				titel = titel.slice(0, 12) + "...";
			}
			var newItem = '<li><a href="' + url + '" title="' + rawTitel + '">' + titel + '</a></li>'; //template voor nieuw item
			if (i != aantal && !refresh) target.innerHTML += newItem;
			if (i != 0 && refresh) target.innerHTML += newItem;

			if (i != (aantal) && doorschuiven) { //cookies een positie doorschuiven
				setCookie("x-com.nl-crumb" + (i + 1), rawTitel, 30, "/");
				setCookie("x-com.nl-crumb" + (i + 1) + "url", url, 30, "/");
			}
		}
	}

	if (huidigTitel && huidigURL && doorschuiven){ //nieuwe laatste pagina
		setCookie("x-com.nl-crumb0", huidigTitel, 30, "/");
		setCookie("x-com.nl-crumb0url", huidigURL, 30, "/");
	}

	//markup
	target.lastChild.className = "lastitem";
}

/**
 * Een virtuele pageview voor google analytics genereren
 * @param {String} url
 */
function virtualClick(url)
{
	if (pageTracker != undefined && typeof(pageTracker._trackPageview) == "function")
	{
		pageTracker._trackPageview(url);
	}
}

function addslashes(str) {
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'\\"');
	str=str.replace(/\0/g,'\\0');
	return str;
}

function setOntvanger(ont){
	contactOntvanger = ont;
}

function trackvideo(p1,p2,p3)
{
	pageTracker._trackEvent(p1,p2,p3)
}
