var ISIE=false, CurrentPollID=0;


// >>> START JQUERY >>>
$(document).ready(function() {
							
								
// check of het Internet Explorer is
ISIE=$.browser.msie; 
// css preloader:
$.preloadCssImages();


// ## NORMAL MENU ##
var normalMenu=$("#top_menu ul");
normalMenu.find("li:not(.active)").hover(function(){
	$(this).addClass("menu_over");
},function(){
	$(this).removeClass("menu_over");
});
													

// ## DROPDOWN MENU ##
/*

var $DropdownMenu=$("#topmenu1");
var $DivSubNav= $DropdownMenu.find(".subnav");
var $MenuHover= $DivSubNav.find("li");
$DropdownMenu.find(".menuchild ul").parent().append("<span class=\"has_child\"></span>");
$DropdownMenu.find("ul.mselected").parents("li").children("a").addClass("childselected");
$DivSubNav.each(function () {
													
	$(this).parent().eq(0).hoverIntent({
		timeout: 100,over: function () {
			var current = $(".subnav:eq(0)", this);current.slideDown(100);
		},out: function () {
			var current = $(".subnav:eq(0)", this);current.slideUp(200);
		}
	});

});
*/


// ## CUSTOM DROPDOWN MENU##
/*
var $DropdownMenu=$("#topmenu1");
var $DivSubNav= $(".subnav");
var maxHeight= 50;
$DivSubNav.find("ul").makeacolumnlists();
$DropdownMenu.find(".menuchild").append("<span class=\"has_child\"></span>");
$DropdownMenu.find(".mselected").addClass("childselected");
$DivSubNav.each(function(){													
var $ParentID,$child, ChildID, ParentID;
$child= $(this);
ParentID="#parent_"+$child.attr("data-child");
$parent=$(ParentID);
	$parent.hoverIntent({
			timeout: 200,over: function () {
				var current = $($child, this);
				$(".subnav").not($child).slideUp(400);				
				current.slideDown(200);
			},out: function () {
			var current = $($child, this);
			current.mouseleave(function(){
			current.slideUp(400);
			});
			}
	});
});
$("#container").click(function(){$DivSubNav.slideUp(400);	});	
*/

// move page title
var pageTitle=""
pageTitle=$(".pagina_aanhef_text:not(:empty)").html();
$(".pagina_aanhef").remove();
if(pageTitle!=null){$("#subtitle").html(pageTitle);}else{$("#subtitle").remove();}


// content picture enlargement
 $("#pagina_back").find("figure.zoom").click(function () {
    var $this = $(this), imageurl = $this.data("zoomurl");
	 $.lightbox(imageurl);
  });
$(".usercontact").lightbox();




// Dynamic backgrounds:
/*
$.mbBgndGallery.buildGallery({
			containment:"body",
			timer:20000,
			effTimer:2000,
			grayScale:false,
			images:buildGalList
});
*/


// zoeken:
var DefaultSearch=$(".zoek_tekst")
var SearchVal=DefaultSearch.val();
DefaultSearch.focus(function(){
	if(DefaultSearch.val() == DefaultSearch.val()){
		DefaultSearch.attr("value", "");	
		}
});
DefaultSearch.blur(function(){
		if(DefaultSearch.val() == ""){
			DefaultSearch.attr("value", SearchVal);
		}
});



// ### initialiseer items ##
// Vervang email links door spamprotected email link:
$("a.email").nospam();
// external links
$('A[rel="external"]').click( function(){window.open( this.href );return false;});	
// Page Tabs
$("#paginatabs").tabs();
// media player
$("a.media").media();



// ## fotoalbum modev ###
// vergberg sidebars 
// Pagina extenden naar breedte pagina 
if($("#fotoalbum").length>0){
// inatieer photo popup
} // einde fotoalbum mode

// checkboxes ui
	$('input').checkBox();


// ######### EFFECTEN  ALGEMEEN ##############


// ## FOOTER OPTIONS 






// ### SIDEBAR KALENDER ### 
var DivKalender=$("#kalender");
if(DivKalender.length>0){
DivKalender.html("<img src=\"/images/ajaxloaders/ajax-loader_small3.gif\" style=\"margin:0px auto;\"/>");
$.get('/include/ajax_kalender.asp', function(output){
if(output!=""){	
		DivKalender.html(output);
		}		
	});
$("#kalender .dd_dag").live('mouseover',function(){
	$(this).css({backgroundColor:"#dceffd"});
});
$("#kalender .dd_dag").live('mouseout',function(){
	$(this).css({backgroundColor:""});
});
}


// ### SIDEBAR RSS FEEDS ##
var DivRSSFeed1=$("#rssfeed1");
if(DivRSSFeed1.length>0){
var furl1= DivRSSFeed1.attr("furl");
var fname1= DivRSSFeed1.attr("fname");
var faantal1= DivRSSFeed1.attr("faantal");
DivRSSFeed1.rssfeed(''+furl1+'', {
		limit: faantal1,
		titletag:'h2',
		date:true
	});
}
var DivRSSFeed2=$("#rssfeed2");
if(DivRSSFeed2.length>0){
var furl2= DivRSSFeed2.attr("furl");
var fname2= DivRSSFeed2.attr("fname");
var faantal2= DivRSSFeed2.attr("faantal");
DivRSSFeed2.rssfeed(''+furl2+'', {
		limit: faantal2,
		titletag:'h2',
		date:true
	});
}




// ### SIDEBAR Sitemap ##


// ### SIDEBAR TAG CLOUD ##
var sidebar007=$("#sidebar007");
if(sidebar007.length>0){
$("#pagina_back").dynaCloud();
}

		
// ### SIDEBAR POLL ##
$("#poll").submit(formProcess); 
if ($.cookie('Archipoll')){
 $("#poll_container").empty();
 CurrentPollID = $.cookie('Archipoll');
	$.get("/include/polls.asp?Poll_id="+CurrentPollID,function(Results){
   		if(Results!=""){$("#poll_container").append(Results).fadeIn("fast",function(){animateResults();});}	
	}); 
}

// #popup dialog generator
// Title of clicked element is hidden target that needs to popup.

$(".open_dialog").click(function(e){
e.preventDefault();
var $Target=$($(this).attr("title"));
var Thtml=$Target.html(); 
var Ttitle=$Target.attr("title");
var $dialog=$("<div></div>").dialog({
			modal: true,
			autoOpen: false,
			title: Ttitle,
			width: 500
		}).html(Thtml);
	$dialog.dialog("open");
	return false;
});

// # Print content function
// Open target content in new window to print
$('.print_window').click(function(e){
e.preventDefault();
var $Target=$($(this).attr("title"));
var Thtml=$Target.html(); 
var Ttitle=$Target.attr("title");
var Print =  window.open('','Print','width=800,height=800');
var html = '<html><head><title>'+Ttitle+'</title><link type="text/css" href="/custom/bio/print.css" rel="stylesheet" /></head><body><div>' +Thtml+ '</div></body></html>';
    Print.document.open();
    Print.document.write(html);
    Print.document.close();
    return false;
});

// # Accordion ui
$(".accordion").accordion({
autoHeight: false,
active:false,
collapsible: true
});


// ### FORM  OPTIONS EN SPAM CHECK ###


// form buttons effect:
$('.submit_button').hover(function(){
//mouseover
$(this).addClass('submit_buttonhover'); 
},function(){
//mouseout
$(this).removeClass('submit_buttonhover'); 
});

$(".datumveld").datepicker({dateFormat: 'dd-mm-yy', changeMonth: true, changeYear: true});
$( ".submit_button, a.button").button();








// limiet voor textarea
$('.ta_limit100').keyup(function() {
      var maxlen = 450;
      var len = this.value.length;
      if (len >= maxlen) { this.value = this.value.substring(0, maxlen); }
      $('#charleft').text("Max chars:" + (maxlen - len));
  });




//## EVENT KALENDER ##
$(".month_selector").live('click',function(){
var smonth=$(this).attr("data-month");
var syear=$(this).attr("data-year");
kal_maand(smonth,syear,'','','');
});

$(".dd_vandaag a, .dd_dag a").live('click',function(e){
 e.preventDefault();

	var $this=$(this);
	var url=$this.attr("href");
	var stitle=$this.attr("title");
	var $pop=$("#event_dialog");
	$pop.dialog({
		modal:true,
		open: function(){
				$pop.load(url);
				},
		height:400,
		width:600,
		title:stitle						
	});
});



$("#slider").easySlider({
		controlsBefore:	'<div id="controls" class="cls">',
		controlsAfter:	'</div>',
		auto: true, 
		continuous: true,
		pause:			5000,
		prevText: 		'',
		nextText: ''
	});	


  
function dev_reload_image(img_id, new_src) {
var  img_id = img_id || '#default_image_id';
img_id = jQuery(img_id);
var  new_src = new_src || '';
        
		if (img_id) {
				old_src = jQuery(img_id).attr('src') || '';
				
				// No change in source we'll have to add random data to the url to refresh the image
				if (new_src == '' || old_src == new_src) {
						if (old_src.indexOf('?') == -1) { 
								old_src += '?';
						} else {
								old_src += '&';
						}
						old_src += '__rnd=' + Math.random();
						img_id.attr('src', old_src);
				} else {
						img_id.attr('src', new_src);
				}
		}
}	
	

function ajaxFileUpload(fileid){
var dobj=fileid.data();
	
	 $("#loading")
        .ajaxStart(function(){
            $(this).show();
        })
        .ajaxComplete(function(){
            $(this).hide();
        });
				

		 $.ajaxFileUpload({
				url:'/include/uploader.asp?umode='+dobj.mode+'&udir='+dobj.dir, 
				secureuri:false,
				fileElementId:'frm_avatar',
				dataType: 'json',
				success: function (data, status)
				{
						if(typeof(data.error) != 'undefined')
						{
								if(data.error != '')
								{
								//    console.log("mislukt:"+data.error);
								}else
								{
								//	console.log("gelukt:"+data);
		
								}
						}
						if(data){
						//	console.log("hi there");
							dev_reload_image(".user-avatar-img");
						}
				},
				error: function (data, status, e)
				{
					//  console.log(e);
				}
		}
)        
 return false;
} // end fileupload
	
$("#user_image_submit").click(function(){
																
	return ajaxFileUpload($("#frm_avatar"))

});

/* >>>>>>>>>> EINDE JQUERY READY <<<<<<<<<< */
 });





//################### LOAD WINDOW SCRIPTS ##################
//$(window).load(function(){}); 
//  END window load 


// ###################### FUNCTIONS  #############

function kal_maand(maand, jaar, P, M, G){
$("#kalender").load('/include/ajax_kalender.asp?KM='+maand+'&KY='+jaar+'&P='+P+'&M='+M+'&G='+G, function(response){
if(response!="false"){$("#kalender").html(response);}
	});																														  
};



// nieuws headlines: volgende / vorige
function get_headlines(page){
$("#tab-nieuws").load('/include/ajax_nieuws.asp?mode=nhl&page='+page, function(response){
if(response!="false"){$("#tab-nieuws").html(response);}
	});																														  
};


// ### POLL FUNCTIONS //
function formProcess(event){
 event.preventDefault();   
  var SelectedVote = $("input[@name='vote']:checked").attr("value");
  var PollID= $("#poll_id").val();
  var GID= $("#GID_ID").val();
  VoteID = SelectedVote.replace("opt",'');
  CurrentPollId=PollID;
  
	$("#poll_container").fadeOut("fast",function(){
   	 $(this).empty();
		 
		 $.get('/include/polls.asp?vote='+VoteID+'&poll_id='+PollID+'&GID_ID='+GID, function(output){
			
			if(output!=""){	
			$("#poll_container").append(output).fadeIn("fast",function(){animateResults();});
			}	
				
		});
	});
  $.cookie('Archipoll',PollID,{expires: 365});  
}

function animateResults(){
  $("#poll_container .bar_bar div").each(function(){
      var percentage = $(this).next().text();
      $(this).css({width: "0%"}).animate({
		width: percentage}, 'slow');
  });
}



// _________________ / FUNCTIONS ________________

/* ****************************************
function: open and closing sliders of BARS (NOT panels)
SliderPos: left/right/top/bottom
e: element
******************************************/
function SliderControl(e, SliderPos) {
    var $Element = $("#" + SliderPos + "_bar .bar_content");
    var elem = {};
    var mode1 = "slide_" + SliderPos + "_open";
    var mode2 = "slide_" + SliderPos + "_close";
    var sWidth = 0;
    var sHeight = 0;
    var SliderTime = 200;

    if (SliderPos === "left" || SliderPos === "right") { sWidth = $Element.width(); }
    if (SliderPos === "top" || SliderPos === "bottom") { sHeight = $Element.height(); }

    if (sWidth !== 0) {

        if (e.parent().hasClass("openbar")) {
            //close the bar
            elem["margin-" + SliderPos] = "-" + sWidth + "px";
            $Element.stop().animate(elem, SliderTime, function() {
                e.parent().removeClass(mode2).addClass(mode1).removeClass("openbar");
            });
        } else {
            //open tab      
            elem["margin-" + SliderPos] = "0px";
            $Element.stop().animate(elem, SliderTime, function() {
                e.parent().removeClass(mode1).addClass(mode2).addClass("openbar");
            });
        }

    } else if (sHeight !== 0) {

        if (e.parent().hasClass("openbar")) {

            // opentab              
            elem["margin-" + SliderPos] = "-" + sHeight + "px";

            $Element.stop().animate(elem, SliderTime, function() {
                e.parent().removeClass(mode2).addClass(mode1).removeClass("openbar");
            });
        } else {
            //close tab
            elem["margin-" + SliderPos] = "0px";
            $Element.stop().animate(elem, SliderTime, function() {
                $Element.addClass("opentab");
                e.parent().removeClass(mode1).addClass(mode2).addClass("openbar");
            });
        }
    }
}



// slideshow subheader
function slideSwitch() {
    var $active = $('.client_box ul li.active');
    if ( $active.length === 0 ) $active = $('.client_box ul li:last');
    // use this to pull the images in the order they appear in the markup
    var $next =  $active.next().length ? $active.next()
        : $('.client_box ul li:first');
    // uncomment the 3 lines below to pull the images in random order    
     var $sibs  = $active.siblings();
     var rndNum = Math.floor(Math.random() * $sibs.length );
     var $next  = $( $sibs[ rndNum ] );
    $active.addClass('last-active');
    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 500, function() {
            $active.removeClass('active last-active');
        });
}
$(function() {
    setInterval( "slideSwitch()", 9000 );
});


// decapicate words
function trimWords(text,length){
	var t = text.replace(/\s/g,' ');
	var words = t.split(' ');
	if(words.length<=length)	return text;
	var ret='';
	for(var i=0;i<length;i++){
		ret+=words[i]+' ';
	}
	return ret;
}

// decapicate characters
function trimText(text, length){
	if(text.length<=length){ 
		return text;
	}
	else{
		var ret='';
		var t=text.split('');
		for(i=0; i<length; i++){
			ret+=t[i];
		}
		return ret;
	}
}



// Check whether string s is empty.
function isEmpty(s){return((s==null)||(s.length==0))}



// Jelastic plugin:
(function(g){g.fn.extend({elastic:function(){var h=["paddingTop","paddingRight","paddingBottom","paddingLeft","fontSize","lineHeight","fontFamily","width","fontWeight"];return this.each(function(){function i(c,j){curratedHeight=Math.floor(parseInt(c,10));a.height()!=curratedHeight&&a.css({height:curratedHeight+"px",overflow:j})}function k(){var c=a.val().replace(/&/g,"&amp;").replace(/ /g,"&nbsp;").replace(/<|>/g,"&gt;").replace(/\n/g,"<br />"),j=b.html().replace(/<br>/ig,"<br />");if(c+"&nbsp;"!= j){b.html(c+"&nbsp;");if(Math.abs(b.height()+l-a.height())>3){c=b.height()+l;if(c>=d)i(d,"auto");else c<=e?i(e,"hidden"):i(c,"hidden")}}}if(this.type!="textarea")return false;var a=g(this),b=g("<div />").css({position:"absolute",display:"none","word-wrap":"break-word"}),l=parseInt(a.css("line-height"),10)||parseInt(a.css("font-size"),"10"),e=parseInt(a.css("height"),10)||l*3,d=parseInt(a.css("max-height"),10)||Number.MAX_VALUE,f=0;if(d<0)d=Number.MAX_VALUE;b.appendTo(a.parent());for(f=h.length;f--;)b.css(h[f].toString(), a.css(h[f].toString()));a.css({overflow:"hidden"});a.bind("keyup change cut paste",function(){k()});a.bind("blur",function(){if(b.height()<d)b.height()>e?a.height(b.height()):a.height(e)});a.live("input paste",function(){setTimeout(k,250)});k()})}})})(jQuery);$("textarea").elastic();


// antispam 
// doe checks op formulieren met class webform:
$(".webform").validate({rules:{antispam_veld:{required:true,minlength:6}},messages:{antispam_veld:{required:"Enter the correct code.",minlength:"enter the 6 digit code"}},submitHandler:function(form){var imgID=$("#antispam_img").attr("title");var spamNaam=$("input#antispam_veld").val();if($("#spamchecker").val()!="true"){$.get('/include/ajax_antispam.asp?antispam='+spamNaam+'&imgID='+imgID,function(response){if(response=="true"){$("#spamchecker").val("true");form.submit();}else{$("#antispam_msg").html("<img src=\"/images/folders/arrow_down.png\" alt=\"Fault!\" style=\"vertical-align:middle;\"/>Enter correct code.<br/>");$("#antispam_msg").show("fast");return false;}});}else{form.submit();}}});$(".weblogin").validate();

// Get querystring from url:
;(function($){$.extend({getQueryString:function(name){function parseParams(){var params={},e,a=/\+/g,r=/([^&=]+)=?([^&]*)/g,d=function(s){return decodeURIComponent(s.replace(a," "));},q=window.location.search.substring(1);while(e=r.exec(q))
params[d(e[1])]=d(e[2]);return params;}
if(!this.queryStringParams)
this.queryStringParams=parseParams();return this.queryStringParams[name];}});})(jQuery);


// Jquery cookie:
jQuery.cookie=function(key,value,options){if(arguments.length>1&&(value===null||typeof value!=="object")){options=jQuery.extend({},options);if(value===null){options.expires=-1;}
if(typeof options.expires==='number'){var days=options.expires,t=options.expires=new Date();t.setDate(t.getDate()+days);}
return(document.cookie=[encodeURIComponent(key),'=',options.raw?String(value):encodeURIComponent(String(value)),options.expires?'; expires='+options.expires.toUTCString():'',options.path?'; path='+options.path:'',options.domain?'; domain='+options.domain:'',options.secure?'; secure':''].join(''));}
options=value||{};var result,decode=options.raw?function(s){return s;}:decodeURIComponent;return(result=new RegExp('(?:^|; )'+encodeURIComponent(key)+'=([^;]*)').exec(document.cookie))?decode(result[1]):null;};


// mailto nospam:
jQuery.fn.nospam=function(settings){settings=jQuery.extend({replaceText:false,filterLevel:'normal'},settings);return this.each(function(){e=null;if(settings.filterLevel=='low'){if($(this).is('a[rel]')){e=$(this).attr('rel').replace('][','@').replace(/\//g,'.')}else{e=$(this).text().replace('][','@').replace(/\//g,'.')}}else{if($(this).is('a[rel]')){e=$(this).attr('rel').split('').reverse().join('').replace('][','@').replace(/\//g,'.')}else{e=$(this).text().split('').reverse().join('').replace('][','@').replace(/\//g,'.')}}if(e){if($(this).is('a[rel]')){$(this).attr('href','mailto:'+e);if(settings.replaceText){$(this).text(e)}}else{$(this).text(e)}}})};




