var in_ie_hell;
window.addEvent('domready', function() {
	if((document.body.id=='home') && ($('home_slideshow')!=null)) { 
		// HOME_SLIDESHOW_init();
	}
	if($$('.gallery').length>0) {
		init_slideshows();
	}
	if(Browser.Engine.trident==true) { 
		in_ie_hell=true; 
	}
	init_image_enlargements();

	// BACK LINK
	if($('back_link')!=null) {
		$('back_link').addEvent('click', function() {
			history.back();
			return false;
		});
	}
	if($('show_all_comments')!=null) {
		trigger_show_all_comments();
	}
});


///////////////////////////////////////////////////////////////////////
///////////// FADING SLIDESHOW /////////////////////////////////
/////////////////////////////////////////////////////////////////////
var page_galleries;
function init_slideshows() {
	page_galleries = $$('.gallery');
	page_galleries.each(function(gal, index) {
		var gal_id = gal.id;
		make_fading_slideshow($(gal_id), 'div.slideshow_slide');
	});
}


var news_change_interval = 5000;
var fade_speed = 500;
var news_ticker_fade_speed = 500;
var fade_delay;
var auto_play;

function make_fading_slideshow(slideshow_holder, element_tag) {
	var slideshow_holder_id = slideshow_holder.id;
	var slides = $$('#'+slideshow_holder_id+' '+element_tag);
	var num_slides = slides.length;

	slideshow_holder.his_slides = slides; 
	slideshow_holder.num_slides = num_slides; 
	slideshow_holder.cur_index = 0;
	
	slides.each(function(slide, index) {
		slide.store('his_index', index);
		slide.store('his_z_index', num_slides);
		slide.setStyles({
			position: 'absolute',
			top: 0,
			left: 0,
			'z-index': num_slides
		});
		num_slides--;
	});

	// CONTROL BUSINESS  / FADE
	slideshow_holder.store('fading', false);
	
	var slideshow_controls = $$('#'+slideshow_holder_id+' a.slider_control');
	slideshow_holder.store('gallery_controls', slideshow_controls);
	//if(slideshow_controls.length>0) {
		//slideshow_holder.store('auto_play', false);
		slideshow_holder.retrieve('gallery_controls').each(function(slide_control, index) {
			if(slide_control.hasClass('prev_slide')) {
				slide_control.addEvent('click', function() {
					var show_is_fading = slideshow_holder.retrieve('fading');
					if(show_is_fading==false) {
						fade_slide_V2(slideshow_holder, 'prev');
					}
					// PREVENT AUTO FADING
					slideshow_holder.store('auto_play', false);
					clearTimeout(slideshow_holder.retrieve('fade_delay'));
					return false;
				});			
			} else if(slide_control.hasClass('next_slide')) {
				slide_control.addEvent('click', function() {
					var show_is_fading = slideshow_holder.retrieve('fading');
					if(show_is_fading==false) {
						fade_slide_V2(slideshow_holder, 'next');
					}
					// PREVENT AUTO FADING
					slideshow_holder.store('auto_play', false);
					clearTimeout(slideshow_holder.retrieve('fade_delay'));

					return false;
				});
			}
		});
	//} else {
		slideshow_holder.store('auto_play', true);
		// alert('slideshow_holder = '+slideshow_holder.id);
		slideshow_holder.store('fade_delay', fade_slide_V2.delay(news_change_interval, slideshow_holder));
	//}	
}

function fade_slide_V2(active_slideshow, slideshow_direction) {
	if(active_slideshow==undefined) {
		active_slideshow = this;
	}
	active_slideshow.store('fading', true);
	if(slideshow_direction==undefined) {
		slideshow_direction = 'next';
	}
	if(active_slideshow.id=='news_ticker') {
		active_slideshow.store('this_fade_speed', news_ticker_fade_speed);
	} else {
		active_slideshow.store('this_fade_speed', fade_speed);
	}
	var NEXT_reset_top = false;
	var PREV_reset_top = false;
	var cur_index = active_slideshow.cur_index;
	var slides = active_slideshow.his_slides;
	var num_slides = active_slideshow.num_slides;
	var next_index;
	var index_to_fade;

	if(slideshow_direction=='next') {
		var top_opacity_start = 1;
		var top_opacity_end = 0;
		if((cur_index+1)<num_slides) {
			NEXT_reset_top = false;
			next_index = cur_index+1;
		} else {
			NEXT_reset_top = true;
			next_index = 0;
			top_opacity_end = 1;
		}	
		// RESET INBETWEENERS ALS INDEX: 0 IS
		if(next_index==1) { NEXT_reset_inbetweeners(slides); }
		index_to_fade = cur_index;
	} else if(slideshow_direction=='prev') {
		if(cur_index==0) {
			PREV_reset_inbetweeners(slides);
			var top_opacity_start = 1;
			var top_opacity_end = 0;
			next_index = num_slides - 1;
			index_to_fade = cur_index;
		} else {
			var top_opacity_start = 0;
			var top_opacity_end = 1;
			next_index = cur_index - 1;					
			index_to_fade = next_index;
		}
	
	}
	// if(active_slideshow.id=='page_slideshow') {	output('cur_index = '+cur_index+' | next_index = '+next_index); }

	var fade_top = new Fx.Tween(slides[index_to_fade], {property: 'opacity', duration: active_slideshow.retrieve('this_fade_speed')});
	fade_top.start(top_opacity_start, top_opacity_end).chain(
			function(){ 
				if(NEXT_reset_top==false) {
					if(slideshow_direction=='next') {
						active_slideshow.cur_index++;
					} else {
						if(cur_index==0) {
							active_slideshow.cur_index=num_slides - 1;
						} else {
							active_slideshow.cur_index--;
						}
					}
				} else {
					active_slideshow.cur_index = 0;
				}
				active_slideshow.store('fading', false);
				var this_auto_play = active_slideshow.retrieve('auto_play');
				if(this_auto_play==true) {
					clearTimeout(active_slideshow.retrieve('fade_delay'));
					active_slideshow.store('fade_delay', fade_slide_V2.delay(news_change_interval, active_slideshow));
				}
			}
	);
	if((NEXT_reset_top==true) && (slides[next_index].getStyle('opacity')==0)) {
		//output('NEXT_reset_top | next_index = '+next_index);
		var fade_bottom = new Fx.Tween(slides[next_index], {property: 'opacity', duration: active_slideshow.retrieve('this_fade_speed')});
		fade_bottom.start(0, 1);
	} 
}
function NEXT_reset_inbetweeners(slides) {
	// ZET TUSSENLIGGENDE SLIDES WEER OP 1
	slides.each(function(slide, slide_index) {
		if(slide_index>0) {
			slide.setStyle('opacity', 1);
		}
	});
}
function PREV_reset_inbetweeners(slides) {
	// ZET TUSSENLIGGENDE SLIDES WEER OP 1
	slides.each(function(slide, slide_index) {
		if((slide_index>0) && (slide_index<(slides.length-1))) {
			slide.setStyle('opacity', 0);
		} else if(slide_index==(slides.length-1)) {
			slide.setStyle('opacity', 1);
		}
	});
}
var output_div_available;
var output_div;
function output(string) {
	if(output_div_available==undefined) {
		if($('output')!=null) {
			output_div_available=true;
			output_div = $('output');
		} else {
			output_div_available=false;		
		}
	}
	if(output_div_available==true) {
	//$('output').appendText("<br />"+string);	
		var cur_content = output_div.innerHTML;
		output_div.innerHTML = cur_content+'<br />'+string;
	}
	return false;
}
/////////////////// SHOW ALL COMMENTS //////////////////////////
function trigger_show_all_comments() {
	var show_all_link = $('show_all_comments');
	var og_show_all_text = show_all_link.innerHTML;
	
	var hidden_comments = $$('div.hidden_comment');
	show_all_link.addEvent('click', function() {
		if(hidden_comments[0].getStyle('display')=='block') {
			hidden_comments.each(function(hidden_comment, index) {
				hidden_comment.setStyle('display', 'none');
			});
			show_all_link.innerHTML = og_show_all_text;
		} else {
			hidden_comments.each(function(hidden_comment, index) {
				hidden_comment.setStyle('display', 'block');
			});
			show_all_link.innerHTML = '&lt;&lt; verberg reacties';
		}
		return false;
	});
}
//////////////////////////////////////////////////////////////////
/////////////////// MODAL EN AJAX STUFF //////////////////////////
//////////////////////////////////////////////////////////////////


var modal_to_show = '';
var modal_pic_height=0;
var image_to_enlarge;

function show_modal(the_link) {
	// SHOW LOADER
	link_insert_loader(the_link);
	// LOAD FILE
	// INSERT MODAL HOLDING HTML
	insert_modal_html();
	// MODAL ID
	modal_to_show = 'rabk_modal';
	var load_file = the_link.href;
	// MAKE ZE CALL
	sendRequest(load_file, handleRequest);
}

function init_image_enlargements() {
	var large_img_links = $$('.enlarge_image');
	large_img_links.addEvent('click', function() {
		enlarge_image(this);
		return false;
	});
}

function enlarge_image(the_link) {
	// SHOW LOADER
	link_insert_loader(the_link);
	// INSERT MODAL HOLDING HTML
	insert_modal_html();
	// LOAD FILE
	image_to_enlarge = the_link.href;
	// MODAL ID
	modal_to_show = 'enlarge_img';
	
	// PRELOAD IMAGE
	var load_img = new Image();
	load_img.onload = function() {
		var his_width = load_img.width;
		var his_height = load_img.height;
		var html_to_show='<div id="enlarge_img" style="width:'+his_width+'px"class="page_modal"><a name="close_werk_modal" id="close_modal"><img src="'+image_to_enlarge+'" id="modal_enlarge_image" border="0" width="'+his_width+'" height="'+his_height+'" /></a></div>';
		var container = document.getElementById('modal_holder');
		container.innerHTML = html_to_show;

		hide_inserted_loader();
		launch_modal(modal_to_show);
	}
	load_img.src=image_to_enlarge;
}

function insert_msg_modal(the_link, msg) {
	// SHOW LOADER
	link_insert_loader(the_link);
	// INSERT MODAL HOLDING HTML
	insert_modal_html();
	// MODAL ID
	modal_to_show = 'de_vorm_message';
	
	var html_to_show='<div id="de_vorm_message" class="page_modal"><a name="close_werk_modal" id="close_modal" class="close_modal"></a><hr class="clear" style="height: 10px;">'+msg+'</div>';
	
	var container = document.getElementById('modal_holder');
	container.innerHTML = html_to_show;

	hide_inserted_loader();
	launch_modal(modal_to_show);
}

function insert_modal_html() {
	// INSERT HTML AT TOP OF PAGE
	var body_tag = document.getElementsByTagName("body").item(0);
	// -- MODAL
	var page_modal = document.createElement("div");
	page_modal.setAttribute('id','modal_holder');
	body_tag.insertBefore(page_modal, body_tag.firstChild);
	// -- OVERLAY
	var overlay_div = document.createElement("div");
	overlay_div.setAttribute('id','overlay');
	body_tag.insertBefore(overlay_div, page_modal.nextSibling);
}
///////// SHOW LOADING /////////
var active_link;
function toggle_opacity(link, state) {
	active_link = link;
	var linked_img=link.getElement('img');

//	var linked_img = link.childNodes[1];
	if(state=='full') {
		opacity_val=1;
	} else {
		opacity_val=0.5;
	}
	if(in_ie_hell==false) {
		linked_img.style.opacity = opacity_val;
	} else {
		linked_img.style.filter = 'alpha(opacity=' + opacity_val*100 + ')';
	}
}
var active_loading_link;
var active_loading_link_html;
var mix_loader_html = ' <img src="_img/ajax_loader.gif" alt="Loading..." border="0" />';

function link_insert_loader(the_link) {
	active_loading_link = the_link;
	active_loading_link_html = the_link.innerHTML;
	the_link.innerHTML = active_loading_link_html + mix_loader_html;
}
function hide_inserted_loader() {
	if((active_loading_link!='') && (active_loading_link!=null)) {
		active_loading_link.innerHTML = active_loading_link_html;
	} 
}

/* -----------------------------------------------------
	INSTANT EDIT CALLBACK FUNCTIONS
 -----------------------------------------------------*/
function handleRequest(req) {
	var html_to_show = req.responseText;
	var container = document.getElementById('modal_holder');
	container.innerHTML = html_to_show;
	hide_inserted_loader();
	launch_modal(modal_to_show);
}
/* -----------------------------------------------------
	XMLHTTP Functions
	As found on Quirksmode. You hero.
 -----------------------------------------------------*/

function sendRequest(url,callback,postData) {
	var req = createXMLHTTPObject();
	if (!req) return;
	var method = (postData) ? "POST" : "GET";
	req.open(method,url,true);
	req.setRequestHeader('User-Agent','XMLHTTP/1.0');
	if (postData)
		req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
	req.onreadystatechange = function () {
		if (req.readyState != 4) return;
		if (req.status != 200 && req.status != 304) {
		//	alert('HTTP error ' + req.status);
			return;
		}
		callback(req);
	}
	if (req.readyState == 4) return;
	req.send(postData);
}

function XMLHttpFactories() {
	return [
		function () {return new XMLHttpRequest()},
		function () {return new ActiveXObject("Msxml2.XMLHTTP")},
		function () {return new ActiveXObject("Msxml3.XMLHTTP")},
		function () {return new ActiveXObject("Microsoft.XMLHTTP")}
	];
}

function createXMLHTTPObject() {
	var xmlhttp = false;
	var factories = XMLHttpFactories();
	for (var i=0;i<factories.length;i++) {
		try {
			xmlhttp = factories[i]();
		}
		catch (e) {
			continue;
		}
		break;
	}
	return xmlhttp;
}
/* -----------------------------------------------------
	SET OVERLAY STUFF
 -----------------------------------------------------*/
var array_page_size;
var overlay_div;
var scroll_x, scroll_y, window_w, window_h;


function get_page_size(){
	var scroll_position = window.getScroll();
	scroll_x = scroll_position.x;
	scroll_y = scroll_position.y;

	var body_size =  $(document.body).getScrollSize();
	body_w = body_size.x;
	body_h = body_size.y;
	
	var window_size = window.getSize();
	window_w = window_size.x;
	window_h = window_size.y;
	
	// for small pages with total height less then height of the viewport
	if(body_h < window_h){
		page_h = window_h;
	} else { 
		page_h = body_h;
	}

	// for small pages with total width less then width of the viewport
	if(scroll_x < window_w){	
		page_w = window_w;
	} else {
		page_w = body_w;
	}
	array_page_size = new Array(page_w, page_h, window_w, window_h);
	return array_page_size;
}

function show_overlay(overlay_height_int) {
	var overlay_height = overlay_height_int + 'px';
	overlay_div.setStyle('height', overlay_height);
	overlay_div.setStyle('display', 'block');
	overlay_div.setStyle('opacity', '0');
	overlay_div.fade(0, 1);
}

function launch_modal(modal_to_display) {

	array_page_size=get_page_size();

	var target_modal_div = $(modal_to_display);
	// ZET OP ZICHTBAAR
	target_modal_div.setStyle('opacity', '0');
	target_modal_div.style.display = "block";
	//  MODAL DIMENSIONS
	var modal_size = target_modal_div.getSize();
	var modal_div_w = modal_size.x;
	var modal_div_h = modal_size.y;
	
	var page_height = array_page_size[1];
	var overlay_height = page_height;
	if(modal_div_h>page_height) {
		overlay_height = modal_div_h;
	}	

	// CENTER THE MODAL AND MAKE SURE LEFT AND TOP VALUES ARE NOT NEGATIVE
	var modal_div_x = Math.round(((array_page_size[2] - modal_div_w) / 2));
	var modal_div_y = Math.round(scroll_y + ((array_page_size[3] - modal_div_h) / 2));

	target_modal_div.style.top = (modal_div_y < 0) ? "0px" : modal_div_y + "px";
	target_modal_div.style.left = (modal_div_x < 0) ? "0px" : modal_div_x + "px";

 	// OVERLAY
	overlay_div = $('overlay');
	show_overlay(overlay_height);
	target_modal_div.fade(0, 1);
	
	// ACTIVATE GALLERY
	if($('modal_gallery')) {
		activate_gallery('modal_gallery');
	}
	// ENLARGE IMAGE BUSINESS	
	if(modal_to_display=='de_vorm_enlarge_img') {
		
	}
	// CLOSE BUSINESS
	var close_link = $('close_modal');
	if(close_link) {
		close_link.onclick=function() {
			close_cur_modal();
		}
	}
	overlay_div.onclick=function() {
		close_cur_modal();
	}
}
var div_fader = new Fx;

function close_cur_modal() {
	if (document.getElementById) {
		// REMOVE THE DYNAMIC DIVS
		if ($(modal_to_show)) { 	
			var modal_to_show_to_del = $(modal_to_show);
			div_fader = new Fx.Tween(modal_to_show_to_del, { property: 'opacity', duration: 150 } ).start(1, 0);
		}
		if ($('overlay')) { 	
			var overlay = $('overlay');
			div_fader = new Fx.Tween(overlay, { property: 'opacity', duration: 150 } ).start(1, 0).chain(
				function() {  
				  	document.body.removeChild(overlay);
			  		var modal_holder = $('modal_holder');
				  	document.body.removeChild(modal_holder);
				}
			);
		}
	}
}
function start_key_functions() {
 	document.onkeydown = check_key;
}
function check_key(event) {
	// IE hack
	if (window.event) { event = window.event; }
	var keycode = event.keyCode;
	var escapeKey;
	if (event.DOM_VK_ESCAPE) {  // mozilla
		escapeKey = event.DOM_VK_ESCAPE;
	} else { // ie
		escapeKey = 27;
	}
	var key = String.fromCharCode(keycode).toLowerCase();
	if (keycode == escapeKey){ // close lightbox
			close_cur_modal();
	}
}
start_key_functions();


function delete_swf_on_unload() {
	window.addEvent ('beforeunload', function() {
		var swf_holders = $$('video_holder');
		// alert('weg halen anders faalt IE ZO HARD!')
		swf_holders.each(function() {
			this.dispose();
		});
	}); 
}

////////////////////////////////////////////////////////////////
//////////////////// VALIDATE BUSINESS ////////////////////
////////////////////////////////////////////////////////////
function validate_add_comment(theform) {
	if(!default_check(theform.poster_name)) { return false; }
	if(!default_check(theform.poster_email)) { return false; }
	if(!echeck(theform.poster_email.value)) { 
		theform.poster_email.focus();
		return false; 
	}
	// if(!default_check(theform.msg_subject)) { return false; }
	if(!default_check(theform.comment_add)) { return false; }
	if(!default_check(theform.check_it)) { return false; }	
	return true;
}
function validate_search(theform) {
	if(!default_check(theform.prd_search_term)) { return false; }
	return true;
}
function validate_login(theform) {
	var login_email=theform.RABK_login_email;
	if(!default_check(login_email)) { return false; }
	if (echeck(login_email.value)==false){
		login_email.focus()
		return false;
	}
	var login_pass=theform.RABK_login_pass;
	if(!default_check(login_pass)) { return false; }
}
function validate_email(theform) {
	var login_email=theform.RABK_user_email;
	if(!default_check(login_email)) { return false; }
	if (echeck(login_email.value)==false){
		login_email.focus()
		return false;
	}
}
var default_border_color = '#000000';
function default_check(input) {
	if ((input.value==null)||(input.value=="")){
    	input.style.borderColor="#ff0000";
		input.focus();
		return false;
	} else {
        input.style.borderColor=default_border_color;
        return true;
	}
}
function validate_new_slide(theform) {
	var file_to_upload = theform.file1.value;
	if(file_to_upload!='') {
		if(!default_check(theform.slideshow_image_name)) { return false; }
		if(!default_check(theform.slideshow_image_name_eng)) { return false; }
	}
	return true;
}

function echeck(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   alert("Invalid e-mail adress")
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   alert("Invalid e-mail adress")
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    alert("Invalid e-mail adress")
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    alert("Invalid e-mail adress")
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    alert("Invalid e-mail adress")
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    alert("Invalid e-mail adress")
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    alert("Invalid e-mail adress")
		    return false
		 }
 		 return true					
}

/***** * script voor de show/hide divs  ****/
function toggle_div(whichLayer)    {
    if (document.getElementById) {
        // this is the way the standards work
        var target_div = document.getElementById(whichLayer);
        var cur_display = target_div.style.display;
        if(cur_display=='block') {
        	target_div.style.display = 'none';
        	// CHECK OF ER EEN IMAGE_BANK IN OPEN STAAT, DAN VERWIJDEREN
        	if(beeldbank_container!=undefined) {
        		beeldbank_container.innerHTML='';
        	}
        } else {
        	target_div.style.display = 'block';
	    }
    } 
}

