var realsite = true;
var headerHeight = 120;
var menuActive  = false;
var curMenuTitle;
var loadStop = false;
var curMenuModalWidth;
var curMenuModalHeight;
var curContentTitle;
var orderid;
var scrolling = false;
var offsetScrolling = 60;
var maxScrollSpeed = 5;
var xPos;
var intval;

function changesubmit()
{
	e('submitbutton').disabled = true;
	e('submitbutton').value = 'Moment a.u.b.';
}

$(document).ready(function()
{
	if(jQuery.browser.msie && parseInt(jQuery.browser.version, 10) == 6) {
	  try {
	    document.execCommand("BackgroundImageCache", false, true);
	  } catch(err) {}
	}
	
	function windowScroll(pos)
	{
		if(pos=='right')
		{
			var speed = (xPos - (winWidth - offsetScrolling)) / maxScrollSpeed;
		 	var scr =  $(window).scrollLeft();
		 	$(window).scrollLeft(scr + speed);
		
		}else if(pos=='left')
		{
			var speed = (offsetScrolling - xPos) / maxScrollSpeed;
		 	var scr =  $(window).scrollLeft();
		 	$(window).scrollLeft(scr - speed);
		}
	}

	$(document).mousemove(function(e)
	{
		xPos =  e.clientX;
		var e = tb_getPageSize();
		winWidth = e[0];
		winHeight  = e[1];
		
		if(xPos >= winWidth - offsetScrolling)
		{	
			 if(!scrolling)
			 {
			 	scrolling = true;
			 	intval = setInterval(function(){windowScroll('right')}, 0);
			 }
		  
		}else if(xPos < offsetScrolling)
		{
			if(!scrolling)
			{
		 		scrolling = true;
		 		intval = setInterval(function(){windowScroll('left')}, 0);
		 	}
		}else
		{
			scrolling = false;
			clearInterval(intval);		
		} 
    });
	
	$(document).mouseleave(function(){
		scrolling = false;
		clearInterval(intval);
	})	

	// Navigation
	var hash = window.location.hash;
	
	if(hash && hash.substr(1,1) != '/')
	{
		// ga naar desbetreffende pagina
		var title = hash.substring(1);
		showContent(title);
	}else
	{
		/*
		var url = "/site/ajax/loadcontent.php?title=boek-bestellen";
		showMenu('boek-bestellen',url);
		*/
	}
	
	$('#menu a').click(function()
	{
		var url = $(this).attr('href');
		var title = $(this).attr('title');
		showMenu(title, url);
		return false;
	})
	
	$('.innerlink').live('click',function()
	{
		var url = $(this).attr('href');
		var title = $(this).attr('title');
		showMenu(title, url);
		return false;
	});
	
	$('#modal_contents_thumbs img').live('click', function()
	{
		$('#modal_left_column_images .visible').removeClass('visible');
		$('#modal_left_column_images img').eq($('#modal_contents_thumbs img').index($(this))).addClass('visible');
		$('#modal_contents_thumbs img').removeClass('active')
		$(this).addClass('active');
	});
	
	//Cufon.replace('#menuitems', { fontFamily: 'tradegothic' });
	//Cufon.replace('#meta', { fontFamily: 'tradegothic' });

	Cufon.replace('.menuitem a', {
		hover: true,hoverables:{a:true}
	});
 	Cufon.replace('#meta a', {
		hover: true,hoverables:{a:true}
	});
	
	Cufon.replace('#viewswitch a', {
		hover: true,hoverables:{a:true}
	});
	Cufon.replace('#viewswitch');
	
	setTimeout(scrollMain,500);
	
	updatePositions();
	
	$(window).scroll(function()
	{
		updatePositions();
	});
	
	$(window).resize(function()
	{
		updatePositions();
	});	
});


function scrollMain()
{
	$('html, body').animate({scrollLeft:14000}, 1000);
}



function checkOrderForm()
{
	var formId = $('#orderForm');
	
	if(error)
	{
		return false;
	}else
	{
		return true;
	}
}

function showMenu(title, url)
{	
	$('#menuitem_' + curMenuTitle).addClass('menu_white');
	$('#menuitem_' + curMenuTitle).removeClass('menu_active');

	$('#menuitem_' + title).removeClass('menu_white');
	$('#menuitem_' + title).addClass('menu_active');
	
	//window.location = '#' + title;
	window.location.hash = title;

	if(title == 'contact' || title == 'biografie' || title == 'sponsoring' || title == 'over-de-stichting' || title == 'bedankt-betaald' || title=='betaling-fout' || title=='werk-kopen')
	{
		curMenuModalWidth = 650;
		curMenuModalHeight = 400;
		
	}else if(title =='nieuwsbrief') 
	{
		curMenuModalWidth = 500;
		curMenuModalHeight = 330;
	}else 
	{
		curMenuModalWidth = 800;
		curMenuModalHeight = 480;
	}
	
	if(!menuActive)
	{
		closeModal(curContentTitle,'content');
		showModal(title,curMenuModalWidth,curMenuModalHeight,'menu', url);
		menuActive = true;
	}else
	{
		closeModal(curContentTitle,'content');
		closeModal(curMenuTitle,'menu');
		showModal(title,curMenuModalWidth,curMenuModalHeight,'menu', url);
	}
	menuActive = true;
	curMenuTitle = title;	
	
	Cufon.replace('.menuitem a', {
		hover: true,hoverables:{a:true}
	});
}

function showContent(title)
{
	window.location.hash = title;
	
	if(title == 'contact' || title == 'biografie' || title == 'sponsoring' || title == 'over-de-stichting' || title == 'bedankt-betaald' || title=='betaling-fout')
	{
		curMenuModalWidth = 650;
		curMenuModalHeight = 400;
	}else if(title =='nieuwsbrief') 
	{
		curMenuModalWidth = 500;
		curMenuModalHeight = 330;
	}else
	{
		curMenuModalWidth = 800;
		curMenuModalHeight = 480;
	}
	menuActive = true;
	
	closeModal(curMenuTitle,'menu');
	closeModal(curContentTitle,'content');
	curContentTitle = title;
	var url = "/site/ajax/loadcontent.php?title="+title;
	showModal(title,curMenuModalWidth,curMenuModalHeight,'content',url);
}

function tb_getPageSize()
{
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
	arrayPageSize = [w,h];
	return arrayPageSize;
}

var curprojecttitle;

function showModal(title, width, height, type, url)
{
	switch(type)
	{
		case 'project':

			closeModal(curprojecttitle,'project');
			curprojecttitle= title;
			var position1 = $('#item_' + title + ' .item_photo').position();
			var position2 = $('#item_' + title).position();
			var leftPos = position2.left - 20;
			var topPos = position1.top - 20;
			var content = '';
		
		break;
	
		case 'menu':
		
			curMenuModalWidth = width;
			curMenuModalHeight = height;
			curMenuTitle = title;
			var e = tb_getPageSize();
			winWidth = e[0];
			winHeight  = e[1];
			var curLeftPos = $(window).scrollLeft();
			//turned off because we use position fixed on the modal			
			//var leftPos = Math.floor(curLeftPos + (winWidth - width) / 2);
			var leftPos = (winWidth - width) / 2;
			var topPos = Math.floor((winHeight - height) / 2);
			var content = '';				

		break;
		
		case 'content':
		
			curMenuModalWidth = width;
			curMenuModalHeight = height;
			curContentTitle = title;
			var e = tb_getPageSize();
			winWidth = e[0];
			winHeight  = e[1];
			var curLeftPos = $(window).scrollLeft();
			//turned off because we use position fixed on the modal						
			//var leftPos = Math.floor(curLeftPos + (winWidth - width) / 2);
			var leftPos = (winWidth - width) / 2;
			var topPos = Math.floor((winHeight - height) / 2);
			var content = '';				

		break;
	}
	
	var modalWindow = '<div id="modal_' + title + '" class="modal_outer" style="left: ' + leftPos + 'px; top: ' + topPos + 'px; width: ' + width + 'px; height: ' + height + 'px; display: block;"><div class="modal_inner"><div class="modal_close"></div><div class="modal_bgs"><div class="modal_bg_r modal_bg"></div><div class="modal_bg_br modal_bg"></div><div class="modal_bg_b modal_bg"></div></div><div class="modal_content">' + content + '</div></div></div>';
	
	switch(type)
	{
		case 'project':
				
			$('#modals').append(modalWindow);
			$('.modal_outer').css('position','absolute');
			$('#main_modal_bg').hide();
			$('#modal_'+title+' .modal_close').click(function()
			{
				//alert('close');
				closeModal(title,'project');
			});
			
			var content = title;
			
			$.ajax({
				type: "GET",
				url: "/site/ajax/project.php",
				data: "id=" + title,
				cache: false,
				success: function(html){
				
					$('#modal_' + title + ' .modal_content').append(html).parent().addClass('loaded');
					
					$('#modal_' + title + ' .modal_content').find('.project img.largeleftimage').load(function(){
								
						if(($(this).height()) > $(this).parent().parent().next().height())
						{
							//image taller
							var titleheight = $(this).parents().find('h1').height();	
							$(this).closest('.modal_outer').height($(this).height() + 45 + titleheight);
							$(this).parent().parent().next().height($(this).height());
						
						}else
						{
							//content taller
							var titleheight = $(this).parents().find('h1').height();
							$(this).closest('.modal_outer').height($(this).parent().parent().next().height()+ 45 + titleheight);
						}
						
						if($(this).hasClass('forsale'))
						{
							//$(this).next('.forsaleimage').addClass('forsaletag');
							//alert('forsale');
						}
					});
					
					$('.colorbox').colorbox(
					{
						opacity: 0.7,
						maxHeight: '95%',
						maxWidth: '95%',
						next: 'volgende',
						previous: 'vorige',

						onComplete:function(){ 
						
							$('#cboxClose').click(function()
							{
								closeModal(title,'project');
							});
							$('#cboxOverlay').click(function()
							{

								closeModal(title,'project');
							});
						},
						
						close: 'sluiten'
					});

					if($('.detailimagevideo').length > 0)
					{	
						var videoheight = $('.detailimagevideo').find('object').attr('height');
						$('.modal_outer').height(Number(videoheight)+80);					
					}	
				}
			})

		break;	
		
		case 'menu':
						
			$('#main_modal_bg').show();
			$('#main_modal_bg').css('height', winHeight-16);
			var winWidth = $('#content').css('width');
			var winWidth = $(document).width();
			$('#main_modal_bg').css('width', winWidth);	
			$('body').append(modalWindow);
			$('.modal_outer').css('position','fixed');
			$('#main_modal_bg').fadeTo(0,0.75);
			$('#modal_' + title).css('z-index',9999);
			$('#modal_' + title + ' .modal_close').click(function()
			{
				closeModal(title,'menu',true);
			});
			loadStop = true;
			$('#modal_' + title + ' .modal_content').css('height', height - 40);		
			//$('#modal_' + title + ' .modal_content').append('<div class="modal_loader"><img src="/site/gfx/preloader.gif" alt="loading" /></div>');		
			$('#modal_' + title + ' .modal_loader').css('width', width - 40);
			$('#modal_' + title + ' .modal_loader').css('padding-top',(height - 100) / 2);
			$.post(url,
		    function(data){
		        if (data != "")
		        {	
		        	$('#modal_' + title + ' .modal_loader').remove();
					$('#modal_' + title + ' .modal_content').append(data).parent().addClass('loaded');
					$('#modal_' + title + ' .modal_contents').css('height', height - 95);
					$('.colorbox').colorbox(
					{
						opacity: 0.7,
						maxHeight: '95%',
						next: 'volgende',
						previous: 'vorige',
						
						close: 'sluiten'
					});
				}
		        loadStop = false; 
		    });
		break;
		
		case 'content':
			
			$('#main_modal_bg').show();
			$('#main_modal_bg').css('height', winHeight-16);
			var winWidth = $('#content').css('width');
			$('#main_modal_bg').css('width', winWidth);	
			$('body').append(modalWindow);
			$('.modal_outer').css('position','fixed');
			$('#main_modal_bg').fadeTo(0,0.75);
			$('#modal_' + title).css('z-index',9999);
			$('#modal_' + title + ' .modal_close').click(function(){
				closeModal(title,'content',true);
			});
			
			loadStop = true;
			$('#modal_' + title + ' .modal_content').css('height', height - 40);
			//$('#modal_' + title + ' .modal_content').append('<div class="modal_loader"><img src="/site/gfx/preloader.gif" alt="loading" /></div>');		
			$('#modal_' + title + ' .modal_loader').css('width', width - 40);
			$('#modal_' + title + ' .modal_loader').css('padding-top',(height - 100) / 2);
			
			//$.post("/site/ajax/loadcontent.php?title=" + title + "&type=" + type + "&orderid=" + order_id,
			$.post(url,
		    function(data){
		        if (data != "")
		        {	
		        	$('#modal_' + title + ' .modal_loader').remove();
					$('#modal_' + title + ' .modal_content').append(data).parent().addClass('loaded');
					$('#modal_' + title + ' .modal_contents').css('height', height - 95);
					$('.colorbox').colorbox(
					{
						opacity: 0.7,
						maxHeight: '95%',
						/*
onComplete:function(){ 
						
							$('.modal_close').click(function()
							{
								alert('ff');
							});
						},
*/
						next: 'volgende',
						previous: 'vorige',
						close: 'sluiten'
					});
				}
		        loadStop = false;
		        
		    });
		break;
	}
	
	Cufon.replace('.modal_content h1', { fontFamily: 'tradegothicBold' });	
}





function closeModal(title, type, closeclicked)
{	
	//$('#menuitem_' + curMenuTitle).addClass('menu_white');
	
	
	
	if(closeclicked)
	{
		$('.menuitem').removeClass('menu_active');
		$('.menuitem').addClass('menu_white');
		Cufon.refresh();
		//remove hash
	window.location.hash = '#/';
	//window.location.hash.substring(1);


	}
	//alert(type);
	switch(type)
	{
		case 'project':
		
			$('#modal_'+title).remove();
			$('#main_modal_bg').hide();
			//alert(title);
			
		break;
		
		case 'menu':	
		case 'content':
			menuActive = false;
			$('#modal_'+title).remove();
			$('#main_modal_bg').hide();
			
		break;
	}
}


function updatePositions()
{

	var e = tb_getPageSize();
	winWidth = e[0];
	winHeight  = e[1];
	$('#content').css('height', winHeight - headerHeight);
	
	var switchWidth = $('#viewswitch').width();
	$('#viewswitch').css('left',Math.floor((winWidth - switchWidth) / 2));
			
	//if(menuActive)
	//{		
		$('#main_modal_bg').css('height', winHeight-16);
		var winWidth2 = $('#content').css('width');
		$('#main_modal_bg').css('width', winWidth2);	
	
		var curLeftPos = $(window).scrollLeft();
		
		var leftPos = Math.floor(curLeftPos + (winWidth - curMenuModalWidth) / 2);
//		turned this off, because we use position fixed now on the modal
//		$('#modal_' + curMenuTitle).css('left', leftPos);
	//}
	
}



function tb_getPageSize()
{
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
	arrayPageSize = [w,h];
	return arrayPageSize;
}

function e(id) { return document.getElementById(id) }

/* Contactform functions */

function toggleErrorLabel(label,state) {
	if(state == 'on') {
		$('#'+label).addClass("errorlabel");
	}else{
		$('#'+label).addClass("normallabel");
	}
}

function isValidEmail(str) {
   return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
}

function ValidateForm(form) {

	var error = 0;
	var errorMessage = 'Je hebt dit formulier niet volledig ingevuld:\n\n';
		
	if(typeof(form.required)=='undefined') {
		return true;
	}
		
	
	var fieldnames = form.required.value.split(',');
	
		for(var key in fieldnames) {
				
		if(e(fieldnames[key])) {
		
			type = e(fieldnames[key]).type
				
			label = e('label_'+fieldnames[key]).innerHTML;
			label = strip_tags(label);

			if(type=='text' || type=='textarea') {
				if(e(fieldnames[key]).value == "") { 
					errorMessage += '- '+label+' is niet ingevuld\n';
					error = 1;
					toggleErrorLabel('label_'+fieldnames[key],'on');
				} else if(fieldnames[key]=='email') {
					p = e(fieldnames[key]).value;
					c1 = p.indexOf('@');
					c2 = p.lastIndexOf('.');
					
					if (c1<1 || c1==(p.length-1) || c2<c1 || c2>=(p.length-2)) {
						errorMessage += '- '+label+' is geen geldig e-mailadres\n';
						error = 1;
						toggleErrorLabel('label_'+fieldnames[key],'on');
					}else
					{
						toggleErrorLabel('label_'+fieldnames[key]);
					}
				}else{
					toggleErrorLabel('label_'+fieldnames[key]);
				}
			} else if(type=='select-one') {
				if(e(fieldnames[key]).options[e(fieldnames[key]).selectedIndex].value=='' || e(fieldnames[key]).options[e(fieldnames[key]).selectedIndex].value=='0') {
					errorMessage += '- '+label+' is niet gekozen\n';
					error = 1;
					toggleErrorLabel('label_'+fieldnames[key],'on');
				}
			} else {
				alert(type)
			}
			
			
			
		}
	
	}

	if(error){
		alert(errorMessage);
		return false; 
	}else{
		e('submitbutton').disabled = true;
		e('submitbutton').value = 'Moment a.u.b.';
		return true;
	}
}

function strip_tags(str, allowed_tags) { // needed for validateform!
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Luke Godfrey
    // +      input by: Pul
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +      input by: Alex
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Marc Palau
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Eric Nagel
    // +      input by: Bobby Drake
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: strip_tags('<p>Kevin</p> <br /><b>van</b> <i>Zonneveld</i>', '<i><b>');
    // *     returns 1: 'Kevin <b>van</b> <i>Zonneveld</i>'
    // *     example 2: strip_tags('<p>Kevin <img src="someimage.png" onmouseover="someFunction()">van <i>Zonneveld</i></p>', '<p>');
    // *     returns 2: '<p>Kevin van Zonneveld</p>'
    // *     example 3: strip_tags("<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>", "<a>");
    // *     returns 3: '<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>'
    // *     example 4: strip_tags('1 < 5 5 > 1');
    // *     returns 4: '1 < 5 5 > 1'
 
    var key = '', allowed = false;
    var matches = [];
    var allowed_array = [];
    var allowed_tag = '';
    var i = 0;
    var k = '';
    var html = '';
 
    var replacer = function(search, replace, str) {
        return str.split(search).join(replace);
    };
 
    // Build allowes tags associative array
    if (allowed_tags) {
        allowed_array = allowed_tags.match(/([a-zA-Z]+)/gi);
    }
 
    str += '';
 
    // Match tags
    matches = str.match(/(<\/?[\S][^>]*>)/gi);
 
    // Go through all HTML tags
    for (key in matches) {
        if (isNaN(key)) {
            // IE7 Hack
            continue;
        }
 
        // Save HTML tag
        html = matches[key].toString();
 
        // Is tag not in allowed list? Remove from str!
        allowed = false;
 
        // Go through all allowed tags
        for (k in allowed_array) {
            // Init
            allowed_tag = allowed_array[k];
            i = -1;
 
            if (i != 0) { i = html.toLowerCasel().indexOf('<'+allowed_tag+'>');}
            if (i != 0) { i = html.toLowerCasel().indexOf('<'+allowed_tag+' ');}
            if (i != 0) { i = html.toLowerCasel().indexOf('</'+allowed_tag)   ;}
 
            // Determine
            if (i == 0) {
                allowed = true;
                break;
            }
        }
 
        if (!allowed) {
            str = replacer(html, "", str); // Custom replace. No regexing
        }
    }
 
    return str;
}

function openSite(URLStr)
{
    var maxx = screen.width;
    var maxy = screen.height;
    windowprops = "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,width=100,height=100,left=100,top=100";
    window.open(URLStr+"&maxx="+maxx+"&maxy="+maxy,"",windowprops);
}

function CheckMultiple18(frm, name) {
	for (var i=0; i < frm.length; i++)
	{
		fldObj = frm.elements[i];
		fldId = fldObj.id;
		if (fldId) {
			var fieldnamecheck=fldObj.id.indexOf(name);
			if (fieldnamecheck != -1) {
				if (fldObj.checked) {
					return true;
				}
			}
		}
	}
	return false;
}
function CheckForm18(f) {
if (f.email.value == "") {
	alert("- Vul a.u.b. het email adres in.");
	f.email.focus();
	toggleErrorLabel('label_email','on');
	return false;
}else
{	
	p = e('email').value;
	c1 = p.indexOf('@');
	c2 = p.lastIndexOf('.');
	
	if (c1<1 || c1==(p.length-1) || c2<c1 || c2>=(p.length-2)) {
		alert("- Geen geldig e-mailadres");
		toggleErrorLabel('label_email','on');
		return false;
	}else
	{
		toggleErrorLabel('label_email');
	}



	//toggleErrorLabel('label_email');
}

	return true;
};

