scripts = document.getElementsByTagName('script');
index = scripts.length - 1;
myScript = scripts[index];
queryString = myScript.src.replace(/^[^\?]+\??/,'');

var params = parseQuery( queryString );

function parseQuery ( query ) {
   var Params = new Object ();
   if ( ! query ) return Params; // return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) continue;
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function replaceAll(text, strA, strB){
    while ( text.indexOf(strA) != -1){
        text = text.replace(strA,strB);
    }
    return text;
}

IE = document.all?true:false;
var xmlhttp;

days=new Array("Ma","Di","Wo","Do","Vr","Za","Zo");
months=new Array("januari","februari","maart","april","mei","juni","juli","augustus","september","oktober","november","december");
startyear=Math.abs(params['startyear']);
endyear=Math.abs(params['endyear']);

page=replaceAll(params['page'],"(","?");
page=replaceAll(page,")","=");
page=replaceAll(page,"*","&");

//alert(page);


TS=params['ts'];		 
								 
linkpage=replaceAll(params['linkpage'],"(","?");
linkpage=replaceAll(linkpage,")","=");
linkpage=replaceAll(linkpage,"*","&");


stylesheet=params['stylesheet'];

csssrc=stylesheet.split("/");
stylesrc=csssrc[csssrc.length-1];

document.write('<div id="calendar">.</div>');
addCSS=true;
lnks=document.getElementsByTagName("link");
for(i=0; i<lnks.length; i++){
	if(lnks[i].getAttribute("href").indexOf(stylesrc)>-1){
		addCSS=false;
		break;
	}
}
if(addCSS){
	CSS=document.createElement("link");
	CSS.rel = 'stylesheet'
	CSS.type = 'text/css';
	CSS.href = stylesheet
	document.getElementsByTagName('head')[0].appendChild(CSS);
}

function in_array(needle, haystack, strict) { 
    var found = false, key, strict = !!strict; 
    for (key in haystack) {
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
            found = true;
            break;
        }
    } 
    return found;
}

function getXML(url){
	//location.href=url;
	xmlhttp=null;
	if (window.XMLHttpRequest){
  		xmlhttp=new XMLHttpRequest();
  	}
	else if (window.ActiveXObject){
 		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  	}
	if (xmlhttp!=null){
 		xmlhttp.open("GET",url,false);
   		xmlhttp.send(null);
		return(xmlhttp);
    }
	else{
   		alert("Your browser does not support XMLHTTP.");
    }
}


function doEvent(target,ev,func){
	//alert(target);	
	if(IE){
		target.attachEvent("on" + ev,func);
	}
	else{
		target.addEventListener(ev,func,false);
	}
}

function mktime() {    
    var no, ma = 0, mb = 0, i = 0, d = new Date(), argv = arguments, argc = argv.length;
    d.setHours(0,0,0); d.setDate(1); d.setMonth(1); d.setYear(1972);
 
    var dateManip = {
        0: function(tt){ return d.setHours(tt); },
        1: function(tt){ return d.setMinutes(tt); },
        2: function(tt){ set = d.setSeconds(tt); mb = d.getDate() - 1; return set; },
        3: function(tt){ set = d.setMonth(parseInt(tt)-1); ma = d.getFullYear() - 1972; return set; },
        4: function(tt){ return d.setDate(tt+mb); },
        5: function(tt){ return d.setYear(tt+ma); }
    };
    
    for( i = 0; i < argc; i++ ){
        no = parseInt(argv[i]*1);
        if (isNaN(no)) {
            return false;
        } else {
            // arg is number, let's manipulate date object
            if(!dateManip[i](no)){
                // failed
                return false;
            }
        }
    }
 
    return Math.floor(d.getTime());
}

function firstDayOfMonth(datum){
	datum=Math.abs(datum);
	if(datum>0){
		now = new Date(datum);
	}
	else{
		now = new Date();
	}
	month=now.getUTCMonth()+1;
	year=now.getFullYear();
	newdate=new Date(mktime(0,0,0,month,1,year));
	dayofweek=newdate.getUTCDay();
	return dayofweek;
}

function daysInPreviousMonth(datum){
	datum=Math.abs(datum);
	if(datum>0){
		now = new Date(datum);
	}
	else{
		now = new Date();
	}
	month=now.getUTCMonth()+1;
	year=now.getFullYear();
	if(month==1){
		pmonth=12;
		pyear=year-1;
	}
	else{
		pmonth=month-1;
		pyear=year;
	}
	if(month==12){
		nmonth=1;
		nyear=year+1;
	}
	else{
		nmonth=month+1;
		nyear=year;
	}
	if(pmonth==1 || pmonth==3 || pmonth==5 || pmonth==7 || pmonth==8 || pmonth==10 || pmonth==12){
		dipm=31;
	}
	else if(pmonth==4 || pmonth==6 || pmonth==9 || pmonth==11){
		dipm=30;
	}
	else if(pmonth==2){
		if(pyear%4==0){
			dipm=29;
		}
		else{
			dipm=28;
		}
	}
	return dipm;
}

function toPrevNextMonth(pn,datum,nu){
	tpnm=new Date(datum);
	month=tpnm.getUTCMonth()+1;
	year=tpnm.getFullYear();
	if(pn=="prev"){
		if(month==1){
			nd=mktime(0,0,0,12,3,year-1);
			startyear=Math.abs(startyear-1);
		}
		else{
			nd=mktime(0,0,0,month-1,3,year);
		}
		createCal(page + "?ts=" + nd);
	}
	else if(pn=="next"){
		if(month==12){
			nd=mktime(0,0,0,1,3,year+1);
			endyear=Math.abs(endyear+1);
		}
		else{
			nd=mktime(0,0,0,month+1,3,year);
		}
		createCal(page + "?ts=" + nd);
	}
}

function DaysInMonth(datum){
	datum=Math.abs(datum);
	if(datum>0){
		now = new Date(datum);
	}
	else{
		now = new Date();
	}
	
	month=now.getUTCMonth()+1;
	year=now.getFullYear();
	if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12){
		dim=31;
	}
	else if(month==4 || month==6 || month==9 || month==11){
		dim=30;
	}
	else if(month==2){
		if(year%4==0){
			dim=29;
		}
		else{
			dim=28;
		}
	}
	return dim;
}


function createCal(url){
	document.getElementById('calendar').innerHTML="";
	if(document.getElementById('agtab')){
		document.getElementById('calendar').removeChild(document.getElementById('agtab'));
	}
	xml=getXML(url);
	result=xml.responseXML;
	dt=result.getElementsByTagName("agendadate");
	datum=dt[0].firstChild.nodeValue;
	THISTS=datum;
	nw=result.getElementsByTagName("curdate");
	nu=nw[0].firstChild.nodeValue;
	lnkd=result.getElementsByTagName("days");
	linkdays=lnkd[0].firstChild.nodeValue;
	actives=linkdays.split(",");
	
	datum=Math.abs(datum);
	nu=Math.abs(nu);
	
	selectDate=new Date(datum);
	//alert(selectDate);
	
	sD=selectDate.getDate();
	sM=selectDate.getMonth();
	sY=selectDate.getFullYear();
	now=new Date(nu);
	thisD=now.getDate();
	thisM=now.getMonth();
	thisY=now.getFullYear();
	
	TABLE=document.createElement("table");
	TABLE.id="agtab";
	TABLE.cellpadding="0";
	TABLE.cellspacing="0";
	TBODY=document.createElement("tbody");
	TR=document.createElement("tr");
	if(IE){
		TD=document.createElement("<td colspan='7'>");
	}
	else{
		TD=document.createElement("td");
		TD.setAttribute("colspan","7");
	}
	SEL=document.createElement("select");
	SEL.style.width="71px";
	for(i=1; i<=12; i++){
		OPT=document.createElement("option");
		V=document.createTextNode(months[i-1]);
		OPT.value=i;
		if(sM+1==i){
			OPT.selected="selected";
		}
		OPT.appendChild(V);
		SEL.appendChild(OPT);
	}
	PM=document.createElement("input");
	PM.type="button";
	PM.value="-";
	
	
	SELY=document.createElement("select");
	for(y=startyear; y<=endyear; y++){
		OPTY=document.createElement("option");
		V=document.createTextNode(y);
		OPTY.appendChild(V);
		if(sY==y){
			OPTY.selected="selected";
			OPTY.value=y;
		}
			SELY.appendChild(OPTY);
	}
	MY=document.createElement("input");
	MY.type="button";
	MY.value="+";
	
	
	TD.appendChild(PM);
	TD.appendChild(SEL);
		
	TD.appendChild(SELY);
	TD.appendChild(MY);
	doEvent(SEL,"change",function(){createCal(page + "?ts=" + mktime(0,0,0,SEL.options[SEL.selectedIndex].value,3,SELY.options[SELY.selectedIndex].value)); SEL.blur(); SELY.blur();});
	doEvent(SELY,"change",function(){createCal(page + "?ts=" + mktime(0,0,0,SEL.options[SEL.selectedIndex].value,3,SELY.options[SELY.selectedIndex].value)); SEL.blur(); SELY.blur();});
	doEvent(PM,"click",function(){toPrevNextMonth("prev",datum,nu)});
	doEvent(MY,"click",function(){toPrevNextMonth("next",datum,nu)});
	TR.appendChild(TD);
	TBODY.appendChild(TR);
	TR=document.createElement("tr");
	for(i=0; i<7; i++){
		TD=document.createElement("td");
		T=document.createTextNode(days[i]);
		TD.appendChild(T);
		TD.className="days";
		TR.appendChild(TD);
	}
	TBODY.appendChild(TR);
	weeks=Math.floor(DaysInMonth(datum) / 7);
	DIM=DaysInMonth(datum);
	FDOM=firstDayOfMonth(datum);
	difM=DIM%28;
	difD=6-FDOM+1;
	if(difM==0){
		if(difD<7){
			weeks+=1;
		}
	}
	else if(difM>0){
		weeks+=1;		
		if(difM>difD){
			weeks+=1;
		}
	}
	for(i=0; i<weeks; i++){
		TR=document.createElement("tr");
		for(j=0; j<7; j++){
			TD=document.createElement("td");	
			
			D=i*7+j - FDOM+1;		
			if(D<1){
				classname="inactive";
				D=daysInPreviousMonth(datum) + D;
				T=document.createTextNode(D);
			}
			else if(D>DIM){
				classname="inactive";
				D=D-DIM;
				T=document.createTextNode(D);
			}
			else{
				classname="active";	
				if(in_array(D,actives)){
					T=document.createElement("a");
					T.setAttribute("href",linkpage + sY + "-" + (sM+1) + "-" + D + "&ts=" + THISTS);
					TT=document.createTextNode(D);
					T.appendChild(TT);
				}
				else{
					T=document.createTextNode(D);
				}
			}
			TD.appendChild(T);
			TD.className=classname;
			
			if(D == thisD && sM==thisM && sY==thisY){
				TD.className+=" today";
			}
			TR.appendChild(TD);
		}
		TBODY.appendChild(TR);
	}
	TR=document.createElement("tr");
	if(IE){
		TD=document.createElement("<td colspan='7'>");
	}
	else{
		TD=document.createElement("td");
		TD.setAttribute("colspan",7);
	}
	A=document.createElement("a");
	A.setAttribute("href",linkpage + "M:" + Math.abs(sM+1) + "-" + "Y:" + sY + "&ts=" + THISTS);
	T=document.createTextNode("Bekijk agenda " + months[Math.abs(sM)]);
	A.appendChild(T);
	TD.appendChild(A);
	TR.appendChild(TD);
	TBODY.appendChild(TR);
	TABLE.appendChild(TBODY);
	document.getElementById('calendar').appendChild(TABLE);
}
createCal(page + "?ts=" + TS);