function seteditoptions(){
	var a = $(".editfield");
	for (i=0; i<a.length; i++){ 
		var eid = a[i].id;
		if(eid !== ''){
			var cheid = "#"+eid;
			$(cheid).click(function() {
			  openaction(this);
			});
		}
	}
}

function openaction(item){
	if(strpos(item.id,'artikel','0') == '0'){
		article(item.id);
	}
	return false;	
}

var oldhtml = "";
var activearticle = "-1";
var articleid = "";
var close = false;
function article(id){
	if(close == false){
		if(id == activearticle){
			return false;
		}
		if(activearticle != '-1'){
			if(confirm('Eventuele wijzigingen worden niet opgeslagen. Weet u zeker dat u de wijzigingen niet wilt opslaan?') == false){
				return false;
			}
			$('#'+activearticle).html(oldhtml);
			activearticle = "-1";
			oldhtml = "";
		}
		
		oldhtml = $('#'+id).html();
		activearticle = id;
		
		articleid = id.replace('artikel','');
		var titel = $('#title'+articleid).html();
		var txt = $('#txt'+articleid).html();
		
		var newhtml = "<div class=\"editorplacement\"><form id=\"articleform\" action=\"/xml/maintenance/mypage/article/"+articleid+"\" method=\"post\" onsubmit=\"return savearticle('"+articleid+"'); return false;\">";
				newhtml += '<label for="title">Titel</label><input type="text" name=\"titel\" id="titel" value="'+titel+'" maxlength="50">';
				newhtml += "<label for=\"txt\">Tekst</label><textarea id=\"txt\" name=\"txt\" class=\"tinymce\">"+txt+"</textarea>";
				newhtml += "<input class=\"submit\" type=\"submit\" value=\"opslaan\"> <input class=\"submit\" type=\"button\" value=\"verwijderen\" onclick=\"removearticle('"+articleid+"');return false;\"> <input class=\"submit\" type=\"button\" value=\"sluiten\" onclick=\"closeedit('article');return false;\">";	
			newhtml += "</form></div>";
		
		$('#'+id).html(newhtml);
		loadeditor('textarea.tinymce','520px');
	}
	close = false;
}

function savearticle(articleid){
	makePostRequest('/xml/maintenance/mypage/article/'+articleid, $("#articleform").serialize(),'articlechange');	
	return false;
}

function newarticle(pageid){
	makeGetRequest('/xml/maintenance/mypage/article/new/'+pageid, '','newarticle');	
}

function articlesort(pageid){
	makeGetRequest('/xml/maintenance/mypage/article/sort/'+pageid, '','sortarticle');	
}

function removearticle(articleid){
	makeGetRequest('/xml/maintenance/mypage/article/remove/'+articleid, '','removearticle');	
}


function html_entity_decode(string, quote_style) {
    var hash_map = {},
        symbol = '',
        tmp_str = '',
        entity = '';    tmp_str = string.toString();
 
    if (false === (hash_map = get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    } 

    delete(hash_map['&']);
    hash_map['&'] = '&amp;'; 
    for (symbol in hash_map) {
        entity = hash_map[symbol];
        tmp_str = tmp_str.split(entity).join(symbol);
    }    tmp_str = tmp_str.split('&#039;').join("'");
 
    return tmp_str;
}


function get_html_translation_table (table, quote_style) {
    var entities = {},
        hash_map = {},        decimal = 0,
        symbol = '';
    var constMappingTable = {},
        constMappingQuoteStyle = {};
    var useTable = {},        useQuoteStyle = {};
 
    // Translate arguments
    constMappingTable[0] = 'HTML_SPECIALCHARS';
    constMappingTable[1] = 'HTML_ENTITIES';    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';
 
    useTable = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';    useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';
 
    if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
        throw new Error("Table: " + useTable + ' not supported');
        // return false;    
	}
 
    entities['38'] = '&amp;';
	entities['128'] = '&euro;';
    if (useTable === 'HTML_ENTITIES') {
        entities['160'] = '&nbsp;';        entities['161'] = '&iexcl;';
        entities['162'] = '&cent;';
        entities['163'] = '&pound;';
        entities['164'] = '&curren;';
        entities['165'] = '&yen;';        entities['166'] = '&brvbar;';
        entities['167'] = '&sect;';
        entities['168'] = '&uml;';
        entities['169'] = '&copy;';
        entities['170'] = '&ordf;';        entities['171'] = '&laquo;';
        entities['172'] = '&not;';
        entities['173'] = '&shy;';
        entities['174'] = '&reg;';
        entities['175'] = '&macr;';        entities['176'] = '&deg;';
        entities['177'] = '&plusmn;';
        entities['178'] = '&sup2;';
        entities['179'] = '&sup3;';
        entities['180'] = '&acute;';        entities['181'] = '&micro;';
        entities['182'] = '&para;';
        entities['183'] = '&middot;';
        entities['184'] = '&cedil;';
        entities['185'] = '&sup1;';        entities['186'] = '&ordm;';
        entities['187'] = '&raquo;';
        entities['188'] = '&frac14;';
        entities['189'] = '&frac12;';
        entities['190'] = '&frac34;';        entities['191'] = '&iquest;';
        entities['192'] = '&Agrave;';
        entities['193'] = '&Aacute;';
        entities['194'] = '&Acirc;';
        entities['195'] = '&Atilde;';        entities['196'] = '&Auml;';
        entities['197'] = '&Aring;';
        entities['198'] = '&AElig;';
        entities['199'] = '&Ccedil;';
        entities['200'] = '&Egrave;';        entities['201'] = '&Eacute;';
        entities['202'] = '&Ecirc;';
        entities['203'] = '&Euml;';
        entities['204'] = '&Igrave;';
        entities['205'] = '&Iacute;';        entities['206'] = '&Icirc;';
        entities['207'] = '&Iuml;';
        entities['208'] = '&ETH;';
        entities['209'] = '&Ntilde;';
        entities['210'] = '&Ograve;';        entities['211'] = '&Oacute;';
        entities['212'] = '&Ocirc;';
        entities['213'] = '&Otilde;';
        entities['214'] = '&Ouml;';
        entities['215'] = '&times;';        entities['216'] = '&Oslash;';
        entities['217'] = '&Ugrave;';
        entities['218'] = '&Uacute;';
        entities['219'] = '&Ucirc;';
        entities['220'] = '&Uuml;';        entities['221'] = '&Yacute;';
        entities['222'] = '&THORN;';
        entities['223'] = '&szlig;';
        entities['224'] = '&agrave;';
        entities['225'] = '&aacute;';        entities['226'] = '&acirc;';
        entities['227'] = '&atilde;';
        entities['228'] = '&auml;';
        entities['229'] = '&aring;';
        entities['230'] = '&aelig;';        entities['231'] = '&ccedil;';
        entities['232'] = '&egrave;';
        entities['233'] = '&eacute;';
        entities['234'] = '&ecirc;';
        entities['235'] = '&euml;';        entities['236'] = '&igrave;';
        entities['237'] = '&iacute;';
        entities['238'] = '&icirc;';
        entities['239'] = '&iuml;';
        entities['240'] = '&eth;';        entities['241'] = '&ntilde;';
        entities['242'] = '&ograve;';
        entities['243'] = '&oacute;';
        entities['244'] = '&ocirc;';
        entities['245'] = '&otilde;';        entities['246'] = '&ouml;';
        entities['247'] = '&divide;';
        entities['248'] = '&oslash;';
        entities['249'] = '&ugrave;';
        entities['250'] = '&uacute;';        entities['251'] = '&ucirc;';
        entities['252'] = '&uuml;';
        entities['253'] = '&yacute;';
        entities['254'] = '&thorn;';
        entities['255'] = '&yuml;';    
	}
 
    if (useQuoteStyle !== 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
	
	if (useQuoteStyle === 'ENT_QUOTES') {
        entities['39'] = '&#39;';
    }
    entities['60'] = '&lt;';
    entities['62'] = '&gt;'; 
 
    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal);        hash_map[symbol] = entities[decimal];
    }
 
    return hash_map;
}


function handlerarticlechange(xmldata){
	$(xmldata).find("maintenance").each(function(){
		var code = $(this).find("code").text();
		if(code == '200'){
			var title = $(this).find("title").text();
			var content = $(this).find("content").text();
				
				$('#artikel'+articleid).html(oldhtml);
				$('#h1'+articleid).html(title);
				$('#title'+articleid).html($('#h1'+articleid).html());
				$('#txt'+articleid).html(html_entity_decode(content));
				
				
				
			
			oldhtml = "";
			activearticle = "-1";
			articleid = "";
			
			initcufon();
			
		}
	});
}


function handlersortarticle(xmldata){
	
	var html = "";
	var c = 0;
	var paginaid = "-1";
	$(xmldata).find("articles").find("entry").each(function(){
		var title = $(this).find("title").text();
		var contentid = $(this).find("content_id").text();
		var sortorder = $(this).find("sortorder").text();
		paginaid = $(this).find("page_id").text();
		html += "<div contentid=\""+contentid+"\">"+title+"</div>";
				
		c++;
	});
	
	if(c == 0){
		alert('Om de volgorde te kunnen wijzigen dient u 2 of meer artikelen op 1 pagina te hebben');
	}
	else{
	
		html = "<div class=\"uitleg\">Om de volgorde te wijzigen sleept u het item van de huidige naar de gewenste positie. Klik op 'opslaan' om de gewenste volgorde vast te leggen.</div><br/><div id=\"sortarticles\" class=\"sortarticles\">"+html+"</div><div style=\"margin-top:10px;text-align:right;\"><input type=\"button\" class=\"button\" style=\"width:100px;\" value=\"opslaan\" onclick=\"changesortarticle('"+paginaid+"');\" /></div>";
		callbackinfowindow = "callbacksortarticle";
		infowindow('Volgorde wijzigen',html);
	}
}

function changesortarticle(p){
	var v = "";
	$('#sortarticles').find('div').each(function(){
		var c =  $(this).attr('contentid');
		if(v != ''){
			v += ";";
		}
		v += c;		
	});
	
	makeGetRequest('/xml/maintenance/mypage/article/sort/'+p+'/change/', v,'pagereload');
	
}


function callbacksortarticle(){
	$("#sortarticles").draganddropsort({"appendlastline": false});
}


function handlernewarticle(xmldata){
	location.reload();
}

function handlerremovearticle(xmldata){
	location.reload();
}


function editaddress(company){
	window.location = "/portal/"+company+"/address";
}

function editagenda(company){
	window.location = "/portal/"+company+"/agenda";
}


function changeaddress(){
	makePostRequest('/xml/maintenance/mypage/address', $("#addressform").serialize(),'');
	return false;
}

var oldactitem = "";
var openact = "-1";
function editactivity(activity){

	if(openact == activity){
		return false;
	}
		
	if(openact != "-1"){
		var item = '#activity'+openact;
		
		$(item).slideUp('fast',function(){
			var colm = $('.infocontent').height();
			colm = colm-400;
			$('.infocontent').css('height',colm);		
		
			$(item).html(oldactitem);
			$(item).slideDown('slow');			
			openact = "-1";
			editactivity(activity);
		});
		
		return false;

	}


	var item = '#activity'+activity;
	var activityurl = "/xml/maintenance/mypage/activities/"+activity;
	
	$(item).slideUp('fast',function(){
		oldactitem = $(item).html();
		openact = activity;
		timestamp = Number(new Date());
		var aurl = activityurl+"?ts="+timestamp;
		$.ajax({
		  url: aurl,
		  success: function(data) { 
				
			var newhtml = "<form id=\"activityform\" action=\""+activityurl+"\" method=\"post\" onsubmit=\"return saveactivity('"+activityurl+"');\">";
				$(data).find("activity").each(function(){
					var start = $(this).find("date_start").text();
					var end = $(this).find("date_end").text();
					var title = $(this).find("title").text();
					var intro = $(this).find("intro").text();
					var text = $(this).find("text").text();
					
					var startdag = "";
					var i=1;
					while (i<=31){
						if(i == $(this).find("startdag").text()){
							startdag += "<option value=\""+i+"\" selected>"+i+"</option>";
						}
						else{
						startdag += "<option value=\""+i+"\">"+i+"</option>";
						}
						i++;
					}
					
					var startmaand = "";
					var i=1;
					while (i<=12){
						if(i == $(this).find("startmaand").text()){
							startmaand += "<option value=\""+i+"\" selected>"+i+"</option>";
						}
						else{
							startmaand += "<option value=\""+i+"\">"+i+"</option>";
						}
						i++;
					}		

					var startjaar = "";
					var i=2010;
					while (i<=2020){
						if(i == $(this).find("startjaar").text()){
							startjaar += "<option value=\""+i+"\" selected>"+i+"</option>";
						}
						else{
							startjaar += "<option value=\""+i+"\">"+i+"</option>";
						}
						i++;
					}
					
					var startuur = "";
					var i=0;
					while (i<=23){
						var bi = i;
						if(i<=9){
							bi = "0"+i;
						}					
					
						if(bi == $(this).find("startuur").text()){
							startuur += "<option value=\""+bi+"\" selected>"+bi+"</option>";
						}
						else{
							startuur += "<option value=\""+bi+"\">"+bi+"</option>";
						}
						i++;
					}					
					
					var startmin = "";
					var i=0;
					while (i<=59){
						var bi = i;
						if(i<=9){
							bi = "0"+i;
						}
					
						if(bi == $(this).find("startmin").text()){
							startmin += "<option value=\""+bi+"\" selected>"+bi+"</option>";
						}
						else{
							startmin += "<option value=\""+bi+"\">"+bi+"</option>";
						}
						i++;
					}					
					
					
					
					var einddag = "";
					var i=1;
					while (i<=31){
						if(i == $(this).find("einddag").text()){
							einddag += "<option value=\""+i+"\" selected>"+i+"</option>";
						}
						else{
							einddag += "<option value=\""+i+"\">"+i+"</option>";
						}
						i++;
					}
					
					var eindmaand = "";
					var i=1;
					while (i<=12){
						if(i == $(this).find("eindmaand").text()){
							eindmaand += "<option value=\""+i+"\" selected>"+i+"</option>";
						}
						else{
							eindmaand += "<option value=\""+i+"\">"+i+"</option>";
						}
						i++;
					}		

					var eindjaar = "";
					var i=2010;
					while (i<=2020){
						if(i == $(this).find("eindjaar").text()){
							eindjaar += "<option value=\""+i+"\" selected>"+i+"</option>";
						}
						else{
							eindjaar += "<option value=\""+i+"\">"+i+"</option>";
						}
						i++;
					}					
					
					var einduur = "";
					var i=0;
					while (i<=23){
						var bi = i;
						if(i<=9){
							bi = "0"+i;
						}					
					
						if(bi == $(this).find("einduur").text()){
							einduur += "<option value=\""+bi+"\" selected>"+bi+"</option>";
						}
						else{
							einduur += "<option value=\""+bi+"\">"+bi+"</option>";
						}
						i++;
					}					
					
					var eindmin = "";
					var i=0;
					while (i<=59){
						var bi = i;
						if(i<=9){
							bi = "0"+i;
						}
					
						if(bi == $(this).find("eindmin").text()){
							eindmin += "<option value=\""+bi+"\" selected>"+bi+"</option>";
						}
						else{
							eindmin += "<option value=\""+bi+"\">"+bi+"</option>";
						}
						i++;
					}						
					
					newhtml += "<label for=\"begin\">Startdatum</label>";
					newhtml += "Datum: <select id=\"startdag\" name=\"startdag\">"+startdag+"</select> ";
					newhtml += "<select id=\"startmaand\" name=\"startmaand\">"+startmaand+"</select> ";
					newhtml += "<select id=\"startjaar\" name=\"startjaar\">"+startjaar+"</select>";
					newhtml += " Tijd: <select id=\"startuur\" name=\"startuur\">"+startuur+"</select> ";
					newhtml += "<select id=\"startmin\" name=\"startmin\">"+startmin+"</select>";
					
					newhtml += "<label for=\"end\">Einddatum</label>";
					newhtml += "Datum: <select id=\"einddag\" name=\"einddag\">"+einddag+"</select> ";
					newhtml += "<select id=\"eindmaand\" name=\"eindmaand\">"+eindmaand+"</select> ";
					newhtml += "<select id=\"eindjaar\" name=\"eindjaar\">"+eindjaar+"</select>";	
					newhtml += " Tijd: <select id=\"einduur\" name=\"einduur\">"+einduur+"</select> ";
					newhtml += "<select id=\"eindmin\" name=\"eindmin\">"+eindmin+"</select>";					
					
					newhtml += "<label for=\"title\">Titel</label><input type=\"text\" id=\"title\" name=\"title\" value=\""+title+"\" /><div class=\"tooltip\" id=\"ltip1\"><img src=\"/i/tooltip.gif\" alt=\"Geef hier de titel van de aanbieding op\" id=\"tip1\" onmouseover=\"showtooltip(this);\" onmouseout=\"hidetooltip(this);\" /></div>";
					newhtml += "<label for=\"title\">Intro</label><input type=\"text\" id=\"intro\" name=\"intro\" value=\""+intro+"\" maxlength=\"100\"/><div class=\"tooltip\" id=\"ltip2\"><img src=\"/i/tooltip.gif\" alt=\"Geef hier de aanbieding kort en krachtig weer, maximale 100 karakters\" id=\"tip2\" onmouseover=\"showtooltip(this);\" onmouseout=\"hidetooltip(this);\" /></div>";
					newhtml += "<label for=\"title\">Tekst</label><textarea id=\"text\" name=\"text\" class=\"tinymce\">"+text+"</textarea><div class=\"tooltip\" id=\"ltip3\"><img src=\"/i/tooltip.gif\" alt=\"Geef een volledige beschrijving van de aanbieding\" id=\"tip3\" onmouseover=\"showtooltip(this);\" onmouseout=\"hidetooltip(this);\" /></div>";
					
				});
						
			
				newhtml += "<br/><input style=\"width:100px;\" class=\"button\" type=\"submit\" value=\"opslaan\"> <input style=\"width:100px;\" class=\"button\" type=\"button\" value=\"verwijderen\" onclick=\"delactivity('"+activity+"');\"> <br/><br/>";	
			newhtml += "</form>";				
			
			$(item).html(newhtml);
			loadeditor('textarea.tinymce','470px');
			$(item).slideDown('slow');
			
			var colm = $('.infocontent').height();
			colm = colm+400;
			$('.infocontent').css('height',colm);
			
		  },
		  dataType: 'xml'
		});		
		
	});
	
	
}

function showtooltip(e){
	var d = "#l"+e.id;
	$(d).append("<div id=\"toontip\" class=\"toontip\">"+e.alt+"</div>") 
}

function hidetooltip(e){
	$('#toontip').remove();
}



function saveactivity(url){
	makePostRequest(url, $("#activityform").serialize(),'activitysaved');	
	return false;
}


function activitysaved(){
	location.reload();
}


function newactivity(){
	makeGetRequest('/xml/maintenance/mypage/activities/new', '','');	
}

function delactivity(a){
	if(confirm('Weet u zeker dat u deze activiteit wilt verwijderen?') == true){
		makeGetRequest('/xml/maintenance/mypage/activities/del/'+a, '','activitysaved');
	}
	else{
		return false;
	}
}



function openactivity(act){
	if(act == 'last'){
		var last = true;
		var a = $(".activities");
		for (i=0; i<a.length; i++){ 
			var eid = a[i].id;
			if(eid != ''){
				if(last == true){
					eid = eid.replace('activity','');
					editactivity(eid);
					last = false;
				}
			}
		}		
		
	}
}



function closeedit(s,a){
	if(s == 'article'){
		if(confirm('Eventuele wijzigingen worden niet opgeslagen. Weet u zeker dat u de wijzigingen niet wilt opslaan?') == false){
			return false;
		}
		close = true;	
		$('#artikel'+articleid).html(oldhtml);
		oldhtml = "";
		articleid = "";	
		activearticle = "-1";
		initcufon();
	}
	
}

var aphoto = "-1";
function createphotomenu(photoid){
	if(photoid != aphoto){
		if(aphoto != '-1'){
			delphotomenu(photoid);
			aphoto = "-1";
			createphotomenu(photoid);
			return false;
		}
		
		var p = "#ph"+photoid;
		var left = $(p).position().left;
		var top = $(p).position().top;
		
		var holder = "#holder"+photoid;
		var menu = "<div id=\"menu"+photoid+"\" class=\"photomenu\"><img width=\"20\" src=\"/images/remove.jpg\"></div>";
		var html = $(holder).html();
		$(holder).html(html+menu);
		aphoto = photoid;
	}
}

function delphotomenu(photoid){
	$('#menu'+photoid).remove(); 
	aphoto = "-1";
}

function delphoto(photoid){
	if(confirm('Weet u zeker dat u deze foto wilt verwijderen?')){
		makeGetRequest('/xml/maintenance/mypage/photos/del/'+photoid, '','');	
	}
}


function newphotobook(){
	var html = "<form id=\"photoform\" action=\"/xml/maintenance/mypage/photos/new\" method=\"post\" onsubmit=\"return savephotobook('/xml/maintenance/mypage/photos/new');\">";
			html += "<label for=\"naam\">Naam fotoboek</label>";
			html += "<input type=\"text\" id=\"naam\" name=\"naam\">";	
			html += "<label for=\"omschrijving\">Omschrijving fotoboek</label>";
			html += "<textarea id=\"omschrijving\" name=\"omschrijving\"></textarea>";	
			html += "<input type=\"submit\" class=\"button\" value=\"opslaan\">";	
		html += "</form>";
	infowindow('nieuw fotoboek aanmaken',html);
}

function editphotobook(p){

	//ophalen
	timestamp = Number(new Date());
	var aurl = "/xml/maintenance/mypage/photos/photobook/"+p+"?ts="+timestamp;
	$.ajax({
	  url: aurl,
	  success: function(data) { 

		$(data).find("fotoboek").each(function(){
			var title = $(this).find("title").text();
			var desc = $(this).find("description").text();

			var html = "<form id=\"photoform\" action=\"/xml/maintenance/mypage/photos/photobook/"+p+"/\" method=\"post\" onsubmit=\"return savephotobook('/xml/maintenance/mypage/photos/photobook/"+p+"/');\">";
					html += "<label for=\"naam\">Naam fotoboek</label>";
					html += "<input type=\"text\" id=\"naam\" name=\"naam\" value=\""+title+"\">";	
					html += "<label for=\"omschrijving\">Omschrijving fotoboek</label>";
					html += "<textarea id=\"omschrijving\" name=\"omschrijving\">"+desc+"</textarea>";
					html += "<input type=\"submit\" class=\"button\" value=\"opslaan\">";	
				html += "</form>";
				
			infowindow('wijzig fotoboek: '+title,html);
		});	
		
	  },
	  dataType: 'xml'
	});		

}
var swfu;
function uploadphoto(p){

	var html = "Klik op de knop uploaden om een bestand te plaatsen, het uploaden wordt dan automatisch gestart<br/><br/>";
	html += "<form id=\"form1\" action=\"index.php\" method=\"post\" enctype=\"multipart/form-data\">";
		html += "<div id=\"divSWFUploadUI\">";
			html += "<div class=\"fieldset flash\" id=\"fsUploadProgress\">";
			html += "<span class=\"legend\"></span>";
			html += "</div>";
				html += "<span id=\"spanButtonPlaceholder\"></span>";
				//html += "<input id=\"btnUpload\" type=\"button\" value=\"Select Files\" style=\"width: 61px; height: 22px; font-size: 8pt;\" />";
				html += "<input id=\"btnCancel\" type=\"button\" value=\"stoppen\" disabled=\"disabled\" style=\"display:none;margin-left: 2px; height: 22px; font-size: 8pt;\" />";
		html += "</div>";
		html += "<noscript>";
			html += "Het upload component kon niet worden geladen, javascript is niet ingeschakeld";
		html += "</noscript>";
		html += "<div id=\"divLoadingContent\" style=\"display:none;\">";
			html += "Een ogenblik geduld a.u.b.";
		html += "</div>";
		html += "<div id=\"divLongLoading\" style=\"display:none;\">";
			html += "Het upload component kon niet worden geladen, neem contact op met de helpdesk";
		html += "</div>";
		html += "<div id=\"divAlternateContent\" style=\"display:none;\">";
			html += "Het upload component kon niet worden geladen, er is geen Flash aanwezig. Neem contact op met de helpdesk";
		html += "</div>";	
	html += "</form>";
	html += "";
	
	infowindow('upload foto\'s',html);
	uploadvars = "?fotoboek="+p;
	phoid = p;
	setTimeout ("placeupload()", 500);
	return false;
}

var uploadvars = "";
function placeupload(){
	if(infowindowstatus == 1){
		var settings = {
			flash_url : "/portal/Flash/swfupload.swf",
			file_post_name: "Filedata",
			post_params: {"PHPSESSID": phpsesid},
			upload_url: "/portal/upload.php"+uploadvars,
			file_size_limit : "100 MB",
			file_types : "*.jpg;*.gif;*.png",
			file_types_description : "Afbeeldingen",
			file_upload_limit : 100,
			file_queue_limit : 0,
			custom_settings : {
				progressTarget : "fsUploadProgress",
				cancelButtonId : "btnCancel"
			},
			debug:	false,

			button_image_url: "/images/upload.png",
			button_placeholder_id : "spanButtonPlaceholder",
			button_width: 60,
			button_height: 30,
			button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
			button_cursor: SWFUpload.CURSOR.HAND,

			swfupload_loaded_handler : swfUploadLoaded,
			file_queued_handler : fileQueued,
			file_queue_error_handler : fileQueueError,
			file_dialog_complete_handler : fileDialogComplete,
			upload_start_handler : uploadStart,
			upload_progress_handler : uploadProgress,
			upload_error_handler : uploadError,
			upload_success_handler : uploadSuccess,
			upload_complete_handler : uploadComplete,
			queue_complete_handler : photobookqueueComplete,
						
			minimum_flash_version : "9.0.28",
			swfupload_pre_load_handler : swfUploadPreLoad,
			swfupload_load_failed_handler : swfUploadLoadFailed
		};
		swfu = new SWFUpload(settings);
	}
	else{
		setTimeout ("placeupload()", 500);
	}
	
}

var phoid = "-1";
function photobookqueueComplete(){
	if(phoid != '-1'){
		makeGetRequest('/xml/maintenance/mypage/photos/photobook/'+phoid, '','');
	}
	location.reload();
}


function delphotobook(p){
	if(confirm('Weet u zeker dat u dit fotoboek wilt verwijderen?') == true){
		makeGetRequest('/xml/maintenance/mypage/photos/photobook/del/'+p, '','');
	}
	return false;
}

function savephotobook(url){
	makePostRequest(url, $("#photoform").serialize(),'');	
	return false;
}

function delguestbookentry(guestbookid){
	if(confirm('Weet u zeker dat u dit gastenboekbericht definitief wilt verwijderen?') == true){
		makeGetRequest('/xml/maintenance/mypage/guestbook/del/', guestbookid, 'removeguestbookentry');
	}
}

function removeguestbookentry(xmldata){
	$(xmldata).find("maintenance").each(function(){
		var gbentryid = $(this).find("gbentryid").text();
		var e = "#gb"+gbentryid;
		$(e).slideUp('slow', function(){
			$(e).remove();	
		});
	});
}



window.onload=function() {
	document.onkeyup = key_event;
}

function key_event(e) {
	if (!e) e = window.event;

	if (e.keyCode == 27){
		if(infowindowstatus === 1){ //alleen als scherm open is hé
			closeinfowindow();
		}
	}
}

var infowindowstatus = 0;
var infowindowanimation = true;
var callbackinfowindow = false;
function infowindow(title, html){
	var w = $(document).width(); 
	var h = $(document).height(); 
	var window = "<div id=\"infowindow\" class=\"infowindow\"><div id=\"contentwindow\" class=\"content\"><div id=\"closebtn\" class=\"close\"><img src=\"/images/close.png\"></div><div class=\"title\">"+title+"</div><div id=\"iddyndiv\" class=\"padding\">"+html+"</div></div></div>";
		
		$('body').prepend(window);
		$('#infowindow').width(w);
		$('#infowindow').height(h);

		if(infowindowanimation === false){
			$('#infowindow').css('display','block');
			$('html, body').animate({scrollTop:0}, 'fast', function(){
				var wc = $('#contentwindow').width();
				var hc = $('#contentwindow').height();	
				var marginwidth = w-wc;
				marginwidth =  marginwidth/2;
				var marginheight = h-hc;	
				marginheight = 200;
				$('#contentwindow').css('marginLeft',marginwidth);
				$('#contentwindow').css('marginTop',marginheight);
				$('#contentwindow').css('display','block');
				
				infowindowstatus = 1;				
				$('#closebtn').click(function() {
				  closeinfowindow();
				});	

				//callback actie na openen window
				if(callbackinfowindow !== false){
					eval(callbackinfowindow+"();");
				}
				callbackinfowindow = false;				
			
			});		
			
		}
		else{
			$('#infowindow').slideDown('slow',function(){
				$('html, body').animate({scrollTop:0}, 'fast', function(){
					var wc = $('#contentwindow').width();
					var hc = $('#contentwindow').height();	
					var marginwidth = w-wc;
						marginwidth =  marginwidth/2;
					var marginheight = h-hc;	
						marginheight = 200;
					$('#contentwindow').css('marginLeft',marginwidth);
					$('#contentwindow').css('marginTop',marginheight);
					$('#contentwindow').fadeIn('slow',function(){
						infowindowstatus = 1;				
						$('#closebtn').click(function() {
						  closeinfowindow();
						});						
					
						//callback actie na openen window		
						if(callbackinfowindow !== false){
							eval(callbackinfowindow+"();");
						}
						callbackinfowindow = false;
						
					});
				});
			});
		}
}


function closeinfowindow(){
	if(infowindowanimation === false){
		$('#infowindow').remove();
		infowindowstatus = 0;
		
		if(setfocus != '-1'){
			$(setfocus).focus();
			setfocus = "-1";
		}	
	
	}
	else{
		$('#contentwindow').slideUp('fast',function(){
			$('#infowindow').slideUp('fast',function(){
				$('#contentwindow').remove();
				infowindowstatus = 0;
				
				if(setfocus != '-1'){
					$(setfocus).focus();
					setfocus = "-1";
				}
				
			});	
		});
	}
}


function strpos (haystack, needle, offset) {
    var i = (haystack+'').indexOf(needle, (offset || 0));
    return i === -1 ? false : i;
}

function strip_tags (input, allowed) {
	 allowed = (((allowed || "") + "")
		  .toLowerCase()
		  .match(/<[a-z][a-z0-9]*>/g) || [])
		  .join('');          
		  var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
		   commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
	   return input.replace(commentsAndPhpTags, '').replace(tags, function($0, $1){
		  return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
	   });     
}


function loadeditor(lid,editorwidth){

	$(lid).tinymce({
		// Location of TinyMCE script
		script_url : '/portal/js/tiny_mce/tiny_mce.js',
		width : editorwidth,

		// General options
		language : "nl",
		theme : "advanced",
		plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist",

		// Theme options
		theme_advanced_buttons1 : "cut,copy,pastetext,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull",
		//theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,bullist,numlist,|,undo,redo,|,link,unlink,image,|,forecolor,backcolor",
		theme_advanced_buttons2 : "bullist,numlist,|,undo,redo,|,link,unlink,image,|,forecolor,backcolor",
		theme_advanced_buttons3	: "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "none",
		theme_advanced_resizing : false,		
		content_css : "/css/portal.css",
		external_image_list_url : "/portal/lib/imagelist.user.php"
	});
}



function enableinputs(fid){
	var fe = document.getElementById(fid).elements;
	
	for(var i = 0; i < fe.length; i++){
		var f = fe[i].id+"";
		if(document.getElementById(f).disabled == false){
			document.getElementById(f).disabled = true;
		}
		else{
			document.getElementById(f).disabled = false;
		}
	}
	
}


function saveform(formid){
	var formaction = $("#"+formid).attr("action");
	makePostRequest(formaction, $("#"+formid).serialize(),'');
}

var cachexmldatasearch = "";
var cachew = "";
var caches = "";

function usersearch(w, s, xmldata){
	if(s == '1'){ // doe de request
		cachew = w;
		caches = s;
		makeGetRequest('/maintenance/dashboardsearch/', w, 'usersearch');
	}
	else{ //processing

		var showroles = new Array();
		var $inputs = $('#rolefilter :input'); 
		var values = {};
			$inputs.each(function() {
				if(this.checked == true){
					showroles.push($(this).val());
				}
			}); 
			
			if(showroles.length == 0){
				var returnhtml = "<strong>U heeft geen rollen geselecteerd, hierdoor kunnen er geen gebruikers getoond worden</strong><br/>";
			}
			else{
				cachexmldatasearch = xmldata;
			
				var emptie = "";
				var returnhtml = "";
				$(xmldata).find('entry').each(function(){
					var ui = $(this).find("user_id").text();
					var u = $(this).find("username").text();
					var s = $(this).find("status").text();
					var r = $(this).find("role").text();
					
					
					if(jQuery.inArray(r, showroles) == '-1'){
					}
					else{
						var role_name = "bezoeker";
						var role_cms = "0";
						var role_portal = "0";
						var role_ticketing = "0";
						var role_intranet = "0";
						var role_shop = "0";
						
						if(r != '-1'){
							role_name = $(this).find("role_name").text();
							role_cms = $(this).find("cms").text();
							role_portal = $(this).find("portal").text();
							role_ticketing = $(this).find("ticketing").text();
							role_intranet = $(this).find("intranet").text();
							role_shop = $(this).find("shop").text();
						}

						returnhtml = returnhtml+"<tr><td>"+u+"</td><td>"+role_name+"</td><td><img src=\"/i/status_"+role_cms+".png\" alt=\"\"/></td><td><img src=\"/i/status_"+role_portal+".png\" alt=\"\"/></td><td><img src=\"/i/status_"+role_ticketing+".png\" alt=\"\"/></td><td><img src=\"/i/status_"+role_intranet+".png\" alt=\"\"/></td><td><img src=\"/i/status_"+role_shop+".png\" alt=\"\"/></td><td><div class=\"dashboardbutton\"><a href=\"\" onclick=\"edituser('"+ui+"','0','');return false;\">wijzig</a></div></td></tr>";
						emptie = "1";
					}
				});
				
				if(emptie == ''){
					returnhtml = "Kon gebruikers vinden, die voldoen aan de opdracht";
				}
				else{
					returnhtml = "<table width=\"100%\" cellpadding=\"4\" cellspacing=\"0\" border=\"0\" class=\"t\"><tr><th>gebruikersnaam</th><th>rol</th><th>cms</th><th>portal</th><th>ticket</th><th>intranet</th><th>shop</th><th></th></tr>"+returnhtml+"</table>";
				}
			}			
				
			returnhtml = "<table cellpadding=\"4\" cellspacing=\"0\" border=\"0\"><tr><td><div class=\"dashboardbutton\"><a href=\"#\" onclick=\"userroles('0','');\">gebruikersrollen</a></div></td><td><div class=\"dashboardbutton\"><a href=\"/maintenance/allmypages\">mypage beheer</a></div></td><td><div class=\"dashboardbutton\"><a href=\"/maintenance/events\">evenementen beheer</a></div></td><td><div class=\"dashboardbutton\"><a href=\"/maintenance/ticketing\">ticketing</a></div></td></tr></table><br/>"+returnhtml;				
			$('#dashboardsearchresults').html(returnhtml);
	}
}

function cachesearchresults(){
	usersearch('', '', cachexmldatasearch);
}


function edituser(u, r, xmldata){
	if(r == '0'){
		makeGetRequest('/xml/login/changeroleuser/', u, 'edituserrole');
	}
	else{
		var html = "";
		var uname = "-1";
		$(xmldata).find('userdata').find('entry').each(function(){
			uname = $(this).find("username").text();
			var urole = $(this).find("role").text();
			var roleid = $(this).find("user_id").text();
			
			html += "<form id=\"userupdateform\" name=\"userupdateform\"><label for=\"rol\">Gebruikersrol wijzigen:</label><select id=\"rol\" name=\"rol\" style=\"width:490px;\" onchange=\"changedituser();\">";
			html += "<option value=\"-1\">bezoeker</option>";
				$(xmldata).find('roles').find('entry').each(function(){	
					var rname = $(this).find("role_name").text();
					var rid = $(this).find("role_id").text();
					if(rid == urole){
						html += "<option value=\""+rid+"\" selected=\"selected\">"+rname+"</option>";
					}
					else{
						html += "<option value=\""+rid+"\">"+rname+"</option>";
					}
				});	
			html += "</select><input type=\"hidden\" id=\"uid\" name=\"uid\" value=\""+roleid+"\"></form><br/><br/>";
			html += "<div id=\"formstatus\" class=\"formstatus\"></div>";
			
		});
		
		infowindow('Wijzig gebruikersrol: '+uname, html);	
		$('#contentwindow').css('width','500px');
		$('#contentwindow').css('height','160px');
	}

	return false;
}

function changedituser(){
	var uf = $("#userupdateform").serialize();
	makePostRequest('/xml/login/changeroleuser/', uf,'changedituser2');
}


function changedituser2(xmldata){
	usersearch(cachew,caches,'');
	
	$('#formstatus').html('Gebruikersrol is gewijzigd');
	$('#formstatus').slideDown('slow', function() {
		$('#formstatus').delay(2000).slideUp('slow');
	});	
}


function userroles(returndata,xmldata){
	if(returndata == '0'){ //aanvraag
		makeGetRequest('/xml/login/roles/', '', 'userroles');
	}
	else if(returndata == '1'){ //request
		var html = "";
		
		var role_id = "";
		var role_name = "";
		var role_cms = "0";
		var role_portal = "0";
		var role_ticketing = "0";
		var role_intranet = "0";		
		var role_shop = "0";	
		
		html = html+"<table width=\"100%\" cellpadding=\"4\" cellspacing=\"0\" border=\"0\" class=\"changeroltbl\">";
		html = html+"<tr><th>Gebruikersrol</th><th>cms</th><th>portal</th><th>ticket</th><th>intranet</th><th>shop</th></tr>";
			$(xmldata).find('entry').each(function(){
				role_id = $(this).find("role_id").text();
				role_name = $(this).find("role_name").text();
				role_cms = $(this).find("cms").text();
				role_portal = $(this).find("portal").text();
				role_ticketing = $(this).find("ticketing").text();
				role_intranet = $(this).find("intranet").text();
				role_shop = $(this).find("shop").text();


				html = html+"<tr><td><form id=\"nameform"+role_id+"\"><input type=\"hidden\" value=\""+role_id+"\" name=\"roleid\" /><input type=\"text\" value=\""+role_name+"\" name=\"name\" onKeyup=\"changerolerightname('nameform"+role_id+"');\" onBlur=\"changerolerightname('nameform"+role_id+"');\" /></form></td>";
					html = html+"<td><a href=\"#\" onclick=\"changeroleright('"+role_id+"','cms');\"><img id=\"cms_"+role_id+"\" src=\"/i/status_"+role_cms+".png\" alt=\"\"/></a></td>";
					html = html+"<td><a href=\"#\" onclick=\"changeroleright('"+role_id+"','portal');\"><img id=\"portal_"+role_id+"\" src=\"/i/status_"+role_portal+".png\" alt=\"\"/></a></td>";
					html = html+"<td><a href=\"#\" onclick=\"changeroleright('"+role_id+"','ticketing');\"><img id=\"ticketing_"+role_id+"\" src=\"/i/status_"+role_ticketing+".png\" alt=\"\"/></a></td>";
					html = html+"<td><a href=\"#\" onclick=\"changeroleright('"+role_id+"','intranet');\"><img id=\"intranet_"+role_id+"\" src=\"/i/status_"+role_intranet+".png\" alt=\"\"/></a></td>";
					html = html+"<td><a href=\"#\" onclick=\"changeroleright('"+role_id+"','shop');\"><img id=\"shop_"+role_id+"\" src=\"/i/status_"+role_shop+".png\" alt=\"\"/></a></td>";
				html = html+"</tr>";
				
			});
		html = html+"</table>";	
		infowindow('Gebruikersrollen', html);
		$('#contentwindow').css('width','600px');
		
	}
}


function changerolerightname(formid){
	makePostRequest('/xml/login/rolename/', $("#"+formid).serialize(),'');	
	usersearch(cachew,caches,'');
	return false;
}

function changeroleright(role_id,role){
	var r = role+"_"+role_id;
	makeGetRequest('/xml/login/roles/edit/', r, 'changeroleright2');	
}

function changeroleright2(xmldata){
	$(xmldata).find('changed').each(function(){
		var s = $(this).find("nieuwestatus").text();
		var e = $(this).find("elementid").text();
		$('#'+e).attr('src','/i/status_'+s+'.png');		
	});
	usersearch(cachew,caches,'');
}

function setmodule(companyid,moduleid,status){
	var r = companyid+"/"+moduleid+"/"+status;
	makeGetRequest('/xml/maintenance/editmodules/', r, '');
}

function setcat(companyid,moduleid,status){
	var r = companyid+"/"+moduleid+"/"+status;
	makeGetRequest('/xml/maintenance/editcats/', r, '');
}

function setcompanystate(companyid, s){
	var r = companyid+"/"+s;
	makeGetRequest('/xml/maintenance/editstatus/', r, '');
}

function makeusername(v,check){
	if(v == ''){
		$('#gb').attr('value','');
		$('#gb').css('border','solid 1px #304364');
	}
	else{
		var c = v.replace(/[^a-zA-Z0-9]/g,''); 
		$('#gb').attr('value',c);
			
		if(check == true){
			setreq(c);
		}
	}
}


function setreq(c){
	makeGetRequest('/xml/maintenance/checkusername/', c, 'checkusername');
}


var checkedusername = "0";
function checkusername(xmldata){
	$('#gb').css('border','solid 1px #304364');	
	checkedusername = "0";
	$(xmldata).find('status').each(function(){
		var s = $(this).find("state").text();
		if(s == '1'){
			checkedusername = "0";
			$('#gb').css('border','solid 1px #990000'); //bestaat
		}
		else if(s == '0'){
			checkedusername = "1";
			$('#gb').css('border','solid 1px #99CC00'); //en niet
		}
	});	
}

function createmp(){
	if(checkedusername == '1'){
		makePostRequest('/xml/maintenance/newmp/', $("#newmp").serialize(),'processmp');	
	}
	else{
		alert('De opgegeven gebruikersnaam is niet uniek, wijzig de gebruikersnaam een nieuwe mypage aan te kunnen maken');
	}
	return false;
}


function processmp(xmldata){
	$(xmldata).find('mypage').each(function(){
		var s = $(this).find("id").text();		
		window.location.href("/maintenance/editcompany/"+s);
	});
}


function newmp(){
	var html = "<form id=\"newmp\" action=\"/xml/maintenance/newmp/\" method=\"post\" onsubmit=\"createmp();return false;\"><div>";
		html += "<label for=\"bn\">bedrijfsnaam</label><input type=\"text\" id=\"bn\" name=\"bedrijfsnaam\" value=\"\" onKeyup=\"makeusername(this.value,true);\" />";
		html += "<label for=\"gb\">gebruikersnaam</label><input type=\"text\" id=\"gb\" name=\"gebruikersnaam\" value=\"\" onKeyup=\"setreq(this.value);\" />";
		html += "<input type=\"submit\" class=\"button\" value=\"aanmaken\"/>";
	html += "</div></form>";
 
	infowindow('Nieuwe mypage aanmaken', html);
} 

var lastidsync = "-1";
var totaltosync = 0;
var synced = 0;

function syncmp(){
	//init

	$.ajax({
	url: '/json/sync/',
	dataType: 'json',
	success: function(jsondata) {
		totaltosync = jsondata['aantal'];

	
		var html = "<table width=\"500\" cellpadding=\"4\" cellspacing=\"0\" border=\"0\" class=\"windowoverzicht\">";
				html += "<tr><td>Totaal bedrijven</td><td>"+totaltosync+"</td></tr>";
				html += "<tr><td>Aantal gesynchroniseerd</td><td><div id=\"synced\">"+synced+"</a></td></tr>";
				html += "<tr><td>Status</td><td><div style=\"width:300px;height:12px;border:solid 1px #EEEEEE;float:left;\"><div id=\"indicator\" style=\"width:1px;height:12px;background-image:url('/i/indicator.jpg');\"></div></div><div id=\"pec\" style=\"float:left;font-size:9px;\">0%</div></td></tr>";
				html += "<tr><td>Bezig met synchroniseren</td><td><div id=\"sync\" style=\"font-style:italic;font-size:9px;\">klik op 'starten' om te synchroniseren</div></td></tr>";
			html += "</table>";
			html += "<div id=\"syncfouten\" style=\"padding:4px;display:none;\"></div>";
			html += "<div align=\"right\"><input id=\"startbtn\" onclick=\"syncprocess();\" type=\"button\" value=\"starten\" class=\"button\" style=\"margin-top:10px;width:100px;\"/>";
		infowindow('Synchroniseren', html);	
		$('#contentwindow').css('width','510px');
	
		}
	});	
}
 
function syncprocess(){
	$('#startbtn').attr('disabled','disabled');
	syncpr();
}
   
function syncpr(){
	$.ajax({
	url: '/json/sync/'+lastidsync,
	dataType: 'json',
	success: function(data) {
		jsondata = data;
			if(jsondata['returncode'] == '200'){
				var c = jsondata['company'];
				lastidsync = jsondata['lastid'];
				$('#sync').html(c);
				
				synced = synced+1;
				$('#synced').html(synced);
				
				var p = (synced/20)*100;
					p = Math.round(p*10)/10;
				var w = p*3;
				$('#indicator').width(w);
				$('#pec').html(p+"%");
				
				if(jsondata['importfoutmelding'] != '-1'){
					var html = $('#syncfouten').html();
					if(html == ""){
						html += "<strong>Foutenrapportage</strong><br>";
					}
					html += jsondata['importfoutmelding']+"<br>";
					$('#syncfouten').html(html);
					$('#syncfouten').slideDown();
				}
				setTimeout("syncpr()",100);
			}		
			else if(jsondata['returncode'] == '201'){
				
				$('#sync').html('synchronisatie afgerond');
				$('#startbtn').attr('disabled','');
				lastidsync = "-1";
				synced = 0;
			}
			else{
				$('#sync').html('synchronisatie afgebroken');
				$('#startbtn').attr('disabled','');
				lastidsync = "-1";
			}
		}
	});
		
}   
  

function exportmp(){
	var html = "<form id=\"newmp\" action=\"/xml/maintenance/exportmp/\" method=\"post\" target=\"new\">";
		html += "<strong>Ik de volgende gegevens exporteren</strong><br/>";
		html += "<table>";
			html += "<tr><td><input type=\"radio\" name=\"export\" value=\"actief\" checked=\"checked\" style=\"width:20px;border:0px;padding:0px;margin:0px;\"/></td><td>Actieve accounts</td></tr>";
			html += "<tr><td><input type=\"radio\" name=\"export\" value=\"inactief\" style=\"width:20px;border:0px;padding:0px;margin:0px;\"/></td><td>Inactive accounts</td></tr>";
			html += "<tr><td><input type=\"radio\" name=\"export\" value=\"alle\" style=\"width:20px;border:0px;padding:0px;margin:0px;\"/></td><td>Alle accounts</td></tr>";
			html += "<tr><td></td><td><input type=\"submit\" class=\"button\" value=\"exporteer\" style=\"width:100px;\"/></td></tr>";
		html += "</table>";		
		html += "</form>";
 
	$('#contentwindow').css('width','400px');
	infowindow('Export', html);	
	
} 

function openmail(msgid){
	makeGetRequest('/xml/maintenance/getmail/', msgid+'/read', 'showmail');
}

function showmail(xmldata){
	
	var subject = "";
	var msg = "";
	
	$(xmldata).find('msg').each(function(){
		var msgid = $(this).find("message_id").text();
		var from_name = $(this).find("from_name").text();
		var from_email = $(this).find("from_email").text();
		var sendto = $(this).find("sendto").text();
		subject = $(this).find("subject").text();
		var m = $(this).find("message").text();
		msg += "<div class=\"mailbuttons\"><div class=\"mailbutton\"><a href=\"#\" onclick=\"answermail('"+msgid+"');\">Beantwoorden</a></div> <div class=\"mailbutton\"><a href=\"#\" onclick=\"forwardmail('"+msgid+"');\">Doorsturen</a></div> <div class=\"mailbutton\"><a href=\"#\" onclick=\"delmsg('"+msgid+"','2')\">Verwijderen</a></div></div>";
		msg += "<div style=\"background-color:#F3F3F3;\"><table cellpadding=\"4\" cellspacing=\"0\" border=\"0\">";
			msg += "<tr><td><strong>Van:</strong></td><td>"+from_name+" ["+from_email+"]</td></tr>";
			msg += "<tr><td><strong>Aan:</strong></td><td>"+sendto+"</td></tr>";
			msg += "<tr><td><strong>Onderwerp:</strong></td><td>"+subject+"</td></tr>";
		msg += "</table></div>";
		
		
		msg += "<div style=\"border:solid 1px #F3F3F3;padding:10px;\">";
			msg += m;
		msg += "</div>";
		resetlist(msgid);	
	});
	
	infowindow("bericht: "+subject,msg);	
	$('#contentwindow').css('width','600px');
	
}

function answermail(msgid){
	makeGetRequest('/xml/maintenance/getmail/', msgid+'/read', 'answermailprocess');
}


function answermailprocess(xmldata){
	$('#contentwindow').slideUp('fast',function(){
		$('#infowindow').slideUp('fast',function(){
			$('#contentwindow').remove();
			infowindowstatus = 0;
			
			$(xmldata).find('msg').each(function(){
				var msgid = $(this).find("message_id").text();
				var from_name = $(this).find("from_name").text();
				var from_email = $(this).find("from_email").text();
				var sendto = $(this).find("sendto").text();
				var subject = $(this).find("subject").text();
				var m = $(this).find("message").text();
				
				var received = $(this).find("received").text();
				
				var opmaak = "<br/><br/>-----Oorspronkelijk bericht-----<br/>";
				opmaak += "Van: "+from_email+"<br/>";
				opmaak += "Verzonden: "+received+"<br/>";
				opmaak += "Aan: "+sendto+"<br/>";
				opmaak += "Onderwerp: "+subject+"<br/>";
				opmaak += m;
				
				opmaak = opmaak.replace(/<br\/>/g,'\n\r');
				
				var msg = "<form method=\"post\" id=\"mailform\" name=\"mailform\" action=\"/xml/maintenance/getmail/send\" onsubmit=\"return sendmail(); return false;\">";
					msg += "<div style=\"background-color:#F3F3F3;\"><table cellpadding=\"4\" cellspacing=\"0\" border=\"0\">";
						msg += "<tr><td><strong>Van:</strong></td><td>"+sendto+"<input type=\"hidden\" name=\"van\" value=\""+sendto+"\"></td></tr>";
						msg += "<tr><td><strong>Aan:</strong></td><td><input type=\"text\" name=\"aan\" value=\""+from_email+"\" /></td></tr>";
						msg += "<tr><td><strong>Onderwerp:</strong></td><td><input type=\"text\" name=\"onderwerp\" value=\"RE: "+subject+"\" /></td></tr>";
					msg += "</table></div>";
					
					
					msg += "<div style=\"border:solid 1px #F3F3F3;padding:10px;\">";
						msg += "<textarea style=\"width:568px;height:400px;\" id=\"msgmail\" name=\"mail\">"+opmaak+"</textarea>";
						msg += "<div align=\"right\"><input type=\"submit\" value=\"verzenden\" style=\"cursor: pointer; cursor: hand;\" /></div>";
					msg += "</div>";
					
				msg += "</form>";
					
				infowindow("RE: "+subject,msg);
				$('#contentwindow').css('width','600px');		
				
			});
				
			
		});	
	});
}


function sendmail(){
	makePostRequest('/xml/maintenance/getmail/send', $("#mailform").serialize(),'');	
	return false;
}

function forwardmail(msgid){
	makeGetRequest('/xml/maintenance/getmail/', msgid+'/read', 'forwardmailprocess');
}

function forwardmailprocess(xmldata){
	$('#contentwindow').slideUp('fast',function(){
		$('#infowindow').slideUp('fast',function(){
			$('#contentwindow').remove();
			infowindowstatus = 0;
			
			$(xmldata).find('msg').each(function(){
				var msgid = $(this).find("message_id").text();
				var from_name = $(this).find("from_name").text();
				var from_email = $(this).find("from_email").text();
				var sendto = $(this).find("sendto").text();
				var subject = $(this).find("subject").text();
				var m = $(this).find("message").text();
				
				var received = $(this).find("received").text();
				
				var opmaak = "<br/><br/>-----Oorspronkelijk bericht-----<br/>";
				opmaak += "Van: "+from_email+"<br/>";
				opmaak += "Verzonden: "+received+"<br/>";
				opmaak += "Aan: "+sendto+"<br/>";
				opmaak += "Onderwerp: "+subject+"<br/>";
				opmaak += m;
				
				opmaak = opmaak.replace(/<br\/>/g,'\n\r');
				
				var msg = "<form method=\"post\" id=\"mailform\" name=\"mailform\" action=\"/xml/maintenance/getmail/send\" onsubmit=\"return sendmail(); return false;\">";
					msg += "<div style=\"background-color:#F3F3F3;\"><table cellpadding=\"4\" cellspacing=\"0\" border=\"0\">";
						msg += "<tr><td><strong>Van:</strong></td><td>"+sendto+"<input type=\"hidden\" name=\"van\" value=\""+sendto+"\"></td></tr>";
						msg += "<tr><td><strong>Aan:</strong></td><td><input type=\"text\" name=\"aan\" value=\"\" /></td></tr>";
						msg += "<tr><td><strong>Onderwerp:</strong></td><td><input type=\"text\" name=\"onderwerp\" value=\"FW: "+subject+"\" /></td></tr>";
					msg += "</table></div>";
					
					
					msg += "<div style=\"border:solid 1px #F3F3F3;padding:10px;\">";
						msg += "<textarea style=\"width:568px;height:400px;\" id=\"msgmail\" name=\"mail\">"+opmaak+"</textarea>";
						msg += "<div align=\"right\"><input type=\"submit\" value=\"verzenden\" style=\"cursor: pointer; cursor: hand;\" /></div>";
					msg += "</div>";
					
				msg += "</form>";
					
				infowindow("FW: "+subject,msg);
				$('#contentwindow').css('width','600px');		
				
			});
				
			
		});	
	});
}


function delmsg(msgid,folder){
	if(folder == '2'){
		var a = confirm ("Weet u zeker dat u deze email voorgoed wilt verwijderen?");
		if (a){
		}
		else{
		 return false;
		}
	}
	makeGetRequest('/xml/maintenance/getmail/', msgid+'/delete', '');
}

function resetlist(msgid){
	var m = "mail"+msgid;
	var a = $(".nieuw");
	
	var minusone = false;
	for (i=0; i<a.length; i++){ 
		var rel = ""+a[i].rel;
		if(m == rel){
			var eid = "#"+a[i].id;
			$(eid).removeClass('nieuw');
			$(eid).removeClass('normaal');	
			minusone = true;
		}
	}
	
	
	var totaal = $('#totaalmails').html();
	if(minusone === true && totaal != '0'){
		var t = totaal-1;
		$('#totaalmails').html(t);
	}
	
}


/*EVENTS*/

function editevent(eventid){
	makeGetRequest('/xml/maintenance/events/', eventid, 'processeditevent');
}


function stripnul(input){
	if((input.length > 1) && (input.substr(0,1) == "0")){
		return input.substr(1);
	}
	else{
		return input;
	}
}

function processeditevent(xmldata){
	var html = "";
		$(xmldata).find('event').each(function(){
			var eid = $(this).find("event_id").text();
			var name = $(this).find("name").text();
			var ds = $(this).find("date_start").text();
			var de = $(this).find("date_end").text();
			var location = $(this).find("location").text();
			var city = $(this).find("city").text();
			var zipcode = $(this).find("zipcode").text();
			var desc = $(this).find("description").text();
			var website = $(this).find("website").text();
			var active = $(this).find("active").text();
			
			var ds_dt = ds.split("-");
			var de_dt = de.split("-");
 
			var hd = new Date();
			
			html +=	"<form method=\"post\" id=\"eventedit\" action=\"/xml/maintenance/events/"+eid+"/edit\" onsubmit=\"processediteventsubmit('"+eid+"');return false;\">";			
			html += "<table>";
				if(active == '1'){
					html += "<tr><td>Actief</td><td><input type=\"checkbox\" name=\"active\" style=\"width:20px;\" checked=\"checked\" /></td></tr>";
				}
				else{
					html += "<tr><td>Actief</td><td><input type=\"checkbox\" name=\"active\" style=\"width:20px;\" /></td></tr>";
				}
				html += "<tr><td valign=\"top\">Naam evenement</td><td><input type=\"text\" id=\"name\" name=\"name\" value=\""+name+"\" /></td></tr>";
				html += "<tr><td valign=\"top\">Startdatum</td><td>";
					html += "<select name=\"ds_dag\" style=\"width:70px;\">";
						var i = 1;
						while (i<=31){
							if(i == ds_dt[0]){
								html += "<option value=\""+i+"\" selected>"+i+"</option>";
							}
							else{
								html += "<option value=\""+i+"\">"+i+"</option>";
							}
						  i++;
						}							
					html += "</select>";
					html += "<select name=\"ds_maand\" style=\"width:70px;\">";
						var i = 1;
						while (i<=12){
							if(i == ds_dt[1]){
								html += "<option value=\""+i+"\" selected>"+i+"</option>";
							}
							else{
								html += "<option value=\""+i+"\">"+i+"</option>";
							}
						  i++;
						}							
					html += "</select>";
					html += "<select name=\"ds_jaar\" style=\"width:70px;\">";
						var i = hd.getFullYear();
						var bi = i+10;

						while (i<=bi){
							if(i == ds_dt[2]){
								html += "<option value=\""+i+"\" selected>"+i+"</option>";
							}
							else{
								html += "<option value=\""+i+"\">"+i+"</option>";
							}
						  i++;
						}							
					html += "</select>&nbsp;&nbsp;";
					html += "<select name=\"ds_uur\" style=\"width:70px;\">";
						var i = 0;
						while (i<=23){
							if(i == stripnul(ds_dt[3])){
								html += "<option value=\""+i+"\" selected>"+i+"</option>";
							}
							else{
								html += "<option value=\""+i+"\">"+i+"</option>";
							}
						  i++;
						}
					html += "</select>&nbsp;:&nbsp;";
					html += "<select name=\"ds_minuut\" style=\"width:70px;\">";
						var i = 0;
						while (i<=59){
							if(i == stripnul(ds_dt[4])){
								html += "<option value=\""+i+"\" selected>"+i+"</option>";
							}
							else{
								html += "<option value=\""+i+"\">"+i+"</option>";
							}
						  i++;
						}
					html += "</select>";					
				html += "</td></tr>";
				html += "<tr><td valign=\"top\">Einddatum</td><td>";
					html += "<select name=\"de_dag\" style=\"width:70px;\">";
						var i = 1;
						while (i<=31){
							if(i == de_dt[0]){
								html += "<option value=\""+i+"\" selected>"+i+"</option>";
							}
							else{
								html += "<option value=\""+i+"\">"+i+"</option>";
							}
						  i++;
						}							
					html += "</select>";
					html += "<select name=\"de_maand\" style=\"width:70px;\">";
						var i = 1;
						while (i<=12){
							if(i == de_dt[1]){
								html += "<option value=\""+i+"\" selected>"+i+"</option>";
							}
							else{
								html += "<option value=\""+i+"\">"+i+"</option>";
							}
						  i++;
						}							
					html += "</select>";
					html += "<select name=\"de_jaar\" style=\"width:70px;\">";
						var i = hd.getFullYear();
						var bi = i+10;
						while (i<=bi){
							if(i == de_dt[2]){
								html += "<option value=\""+i+"\" selected>"+i+"</option>";
							}
							else{
								html += "<option value=\""+i+"\">"+i+"</option>";
							}
						  i++;
						}
					html += "</select>&nbsp;&nbsp;";
					html += "<select name=\"de_uur\" style=\"width:70px;\">";
						var i = 0;
						while (i<=23){
							if(i == stripnul(de_dt[3])){
								html += "<option value=\""+i+"\" selected>"+i+"</option>";
							}
							else{
								html += "<option value=\""+i+"\">"+i+"</option>";
							}
						  i++;
						}
					html += "</select>&nbsp;:&nbsp;";
					html += "<select name=\"de_minuut\" style=\"width:70px;\">";
						var i = 0;
						while (i<=59){
							if(i == stripnul(de_dt[4])){
								html += "<option value=\""+i+"\" selected>"+i+"</option>";
							}
							else{
								html += "<option value=\""+i+"\">"+i+"</option>";
							}
						  i++;
						}
					html += "</select>";					
				html += "</td></tr>";
				html += "<tr><td valign=\"top\">Locatie</td><td><input type=\"text\" id=\"location\" name=\"location\" value=\""+location+"\" /></td></tr>";
				html += "<tr><td valign=\"top\">Postcode</td><td><input type=\"text\" id=\"zipcode\" name=\"zipcode\" value=\""+zipcode+"\" /></td></tr>";
				html += "<tr><td valign=\"top\">Plaatsnaam</td><td><input type=\"text\" id=\"city\" name=\"city\" value=\""+city+"\" /></td></tr>";
				html += "<tr><td valign=\"top\">Omschrijving</td><td><textarea name=\"desc\" id=\"desc\">"+desc+"</textarea></td></tr>";
				html += "<tr><td valign=\"top\">Website</td><td><input type=\"text\" id=\"website\" name=\"website\" value=\""+website+"\" /></td></tr>";
				html += "<tr><td valign=\"top\"></td><td><input type=\"submit\" value=\"wijzigen\" class=\"button\" style=\"width:100px\" /> <input type=\"button\" value=\"verwijderen\" class=\"button\" style=\"width:100px\" onclick=\"deleventitem('"+eid+"');\" /></td></tr>";
			html += "</table>";
		html += "</form>";
		});
		
	infowindow('Evenementen wijzigen',html);
	$('#contentwindow').css('width','500px');			
}

function processediteventsubmit(eid){
	makePostRequest('/xml/maintenance/events/'+eid+'/edit', $("#eventedit").serialize(),'');	
}

function newevent(){
	var html = "";
	var hd = new Date();
	
	html +=	"<form method=\"post\" id=\"eventedit\" action=\"/xml/maintenance/events/new/edit\" onsubmit=\"processediteventsubmit('new');return false;\">";			
	html += "<table>";
		html += "<tr><td>Actief</td><td><input type=\"checkbox\" name=\"active\" style=\"width:20px;\" checked=\"checked\" /></td></tr>";
		html += "<tr><td valign=\"top\">Naam evenement</td><td><input type=\"text\" id=\"name\" name=\"name\" /></td></tr>";
		html += "<tr><td valign=\"top\">Startdatum</td><td>";
			html += "<select name=\"ds_dag\">";
				var i = 1;
				while (i<=31){
					html += "<option value=\""+i+"\">"+i+"</option>";
				  i++;
				}							
			html += "</select>";
			html += "<select name=\"ds_maand\">";
				var i = 1;
				while (i<=12){
					html += "<option value=\""+i+"\">"+i+"</option>";
				  i++;
				}							
			html += "</select>";
			html += "<select name=\"ds_jaar\">";
				var i = hd.getFullYear();
				var bi = i+10;

				while (i<=bi){
					html += "<option value=\""+i+"\">"+i+"</option>";
				  i++;
				}							
			html += "</select>&nbsp;&nbsp;";
			html += "<select name=\"ds_uur\">";
				var i = 0;
				while (i<=23){
					html += "<option value=\""+i+"\">"+i+"</option>";
				  i++;
				}
			html += "</select>&nbsp;:&nbsp;";
			html += "<select name=\"ds_minuut\">";
				var i = 0;
				while (i<=59){
					html += "<option value=\""+i+"\">"+i+"</option>";
				  i++;
				}
			html += "</select>";					
		html += "</td></tr>";
		html += "<tr><td valign=\"top\">Einddatum</td><td>";
			html += "<select name=\"de_dag\">";
				var i = 1;
				while (i<=31){
					html += "<option value=\""+i+"\">"+i+"</option>";
				  i++;
				}							
			html += "</select>";
			html += "<select name=\"de_maand\">";
				var i = 1;
				while (i<=12){
					html += "<option value=\""+i+"\">"+i+"</option>";
				  i++;
				}							
			html += "</select>";
			html += "<select name=\"de_jaar\">";
				var i = hd.getFullYear();
				var bi = i+10;
				while (i<=bi){
					html += "<option value=\""+i+"\">"+i+"</option>";
				  i++;
				}
			html += "</select>&nbsp;&nbsp;";
			html += "<select name=\"de_uur\">";
				var i = 0;
				while (i<=23){
					html += "<option value=\""+i+"\">"+i+"</option>";
				  i++;
				}
			html += "</select>&nbsp;:&nbsp;";
			html += "<select name=\"de_minuut\">";
				var i = 0;
				while (i<=59){
					html += "<option value=\""+i+"\">"+i+"</option>";
				  i++;
				}
			html += "</select>";					
		html += "</td></tr>";
		html += "<tr><td valign=\"top\">Locatie</td><td><input type=\"text\" id=\"location\" name=\"location\" /></td></tr>";
		html += "<tr><td valign=\"top\">Postcode</td><td><input type=\"text\" id=\"zipcode\" name=\"zipcode\" /></td></tr>";
		html += "<tr><td valign=\"top\">Plaatsnaam</td><td><input type=\"text\" id=\"city\" name=\"city\" /></td></tr>";
		html += "<tr><td valign=\"top\">Omschrijving</td><td><textarea name=\"desc\" id=\"desc\"></textarea></td></tr>";
		html += "<tr><td valign=\"top\">Website</td><td><input type=\"text\" id=\"website\" name=\"website\" /></td></tr>";
		html += "<tr><td valign=\"top\"></td><td><input type=\"submit\" value=\"aanmaken\" class=\"button\" /></td></tr>";
	html += "</table>";
	html += "</form>";
	infowindow('Evenementen aanmaken',html);
	$('#contentwindow').css('width','500px');
}

function deleventitem(item){
	var a = confirm('Weet u zeker dat u dit evenement wilt verwijderen?');
	if(a === true){
		makeGetRequest('/xml/maintenance/events/'+item+'/del', '','');	
	}
}

var edithourid = "";
function edithours(cid){
	edithourid = cid;
	makeGetRequest('/xml/maintenance/hours/'+cid, '','edithours2');
}


function edithours2(xmldata){
	
	var html = "<div class=\"uitleg\">Geef hier de openingstijden van uw bedrijf op. Bent u een specifieke dag gesloten? Vink dan die optie aan.</div><br/><form id=\"hoursedit\" action=\"/xml/maintenance/hours/edit\" method=\"post\" onsubmit=\"hoursubmit();return false;\"><input type=\"hidden\" id=\"xcompanyid\" name=\"xcompanyid\" value=\""+edithourid+"\"/><table>";
			html += "<tr><th>Dag</td><th>Van / tot</th><th>Gesloten</th></tr>";
			html += "<tr><td>Zondag</td><td><table class=\"edithours\"><tr><td><input type=\"text\" id=\"o00\" name=\"o00\" maxlength=\"2\" /></td><td>:</td><td><input type=\"text\" id=\"o10\" name=\"o10\" maxlength=\"2\" /></td><td>-</td><td><input type=\"text\" id=\"e00\" name=\"e00\" maxlength=\"2\" /></td><td>:</td><td><input type=\"text\" id=\"e10\" name=\"e10\" maxlength=\"2\" /></td></tr></table></td><td><input type=\"checkbox\" id=\"gesloten0\" name=\"gesloten0\" style=\"width:20px;border:0px;\" />Hele dag gesloten</td></tr>";
			html += "<tr><td>Maandag</td><td><table class=\"edithours\"><tr><td><input type=\"text\" id=\"o01\" name=\"o01\" maxlength=\"2\" /></td><td>:</td><td><input type=\"text\" id=\"o11\" name=\"o11\" maxlength=\"2\" /></td><td>-</td><td><input type=\"text\" id=\"e01\" name=\"e01\" maxlength=\"2\" /></td><td>:</td><td><input type=\"text\" id=\"e11\" name=\"e11\" maxlength=\"2\" /></td></tr></table></td><td><input type=\"checkbox\" id=\"gesloten1\" name=\"gesloten1\" style=\"width:20px;border:0px;\" />Hele dag gesloten</td></tr>";
			html += "<tr><td>Dinsdag</td><td><table class=\"edithours\"><tr><td><input type=\"text\" id=\"o02\" name=\"o02\" maxlength=\"2\" /></td><td>:</td><td><input type=\"text\" id=\"o12\" name=\"o12\" maxlength=\"2\" /></td><td>-</td><td><input type=\"text\" id=\"e02\" name=\"e02\" maxlength=\"2\" /></td><td>:</td><td><input type=\"text\" id=\"e12\" name=\"e12\" maxlength=\"2\" /></td></tr></table></td><td><input type=\"checkbox\" id=\"gesloten2\" name=\"gesloten2\" style=\"width:20px;border:0px;\" />Hele dag gesloten</td></tr>";
			html += "<tr><td>Woensdag</td><td><table class=\"edithours\"><tr><td><input type=\"text\" id=\"o03\" name=\"o03\" maxlength=\"2\" /></td><td>:</td><td><input type=\"text\" id=\"o13\" name=\"o13\" maxlength=\"2\" /></td><td>-</td><td><input type=\"text\" nid=\"e03\" name=\"e03\" maxlength=\"2\" /></td><td>:</td><td><input type=\"text\" id=\"e13\" name=\"e13\" maxlength=\"2\" /></td></tr></table></td><td><input type=\"checkbox\" id=\"gesloten3\" name=\"gesloten3\" style=\"width:20px;border:0px;\" />Hele dag gesloten</td></tr>";
			html += "<tr><td>Donderdag</td><td><table class=\"edithours\"><tr><td><input type=\"text\" id=\"o04\" name=\"o04\" maxlength=\"2\" /></td><td>:</td><td><input type=\"text\" id=\"o14\" name=\"o14\" maxlength=\"2\" /></td><td>-</td><td><input type=\"text\" id=\"e04\" name=\"e04\" maxlength=\"2\" /></td><td>:</td><td><input type=\"text\" id=\"e14\" name=\"e14\" maxlength=\"2\" /></td></tr></table></td><td><input type=\"checkbox\" id=\"gesloten4\" name=\"gesloten4\" style=\"width:20px;border:0px;\" />Hele dag gesloten</td></tr>";
			html += "<tr><td>Vrijdag</td><td><table class=\"edithours\"><tr><td><input type=\"text\" id=\"o05\" name=\"o05\" maxlength=\"2\" /></td><td>:</td><td><input type=\"text\" id=\"o15\" name=\"o15\" maxlength=\"2\" /></td><td>-</td><td><input type=\"text\" id=\"e05\" name=\"e05\" maxlength=\"2\" /></td><td>:</td><td><input type=\"text\" id=\"e15\" name=\"e15\" maxlength=\"2\" /></td></tr></table></td><td><input type=\"checkbox\" id=\"gesloten5\" name=\"gesloten5\" style=\"width:20px;border:0px;\" />Hele dag gesloten</td></tr>";
			html += "<tr><td>Zaterdag</td><td><table class=\"edithours\"><tr><td><input type=\"text\" id=\"o06\" name=\"o06\" maxlength=\"2\" /></td><td>:</td><td><input type=\"text\" id=\"o16\" name=\"o16\" maxlength=\"2\" /></td><td>-</td><td><input type=\"text\" id=\"e06\" name=\"e06\" maxlength=\"2\" /></td><td>:</td><td><input type=\"text\" id=\"e16\" name=\"e16\" maxlength=\"2\" /></td></tr></table></td><td><input type=\"checkbox\" id=\"gesloten6\" name=\"gesloten6\" style=\"width:20px;border:0px;\" />Hele dag gesloten</td></tr>";
			html += "<tr><td></td><td colspan=\"2\"><input type=\"submit\" value=\"wijzigen\" class=\"button\" style=\"width:100px;\" /></td></tr>";
		html += "</table></form>";

		
	infowindow('Openingstijden wijzigen',html);
	
	$('#contentwindow').css('width','400px');	
		$(xmldata).find('entry').each(function(){
			var cid = $(this).find("company_id").text();
			var day = $(this).find("day").text();
			var from = $(this).find("time_from").text();
			var to = $(this).find("time_to").text();
			var c = $(this).find("closed").text();
			
			var f = from.split(':');	
			$('#o0'+day).attr('value',f[0]);
			$('#o1'+day).attr('value',f[1]);
			
			var t = to.split(':');	
			$('#e0'+day).attr('value',t[0]);
			$('#e1'+day).attr('value',t[1]);
			

			if(c == 1){
				$('#gesloten'+day).attr('checked','checked');
			}
			
			$('#xcompanyid').attr('value',cid);
		});	
}

function hoursubmit(){
	makePostRequest('/xml/maintenance/hours/edit', $("#hoursedit").serialize(),'');
}

function openprofileoption(box){
	if(box.checked == true) { 
		var b = box.value.split('||');
		
		if(b[0] !== 'undefined'){
			var blocked = $('#selectbox').attr('value');
			var b2 = blocked.split(';');
			if(in_array(b[0],b2,false) === true){
				var hid = box.id;
				$.each($(":input[type=checkbox]"),function(i,e){
					var v = e.value.split('||');
					if(v[0] == b[0]){
						$('#'+e.id).attr('checked',false);
					}
				});
				$('#'+hid).attr('checked',true);
			}
			
			
		}
						
	}

	
	var a = $('#optiesform').attr('action');
	makePostRequest(a, $("#optiesform").serialize(),'optieformreset');
}


function optieformreset(){

}


function in_array(needle, haystack, argStrict) {
    var key = '', strict = !! argStrict;
 
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) { 
				return true;
            }
        }
    } else {
        for (key in haystack) {
			if (haystack[key] == needle) {
                return true;
            }
        }
    } 
    return false;
}


function toggleformopties(profile_id){
	var i = "#"+profile_id;
	$(i).slideToggle("slow");
	return false;
}


/*TICKETING*/

function trainsearch(){
	makePostRequest('/xml/maintenance/ticketing/search/', $("#trainsearch").serialize(),'trainsearchprocess');
}

function trainsearchprocess(xmldata){
	var returnv = "<table class='eventstable'>";
		returnv += "<tr><th>Treinnumer</th><th>Tijd</th><th>Soort</th></tr>";
		
	var i = false;
	$('#trains').html('t');
	$(xmldata).find("ritten").find("entry").each(function(){
		var cid = $(this).find("rit_id").text();
		var treinnummer = $(this).find("treinnummer").text();
		var diner = $(this).find("dinertrein").text();
		var special = $(this).find("special").text();
		var tijd = $(this).find("vertrektijdcaption").text();
		
		
		
		var soort = "pendel";
				
		if(diner === '1'){
			soort = "dinertrein";
		}
		else if(special === '1'){
			soort = "special";
		}
		
			returnv += "<tr onclick=\"edittrainride('"+cid+"');\"><td>"+treinnummer+"</td><td>"+tijd+"</td><td>"+soort+"</td></tr>";
			
			i = true;
	});
	
	if(i === false){
		returnv += "<tr><td colspan='3'>er zijn geen treinen gevonden</td></tr>";
	}
	
	returnv += "</table>";
	
	$('#trains').html(returnv);
	
}

function newtrainride(){
	var jsondata = "";
	$.ajax({
	  url: '/json/stations',
	  dataType: 'json',
	  success: function(data) {
		jsondata = data;
		if(jsondata['returncode'] == '200'){
			
			var stations = "";
			for(var key in jsondata['stations']) {
				stations = stations+"<option value=\""+key+"\">"+jsondata['stations'][key]+"</option>";
			} 	
			
			var i=0;
			var uren = "";
			while (i<=23){
				var voorloop = "";
				if(i<10){
					voorloop = "0";
				}
				uren = uren+"<option value=\""+i+"\">"+voorloop+""+i+"</option>";
				i++;
			}

			
			var i=0;
			var min = "";
			while (i<=59){
				var voorloop = "";
				if(i<10){
					voorloop = "0";
				}		
				min = min+"<option value=\""+i+"\">"+voorloop+""+i+"</option>";
				i++;
			}
			
			
			var i=1;
			var dag = "";
			while (i<=31){
				var voorloop = "";
				if(i<10){
					voorloop = "0";
				}		
				dag = dag+"<option value=\""+i+"\">"+voorloop+""+i+"</option>";
				i++;
			}		
			
			var i=1;
			var maand = "";
			while (i<=12){
				var voorloop = "";
				if(i<10){
					voorloop = "0";
				}		
				maand = maand+"<option value=\""+i+"\">"+voorloop+""+i+"</option>";
				i++;
			}		
				
			var i=2011;
			var jaar = "";
			while (i<=2020){
				jaar = jaar+"<option value=\""+i+"\">"+i+"</option>";
				i++;
			}				
			
			var title = "Nieuwe trein aanmaken";
			var html = "<form id='newtrainform' action='/xml/maintenance/ticketing/newtrain' method='post' onsubmit='savenewtrain();return false;'><table width='400' cellspacing='0' cellpadding='4' border='0'>";
					html += "<tr><td valign='top'>Treinnummer</td><td valign='top'><input type='text' name='treinnummer' id='treinnummer2' /></td></tr>";
					html += "<tr><td valign='top'>Capaciteit</td><td valign='top'><input type='text' id='capaciteit' name='capaciteit' style='width:100px;' /> personen</td></tr>";
					html += "<tr><td valign='top'>Soort</td><td valign='top'><select id='soort' name='soort'><option id='pendel'>pendel</option><option id='dinertrein'>dinertrein</option><option id='special'>special</option></select></td></tr>";
					html += "<tr><td valign='top'>Vertrekstation</td><td valign='top'><select name='vertrekstation' id='vertrekstation'>"+stations+"</select></td></tr>";
					html += "<tr><td valign='top'>Eindstation</td><td valign='top'><select name='eindstation' id='eindstation'>"+stations+"</select></td></tr>";			
					html += "<tr><td valign='top'>Datum</td><td valign='top'><select name='datumdag' id='datumdag' style='width:80px;'>"+dag+"</select> <select name='datummaand' id='datummaand' style='width:80px;'>"+maand+"</select> <select name='datumjaar' id='datumjaar' style='width:80px;'>"+jaar+"</select></td></tr>";
					html += "<tr><td valign='top'>Vertrektijd</td><td valign='top'><select name='vertrektijduur' id='vertrektijduur' style='width:50px;'>"+uren+"</select>:<select name='vertrektijdmin' id='vertrektijdmin' style='width:50px;'>"+min+"</select></td></tr>";
				html += "</table>";
				
				html += "<div align='right'><input type='submit' class='button' value='aanmaken' style='width:100px;'/></div>";
				html += "</form>";
			
			infowindow(title, html);
			
			$('#contentwindow').css('width','420px');
			$('#contentwindow').css('height','360px');	
			
		}
		else{
			alert(jsondata['fout']);
		}	
		
	  }
	});

}


function savenewtrain(){
	makePostRequest('/xml/maintenance/ticketing/newtrain', $("#newtrainform").serialize(),'newtrainprocess');
}



function newtrainprocess(xmldata){
	var trainid = "-1";
	$(xmldata).find('newtrain').each(function(){
		trainid = $(this).find("trainid").text();
		$('#treinnumer').attr('value',trainid);
		trainsearch();
		closeinfowindow();
	});
	
	
	$(xmldata).find('pid').each(function(){
		var field = $(this).find("field").text();
		alert(field);
	});

	return false;
}


function edittrainride(rid){
	makeGetRequest('/xml/maintenance/ticketing/edittrain/', rid,'edittrainrideform');
}

function saveedittrain(ritid){
	makePostRequest('/xml/maintenance/ticketing/edittrain/'+ritid, $("#newtrainform").serialize(),'newtrainprocess');
}

function edittrainrideform(xmldata){

	var jsondata = "";
	$.ajax({
	  url: '/json/stations',
	  dataType: 'json',
	  success: function(data) {
		jsondata = data;
		if(jsondata['returncode'] == '200'){

			var title = "Trein wijzigen";
			var html = "";
			$(xmldata).find('ticketdata').each(function(){
			
				var ritid = $(this).find("rit_id").text();
				var nummer = $(this).find("treinnummer").text();
				var start = $(this).find("startstation").text();
				var eind = $(this).find("eindstation").text();
				var aantal = $(this).find("aantalplaatsen").text();
				var dinertrein = $(this).find("dinertrein").text();
				var special = $(this).find("special").text();
				var datum = $(this).find("datum").text().split('/');
									
		
				var i=0;
				var uren = "";
				while (i<=23){
					var voorloop = "";
					if(i<10){
						voorloop = "0";
					}
					
					if(i == datum['3']){
						uren = uren+"<option value=\""+i+"\" selected>"+voorloop+""+i+"</option>";
					}
					else{
						uren = uren+"<option value=\""+i+"\">"+voorloop+""+i+"</option>";
					}
					i++;
				}

				
				var i=0;
				var min = "";
				while (i<=59){
					var voorloop = "";
					if(i<10){
						voorloop = "0";
					}		
					
					var bi = voorloop+""+i;
					
					if(bi == datum['4']){				
						min = min+"<option value=\""+i+"\" selected>"+voorloop+""+i+"</option>";
					}
					else{
						min = min+"<option value=\""+i+"\">"+voorloop+""+i+"</option>";
					}
								
					i++;
				}
				
				
				var i=1;
				var dag = "";
				while (i<=31){
					var voorloop = "";
					if(i<10){
						voorloop = "0";
					}		
					
					if(i == datum['0']){
						dag = dag+"<option value=\""+i+"\" selected>"+voorloop+""+i+"</option>";
					}
					else{
						dag = dag+"<option value=\""+i+"\">"+voorloop+""+i+"</option>";
					}
					
					
					i++;
				}		
				
				var i=1;
				var maand = "";
				while (i<=12){
					var voorloop = "";
					if(i<10){
						voorloop = "0";
					}	

					if(i == datum['1']){
						maand = maand+"<option value=\""+i+"\" selected>"+voorloop+""+i+"</option>";
					}
					else{
						maand = maand+"<option value=\""+i+"\">"+voorloop+""+i+"</option>";
					}
					
					
					
					i++;
				}		
					
				var i=2011;
				var jaar = "";
				while (i<=2020){
				
					if(i == datum['2']){
						jaar = jaar+"<option value=\""+i+"\" selected>"+i+"</option>";
					}
					else{
						jaar = jaar+"<option value=\""+i+"\">"+i+"</option>";
					}				
				
					
					i++;
				}								
				
				
				
				var startstations = "";
				for(var key in jsondata['stations']) {
					if(key == start){
						startstations = startstations+"<option value=\""+key+"\" selected>"+jsondata['stations'][key]+"</option>";
					}
					else{
						startstations = startstations+"<option value=\""+key+"\">"+jsondata['stations'][key]+"</option>";
					}
				} 					
				
				
				var eindstations = "";
				for(var key in jsondata['stations']) {
					if(key == eind){
						eindstations = eindstations+"<option value=\""+key+"\" selected>"+jsondata['stations'][key]+"</option>";
					}
					else{
						eindstations = eindstations+"<option value=\""+key+"\">"+jsondata['stations'][key]+"</option>";
					}
				} 				
			
			
				var soort = "<option id='pendel'>pendel</option>";
				
				if(dinertrein == '1'){
					soort = soort+"<option id='dinertrein' selected>dinertrein</option>";
				}
				else{
					soort = soort+"<option id='dinertrein'>dinertrein</option>";
				}
				
				if(special == '1'){
					soort = soort+"<option id='special' selected>special</option>";
				}
				else{
					soort = soort+"<option id='special'>special</option>";
				}				
					
			
				html = "<form id='newtrainform' method='post' onsubmit=\"saveedittrain(\'"+ritid+"\');return false;\">";
					html += "<table width='400' cellspacing='0' cellpadding='4' border='0'>";
						html += "<tr><td valign='top'>Treinnummer</td><td valign='top'><input type='text' name='treinnummer' id='treinnummer2' value='"+nummer+"' /></td></tr>";
						html += "<tr><td valign='top'>Capaciteit</td><td valign='top'><input type='text' id='capaciteit' name='capaciteit' style='width:100px;' value='"+aantal+"' /> personen</td></tr>";
						html += "<tr><td valign='top'>Soort</td><td valign='top'><select id='soort' name='soort'>"+soort+"</select></td></tr>";
						html += "<tr><td valign='top'>Vertrekstation</td><td valign='top'><select name='vertrekstation' id='vertrekstation'>"+startstations+"</select></td></tr>";
						html += "<tr><td valign='top'>Eindstation</td><td valign='top'><select name='eindstation' id='eindstation'>"+eindstations+"</select></td></tr>";			
						html += "<tr><td valign='top'>Datum</td><td valign='top'><select name='datumdag' id='datumdag' style='width:80px;'>"+dag+"</select> <select name='datummaand' id='datummaand' style='width:80px;'>"+maand+"</select> <select name='datumjaar' id='datumjaar' style='width:80px;'>"+jaar+"</select></td></tr>";
						html += "<tr><td valign='top'>Vertrektijd</td><td valign='top'><select name='vertrektijduur' id='vertrektijduur' style='width:50px;'>"+uren+"</select>:<select name='vertrektijdmin' id='vertrektijdmin' style='width:50px;'>"+min+"</select></td></tr>";
					html += "</table>";
									
					html += "<div align='right'><input type='submit' class='button' value='aanmaken' style='width:100px;'/></div>";
				html += "</form>";

			});
						
			infowindow(title, html);
			
			$('#contentwindow').css('width','420px');
			$('#contentwindow').css('height','360px');	
			
		}
		else{
			alert(jsondata['fout']);
		}	
		
	  }
	});


}


function settoday(d,m,j){
	$('#dag').val(d);
	$('#maand').val(m);
	$('#jaar').val(j);
	trainsearch();
}
 
 
var caption_nl = "leeg";
var caption_frl = "";
var caption_de = "";
var caption_en = "";
var retour = "0";
var arrangement = "0"; 
var status = "0"; 
var opmaak = "default";
 
function showtarieven(kaartid){
	var jsondata = "";
	$.ajax({
	  url: "/json/tarieven/"+kaartid,
	  dataType: 'json',
	  success: function(data) {
		jsondata = data;
		if(jsondata['returncode'] == '200'){
			var title = "Tariefgroepen";
			
			var jsondata2 = "";
			$.ajax({
			  url: "/json/tariefgroep/"+kaartid,
			  dataType: 'json',
			  success: function(data) {
				jsondata2 = data;
				if(jsondata2['returncode'] == '200'){
				
					caption_nl = jsondata2['tariefgroep']['caption_nl'];
					caption_frl = jsondata2['tariefgroep']['caption_frl'];
					caption_de = jsondata2['tariefgroep']['caption_de'];
					caption_en = jsondata2['tariefgroep']['caption_en'];
					opmaak = jsondata2['tariefgroep']['kaartopmaak'];

					if(jsondata2['tariefgroep']['retour'] == '1'){
						retour = "1";
					}

					if(jsondata2['tariefgroep']['arrangement'] == '-1'){
						arrangement = "1";
					}
					else{
						arrangement = jsondata2['tariefgroep']['arrangement'];
					}

					status = jsondata2['tariefgroep']['status'];
					
					var html = "<form id=\"kaartinfo\" method=\"post\" action=\"#\">";
						html = html+"<input type=\"hidden\" id=\"opmaak\" name=\"opmaak\" value=\""+opmaak+"\" />";
							if(kaartid == '4'){
								html = html+"<input type=\"hidden\" id=\"arrangement\" name=\"arrangement\" value=\"-1\" />";
								html = html+"<input type=\"hidden\" id=\"retour\" name=\"retour\" value=\"0\" />";
							}
							else{
								if(arrangement == '-2'){
									html = html+"<input type=\"hidden\" id=\"arrangement\" name=\"arrangement\" value=\"-2\" />";
								}
								else{
									html = html+"<input type=\"hidden\" id=\"arrangement\" name=\"arrangement\" value=\"-1\" />";
								}
							}
							
							html = html+"<table cellpadding=\"4\" cellspacing=\"0\" border=\"0\" width=\"100%\" class=\"windowoverzicht\">";
							html = html+"<tr><th>Kaart info</th><th></th></tr>";
							html = html+"<tr><td>Titel Nederlands</td><td><input type=\"text\" id=\"captionnl\" name=\"captionnl\" style=\"margin:0px;padding:0px;\" value=\""+caption_nl+"\" /></td></tr>";
							html = html+"<tr><td>Titel Friesland</td><td><input type=\"text\" id=\"captionfrl\" name=\"captionfrl\" style=\"margin:0px;padding:0px;\" value=\""+caption_frl+"\" /></td></tr>";
							html = html+"<tr><td>Titel Duits</td><td><input type=\"text\" id=\"captionde\" name=\"captionde\" style=\"margin:0px;padding:0px;\" value=\""+caption_de+"\" /></td></tr>";
							html = html+"<tr><td>Titel Engels</td><td><input type=\"text\" id=\"captionen\" name=\"captionen\" style=\"margin:0px;padding:0px;\" value=\""+caption_en+"\" /></td></tr>";
							if(kaartid != '4' && kaartid != '5'){							
								html = html+"<tr><td>Retour</td><td><select id=\"retour\" name=\"retour\" style=\"margin:0px;padding:0px;\">";
									html = html+"<option value=\"0\">nee</option>";
									if(retour == '1'){
										html = html+"<option value=\"1\" selected>ja</option>";
									}
									else{
										html = html+"<option value=\"1\">ja</option>";
									}
								html = html+"</select></td></tr>";
							}

							html = html+"<tr><td>Status</td><td><select id=\"status\" name=\"status\" style=\"margin:0px;padding:0px;\">";
								html = html+"<option value=\"0\">inactief</option>";
								if(status == '1'){
									html = html+"<option value=\"1\" selected>actief</option>";
								}
								else{
									html = html+"<option value=\"1\">actief</option>";
								}					
							html = html+"</select></td></tr>"
							html = html+"<tr><td>Opmaak ticket</td><td><span id=\"filename\">"+opmaak+"</span> <a href=\"#\" onclick=\"uploadticket('"+kaartid+"');\"><img src=\"/portal/js/tiny_mce/plugins/advimage/uploadicon.png\" border=\"0\"></a></td></tr></table></td></tr>"; 
						html = html+"</table><div id=\"uploader\" class=\"uploader\"></div><div align=\"right\">";
						if(kaartid != '4' && kaartid != '5'){
							html = html+"<input type=\"button\" class=\"button\" style=\"width:140px;\" onclick=\"delkaartsoort('"+kaartid+"');return false;\" value=\"kaartsoort verwijderen\"> ";
						}
						
						html = html+="<input type=\"button\" class=\"button\" style=\"width:100px;\" onclick=\"savekaartinfo('"+kaartid+"');return false;\" value=\"wijzigen\"></div></form>";
						if(kaartid != '4' && kaartid != '5'){
							html = html+"<table cellpadding=\"4\" cellspacing=\"0\" border=\"0\" width=\"100%\" class=\"windowoverzicht\">";
							html = html+"<tr><th>Tariefsoorten</th></tr>";
							for(var key in jsondata['tarieven']) {
								html = html+"<tr><td><a href=\"#\" onclick=\"edittarief('"+key+"');return false;\">"+jsondata['tarieven'][key]+"</a></td></tr>";			
							} 	
							html = html+"</table><div align=\"right\"><input type=\"button\" class=\"button\" style=\"width:100px;\" onclick=\"nieuwetariefgroep('"+kaartid+"');return false;\" value=\"nieuw\"></div>";
						}
						infowindow(title, html);
					
						$('#contentwindow').css('width','420px');					
							
				}
				else{
					alert(jsondata2['fout']);
				}
			  }
			});			
			 

		}
		else{
			alert(jsondata['fout']);
		}	
	  }
	});	
	
}


function uploadticket(k){
	$('#uploader').html('<iframe width="368" height="100" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="/portal/ticket_upload.php"></iframe>');	
	$('#uploader').slideDown('fast',function(){});
}

function processticketupload(filename){
	$('#uploader').slideUp('fast',function(){
		$('#opmaak').attr('value',filename);
		$('#filename').html(filename);
	});
}


function showdinertarieven(ritid){
	makeGetRequest('/xml/maintenance/ticketing/dinertarief/', ritid,'showdinertarievenhtml');	
}

function showdinertarievenhtml(xmldata){
	var m = false;
	var groepid = $(xmldata).find('groep').find('id').text();
	var html = "<table width=\"100%\" cellpadding=\"4\" cellspacing=\"0\" border=\"0\" class=\"windowoverzicht\">";
	html += "<tr><th>Naam groep</th></tr>";
	$(xmldata).find('tarieven').find('entry').each(function(){	
		var caption = $(this).find('caption_nl').text();
		var tariefid = $(this).find('tarief_id').text();
		html += "<tr onclick=\"edittarief('"+tariefid+"');\"><td>"+caption+"</td></tr>";
		m = true;
	}); 
	html += "</table>";
	html += "<div align=\"right\"><input style=\"width:110px;\" type=\"button\" id=\"button\" name=\"button\" class=\"button\" value=\"nieuwe tariefgroep\" onclick=\"nieuwetariefgroep('5/"+groepid+"');\"></div>";

	if(m === false){
		
		html = "Er is op dit moment nog geen tariefgroep toegekend aan deze dinertrein. <a href=\"#\" onclick=\"nieuwetariefgroep('5/"+groepid+"');\">Klik op nieuw om een nieuwe groep toe te kennen.</a>";
	}
	infowindow('Tarieven gekoppeld aan dinertrein',html);
	$('#contentwindow').css('width','420px');
}


function savekaartinfo(kid){
	makePostRequest('/xml/maintenance/ticketing/editkaartsoort/'+kid, $("#kaartinfo").serialize(),'pagereload');	
}

function createnewkaart(deel){
	makeGetRequest('/xml/maintenance/ticketing/createkaartsoort/', deel,'pagereload');	
}

function delkaartsoort(kid){
	if(confirm('Weet u zeker dat u deze kaartsoort wilt verwijderen?')){
		makeGetRequest('/xml/maintenance/ticketing/delkaartsoort/', kid,'pagereload');	
	}
	else{
		return false;
	}
}

function edittarief(t){
	
	$('#contentwindow').slideUp('fast',function(){
		$('#infowindow').slideUp('fast',function(){
			$('#contentwindow').remove();
			infowindowstatus = 0;	
			makeGetRequest('/xml/maintenance/ticketing/edittarief/', t,'processedittarief');
		});
	});
}

function setmoneyvaleu(id,v){
	var euro = v/100;
	euro = $.currency(euro, {s:".",d:",",c:2});
	if(id == 'returnvalue'){
		return euro
	}
	else{
		$('#'+id).html("(&euro; "+euro+")");
	}
}


function nieuwetariefgroep(kaartid){

	var k = kaartid.split('/');
	var l = k.length;
	var ritid = "-1";
	for(var i = 0; i < l; i++){ 
		if(i == 0){
			var kaartid = k[i];
		}
		else{
			var ritid = k[i];
		}
	}
	

	$('#contentwindow').slideUp('fast',function(){
		$('#infowindow').slideUp('fast',function(){
			$('#contentwindow').remove();
			infowindowstatus = 0;	
			var html = "";
			var title = "Nieuwe tariefgroep";
			
			var i=1;
			var eenheden = "";
			while (i<=200){
				eenheden = eenheden+"<option value='"+i+"'>"+i+"</option>";
				i++;
			}
			
			html = html+"<form id=\"edittarief\" action=\"/xml/maintenance/ticketing/edittarief/new/\" method=\"post\" onsubmit=\"saveedittarief('new');return false;\">";		
				html = html+"<input type=\"hidden\" id=\"kaart\" name=\"kaart\" value=\""+kaartid+"\" />";
				
				if(ritid != '-1'){
					html = html+"<input type=\"hidden\" id=\"ritid\" name=\"ritid\" value=\""+ritid+"\" />";
				}
				
				html = html+"<fieldset style=\"margin-bottom:10px;\"><legend>Prijs informatie</legend>";
					html = html+"<table cellpadding=\"4\" cellspacing=\"0\" border=\"0\">";
						html = html+"<tr><td valign=\"top\">Aantal eenheden</td><td colspan=\"2\"><select style=\"width:100px;\" id=\"eenheden\" name=\"eenheden\">"+eenheden+"</select></td></tr>";
						html = html+"<tr><td valign=\"top\">Half traject</td><td valign=\"top\"><input type=\"text\" onkeyup=\"setmoneyvaleu('eurohalf',this.value);\" style=\"width:100px;\" id=\"halftraject\" name=\"halftraject\" /> centen </td><td valign=\"top\"><div id=\"eurohalf\" style=\"margin-top:4px;\"></div></td></tr>";
						html = html+"<tr><td valign=\"top\">Heel traject</td><td valign=\"top\"><input type=\"text\" onkeyup=\"setmoneyvaleu('euroheel',this.value);\" style=\"width:100px;\" id=\"heeltraject\" name=\"heeltraject\" /> centen </td><td valign=\"top\"><div id=\"euroheel\" style=\"margin-top:4px;\"></div></td></tr>";
					html = html+"</table>";
				html = html+"</fieldset>";
				
				
				html = html+"<fieldset style=\"margin-bottom:10px;\"><legend>Presentatie Nederlands</legend>";
					html = html+"<table cellpadding=\"4\" cellspacing=\"0\" border=\"0\">";
						html = html+"<tr><td valign=\"top\">Titel</td><td><input type=\"text\" id=\"caption_nl\" name=\"caption_nl\" /></td></tr>";
						html = html+"<tr><td valign=\"top\">Uitleg</td><td><textarea id=\"uitleg_nl\" name=\"uitleg_nl\" style=\"width:300px;height:60px;\"></textarea></td></tr>";
					html = html+"</table>";
				html = html+"</fieldset>";		
				
				
				html = html+"<fieldset style=\"margin-bottom:10px;\"><legend>Presentatie Fries</legend>";
					html = html+"<table cellpadding=\"4\" cellspacing=\"0\" border=\"0\">";
						html = html+"<tr><td valign=\"top\">Titel</td><td><input type=\"text\" id=\"caption_frl\" name=\"caption_frl\" /></td></tr>";
						html = html+"<tr><td valign=\"top\">Uitleg</td><td><textarea id=\"uitleg_frl\" name=\"uitleg_frl\" style=\"width:300px;height:60px;\"></textarea></td></tr>";
					html = html+"</table>";
				html = html+"</fieldset>";	

				html = html+"<fieldset style=\"margin-bottom:10px;\"><legend>Presentatie Duits</legend>";
					html = html+"<table cellpadding=\"4\" cellspacing=\"0\" border=\"0\">";
						html = html+"<tr><td valign=\"top\">Titel</td><td><input type=\"text\" id=\"caption_de\" name=\"caption_de\" /></td></tr>";
						html = html+"<tr><td valign=\"top\">Uitleg</td><td><textarea id=\"uitleg_de\" name=\"uitleg_de\" style=\"width:300px;height:60px;\"></textarea></td></tr>";
					html = html+"</table>";
				html = html+"</fieldset>";	
				
				html = html+"<fieldset style=\"margin-bottom:10px;\"><legend>Presentatie Engels</legend>";
					html = html+"<table cellpadding=\"4\" cellspacing=\"0\" border=\"0\">";
						html = html+"<tr><td valign=\"top\">Titel</td><td><input type=\"text\" id=\"caption_en\" name=\"caption_en\" /></td></tr>";
						html = html+"<tr><td valign=\"top\">Uitleg</td><td><textarea id=\"uitleg_en\" name=\"uitleg_en\" style=\"width:300px;height:60px;\"></textarea></td></tr>";
					html = html+"</table>";
				html = html+"</fieldset>";			
				html = html+"<div align=\"right\"><input type=\"submit\" class=\"button\" style=\"width:100px;\" value=\"wijzigen\"/></div>";	
			html = html+"</form>";		
				
			infowindow(title, html);
			$('#contentwindow').css('width','420px');
		});
	});			
}

function removetarief(tid){
	if(confirm('Weet u zeker dat u deze tariefgroep wilt verwijderen?')){
		makeGetRequest('/xml/maintenance/ticketing/deltarief/', tid,'pagereload');	
	}
	else{
		return false;
	}
}


function processedittarief(xmldata){
	var title = "Wijzig tariefgroep";
	var html = "";
		
		
	$(xmldata).find('tarief').find('entry').each(function(){
		var tid = $(this).find("tarief_id").text();		
		var caption_nl = $(this).find("caption_nl").text();		
		var caption_frl = $(this).find("caption_frl").text();		
		var caption_de = $(this).find("caption_de").text();		
		var caption_en = $(this).find("caption_en").text();
		
		var half_traject = $(this).find("half_traject").text();
		var heel_traject = $(this).find("heel_traject").text();
		var aantal_eenheden = $(this).find("aantal_eenheden").text();
		
		var uitleg_nl = $(this).find("uitleg_nl").text();		
		var uitleg_frl = $(this).find("uitleg_frl").text();		
		var uitleg_de = $(this).find("uitleg_de").text();		
		var uitleg_en = $(this).find("uitleg_en").text();		
		
		
		var i=1;
		var eenheden = "";
		while (i<=200){
			if(i == aantal_eenheden){
				eenheden = eenheden+"<option value='"+i+"' selected>"+i+"</option>";
			}
			else{
				eenheden = eenheden+"<option value='"+i+"'>"+i+"</option>";
			}
			i++;
		}
		html = html+"<form id=\"edittarief\" action=\"/xml/maintenance/ticketing/edittarief/"+tid+"\" method=\"post\" onsubmit=\"saveedittarief('"+tid+"');return false;\">";		
			html = html+"<fieldset style=\"margin-bottom:10px;\"><legend>Prijs informatie</legend>";
				html = html+"<table cellpadding=\"4\" cellspacing=\"0\" border=\"0\">";
					html = html+"<tr><td valign=\"top\">Aantal eenheden</td><td colspan=\"2\"><select style=\"width:100px;\" id=\"eenheden\" name=\"eenheden\">"+eenheden+"</select></td></tr>";
					html = html+"<tr><td valign=\"top\">Half traject</td><td valign=\"top\"><input type=\"text\" onkeyup=\"setmoneyvaleu('eurohalf',this.value);\" style=\"width:100px;\" id=\"halftraject\" name=\"halftraject\" value=\""+half_traject+"\" /> centen </td><td valign=\"top\"><div id=\"eurohalf\" style=\"margin-top:4px;\"></div></td></tr>";
					html = html+"<tr><td valign=\"top\">Heel traject</td><td valign=\"top\"><input type=\"text\" onkeyup=\"setmoneyvaleu('euroheel',this.value);\" style=\"width:100px;\" id=\"heeltraject\" name=\"heeltraject\" value=\""+heel_traject+"\" /> centen </td><td valign=\"top\"><div id=\"euroheel\" style=\"margin-top:4px;\"></div></td></tr>";
				html = html+"</table>";
			html = html+"</fieldset>";
			
			
			html = html+"<fieldset style=\"margin-bottom:10px;\"><legend>Presentatie Nederlands</legend>";
				html = html+"<table cellpadding=\"4\" cellspacing=\"0\" border=\"0\">";
					html = html+"<tr><td valign=\"top\">Titel</td><td><input type=\"text\" id=\"caption_nl\" name=\"caption_nl\" value=\""+caption_nl+"\" /></td></tr>";
					html = html+"<tr><td valign=\"top\">Uitleg</td><td><textarea id=\"uitleg_nl\" name=\"uitleg_nl\" style=\"width:300px;height:60px;\">"+uitleg_nl+"</textarea></td></tr>";
				html = html+"</table>";
			html = html+"</fieldset>";		
			
			
			html = html+"<fieldset style=\"margin-bottom:10px;\"><legend>Presentatie Fries</legend>";
				html = html+"<table cellpadding=\"4\" cellspacing=\"0\" border=\"0\">";
					html = html+"<tr><td valign=\"top\">Titel</td><td><input type=\"text\" id=\"caption_frl\" name=\"caption_frl\" value=\""+caption_frl+"\" /></td></tr>";
					html = html+"<tr><td valign=\"top\">Uitleg</td><td><textarea id=\"uitleg_frl\" name=\"uitleg_frl\" style=\"width:300px;height:60px;\">"+uitleg_frl+"</textarea></td></tr>";
				html = html+"</table>";
			html = html+"</fieldset>";	

			html = html+"<fieldset style=\"margin-bottom:10px;\"><legend>Presentatie Duits</legend>";
				html = html+"<table cellpadding=\"4\" cellspacing=\"0\" border=\"0\">";
					html = html+"<tr><td valign=\"top\">Titel</td><td><input type=\"text\" id=\"caption_de\" name=\"caption_de\" value=\""+caption_de+"\" /></td></tr>";
					html = html+"<tr><td valign=\"top\">Uitleg</td><td><textarea id=\"uitleg_de\" name=\"uitleg_de\" style=\"width:300px;height:60px;\">"+uitleg_de+"</textarea></td></tr>";
				html = html+"</table>";
			html = html+"</fieldset>";	
			
			html = html+"<fieldset style=\"margin-bottom:10px;\"><legend>Presentatie Engels</legend>";
				html = html+"<table cellpadding=\"4\" cellspacing=\"0\" border=\"0\">";
					html = html+"<tr><td valign=\"top\">Titel</td><td><input type=\"text\" id=\"caption_en\" name=\"caption_en\" value=\""+caption_en+"\" /></td></tr>";
					html = html+"<tr><td valign=\"top\">Uitleg</td><td><textarea id=\"uitleg_en\" name=\"uitleg_en\" style=\"width:300px;height:60px;\">"+uitleg_en+"</textarea></td></tr>";
				html = html+"</table>";
			html = html+"</fieldset>";			
			html = html+"<div align=\"right\"><input type=\"button\" class=\"button\" style=\"width:100px;\" value=\"verwijderen\" onclick=\"removetarief('"+tid+"');\"/>  <input type=\"submit\" class=\"button\" style=\"width:100px;\" value=\"wijzigen\"/></div>";	
		html = html+"</form>";		
	});
	
	if(html == ''){
		html = "er is op dit moment geen tariefgroep beschikbaar";
	}
	
	infowindow(title, html);
	$('#contentwindow').css('width','420px');
}

function IsNumeric(input) {
	return (input - 0) == input && input.length > 0; 
} 


function saveedittarief(tid){
	//controle

	var h = $('#halftraject').val();
		h = h+"";
		
	var h2 = $('#heeltraject').val();
		h2 = h2+"";		
		
	
	if(h == ''){
		alert('De prijs van het half traject dient ingevuld te worden.');
		return false;
	}
	else if(h2 == ''){
		alert('De prijs van het heel traject dient ingevuld te worden.');
		return false;
	}	
	else{
		if(IsNumeric($('#halftraject').attr('value'))){
			if(IsNumeric($('#heeltraject').attr('value'))){
				
				var c = $('#caption_nl').val();
					c = c+"";
					
				var u = $('#uitleg_nl').val();
					u = u+"";					
					
					if(c == ''){
						alert('De titel in het Nederlands dient minimaal ingevuld te worden');
						return false;						
					}
					else if(u == ''){
						alert('De uitleg in het Nederlands dient minimaal ingevuld te worden');
						return false;											
					}
			}
			else{
				alert('De prijs van het heel traject dient ingevuld te worden als bedrag in centen');
				return false;
			}
		}
		else{
			alert('De prijs van het half traject dient ingevuld te worden als bedrag in centen');
			return false;
		}
	}
	
	makePostRequest('/xml/maintenance/ticketing/edittarief/'+tid, $("#edittarief").serialize(),'pagereload');
}


function ticketsearch(t){
	if(t == ''){ //algemeen
		$('#ticketlist').html('');
	}
	else{
		if(t.value == ''){
			$('#ticketlist').html('');
		}
		else{
			var url = "";
			if(t.id == 'boekingsnummer'){
				url = url+"/boeking/"+t.value;
			}
			else if(t.id == 'trein'){
				url = url+"/trein/"+t.value;
			}	
			else if(t.id == 'achternaam'){
				url = url+"/achternaam/"+t.value;
			}	 
			
			makeGetRequest('/xml/maintenance/ticketing/ticketsearch', url,'ticketsearchresult');		
		}
	}
}

function ticketsearchresult(xmldata){
 
	var html = "<table width=\"100%\" cellpadding=\"4\" cellspacing=\"0\" border=\"0\" class=\"allmypages t\">";
		html += "<tr>";
			html += "<th>Boeking</th>";
			html += "<th>Achternaam</th>";
			html += "<th>Trein</th>";
			html += "<th>Datum</th>";
		html += "</tr>";	
	
	var t = false;
	$(xmldata).find('result').find('entry').each(function(){
		var orderid = $(this).find("order_id").text();
		var userid = $(this).find("user_id").text();
		var achternaam = $(this).find("achternaam").text();
		var ritid = $(this).find("ritid").text();
		var treinnummer = $(this).find("treinnummer").text();
		var vertrektijd = $(this).find("vertrektijd").text();
		
		html += "<tr>";
			html += "<td><a href=\"#\" onclick=\"ticketdetails('"+orderid+"');\">"+orderid+"</a></td>";
			html += "<td><a href=\"#\" onclick=\"ticketdetails('"+orderid+"');\">"+achternaam+"</a></td>";
			html += "<td><a href=\"#\" onclick=\"ticketdetails('"+orderid+"');\">"+treinnummer+"</a></td>";
			html += "<td><a href=\"#\" onclick=\"ticketdetails('"+orderid+"');\">"+vertrektijd+"</a></td>";
		html += "</tr>";
		t = true;
	});
	
	
	if(t == false){
		html += "<tr>";
			html += "<td colspan=\"4\">er zijn geen boekingen gevonden</td>";
		html += "</tr>";	
	}	
	html += "</table>";
	

	$('#ticketlist').html(html);
	
}

function ticketdetails(orderid){
	makeGetRequest('/xml/maintenance/ticketing/details/', orderid,'ticketdetailsresult');
}

function ticketdetailsresult(xmldata){
	var title = "Wijzig boeking";
	var html = "";
		html += "<table cellpadding=\"4\" cellspacing=\"0\" border=\"0\" width=\"100%\" class=\"windowoverzicht\">";
			html += "<tr><th colspan=\"2\">Boekingsgegevens</th></tr>";	

			var payedstatus = "";
			var download = "";
			var scan = "";
			var processed = "";
			
			var annuleren = "false";
			
			$(xmldata).find('response').find('ticketinfo').find('entry').each(function(){
				var kaartid = $(this).find("kaartid").text();
				var ticket = $(this).find("ticket").text();
				var naam = $(this).find("kaartnaam").text();
				var rit = $(this).find("rit").text();
				var aantal = $(this).find("aantal").text();
				var aantaleenheden = $(this).find("aantaleenheden").text();
				var tarief = $(this).find("tarief").text();
				var tariefaantal = $(this).find("tariefaantal").text();
				var soorttarief = $(this).find("soorttarief").text();
				var start = $(this).find("startstation").text();
				var eind = $(this).find("eindstation").text();
				var retourrit = $(this).find("retourrit").text();			
				var totaaltebetalen = $(this).find("totaaltebetalen").text();
				
		
					html += "<tr><td><strong>Kaartsoort</strong></td><td>"+ticket+"</td></tr>";
					html += "<tr><td>Tariefgroep</td><td>"+naam+"</td></tr>";
					html += "<tr><td>Aantal</td><td>"+aantal+" (eenheden: "+aantaleenheden+")</td></tr>";
					
					html += "<tr><td>Startstation</td><td>"+start+"</td></tr>";
					html += "<tr><td>Eindstation</td><td>"+eind+"</td></tr>";
					html += "<tr><td>Tariefsoort</td><td>"+soorttarief+"</td></tr>";
					html += "<tr><td>&nbsp;</td><td>&nbsp;</td></tr>";
			}); 
			
			var user_geslacht = "heer/mevrouw";
			var user_naam = "";
			var user_email = "";
			var loged_user_naam = "";
			var loged_user_email = "";
			$(xmldata).find('response').find('userdata').each(function(){
				user_geslacht = $(this).find("geslacht").text(); 
				user_naam = $(this).find("achternaam").text();
				user_email = $(this).find("emailadres").text();
			});
			
			$(xmldata).find('response').find('profiledata').each(function(){
				loged_user_naam = $(this).find("voorletters").text()+" "+$(this).find("tussenvoegsel").text()+" "+$(this).find("achternaam").text();
				loged_user_email = $(this).find("emailadres").text();
			});			
			
			
			var orderid = "-1";
			$(xmldata).find('response').find('orderinfo').each(function(){
				
				orderid = $(this).find("orderid").text();
							
				payedstatus =  $(this).find("status").text();
				if(payedstatus == '0'){
					payedstatus = "nee";
				}
				else if(payedstatus == '1'){
					payedstatus = "ja";
				}	
				else if(payedstatus == '5'){
					payedstatus = "order geannuleerd";
				}
				else if(payedstatus == '7'){
					payedstatus = "order geannuleerd, <span style=\"color:red;\">terugboeking dient nog gedaan te worden</span>";
				}				
				else{
					payedstatus = "onbekend";
				}
				
				
				download =  $(this).find("download").text();
				if(download == '0'){
					download = "nee";
				}
				else if(download == '1'){
					download = "ja";
				}				
				else{
					download = "onbekend";
				}				
				
				
				scan =  $(this).find("scan").text();
				if(scan == '0'){
					scan = "nee";
				}
				else if(scan == '1'){
					scan = "heenreis";
				}				
				else if(scan == '2'){
					scan = "terugreis";
				}
				else if(scan == '3'){
					scan = "retour gescand";
				}					
				else{
					scan = "onbekend";
				}					
				
				annuleren = $(this).find("refund").text();
				processed =  $(this).find("processed").text();
				if(processed == '0'){
					processed = "nee";
				}
				else if(processed == '1'){
					processed = "ja";
				}				
				else{
					processed = "onbekend";
				}				
			});
			
			html += "<tr><th colspan=\"2\">Statusoverzicht</th></tr>";
			html += "<tr><td>Betaald</td><td>"+payedstatus+"</td></tr>";
			html += "<tr><td>Download</td><td>"+download+"</td></tr>";
			html += "<tr><td>Scan</td><td>"+scan+"</td></tr>";
			html += "<tr><td>Verwerking</td><td>"+processed+"</td></tr>";
			if(annuleren == "true"){
				html += "<tr><td></td><td><input type=\"button\" value=\"boeking annuleren\" class=\"btn\" style=\"width:160px;\" onclick=\"annulerenticket('"+orderid+"');\"/> <input type=\"button\" class=\"btn\" value=\"mail versturen\" style=\"width:160px;\" onclick=\"mailticket('"+orderid+"');\" /></td></tr>";
			}
			
		html += "</table>";
		
		html += "<div id=\"maillayer\" style=\"display:none;\"><br/><fieldset><legend>Tickets mailen</legend><form id=\"mailticketform\"><table cellpadding=\"4\" cellspacing=\"0\" border=\"0\">";
			html += "<tr><td valign=\"top\">Uw naam</td><td><input type=\"text\" name=\"uwnaam\" value=\""+loged_user_naam+"\" /></td></tr>";
			html += "<tr><td valign=\"top\">Uw emailadres</td><td><input type=\"text\" name=\"uwemail\" value=\""+loged_user_email+"\" /></td></tr>";
			html += "<tr><td valign=\"top\">Ontvanger</td><td><input type=\"text\" name=\"ontvanger\" value=\""+user_email+"\" /></td></tr>";
			html += "<tr><td valign=\"top\">Onderwerp</td><td><input type=\"text\" name=\"onderwerp\" value=\"Uw FStM tickets\" /></td></tr>";
			html += "<tr><td valign=\"top\">Bericht</td><td><textarea name=\"bericht\">Geachte "+user_geslacht+" "+user_naam+",\n\rDe door u bestelde tickets liggen klaar. U kunt ze nu downloaden door op de volgende link te klikken:\n\rhttp://beta.fstm.nl/e-ticket/download \n\rWij zien u graag op de trein!</textarea></td></tr>";
			html += "<tr><td valign=\"top\"></td><td align=\"right\"><input type=\"button\" class=\"btn\" onclick=\"processmailticket();\" value=\"versturen\"></td></tr>";
		html += "</table></form></fieldset></div>";
	
	infowindow(title, html);
	$('#contentwindow').css('width','420px');		
	
}


function mailticket(orderid){
	$('#maillayer').slideDown();
}

function processmailticket(){
	makePostRequest('/xml/maintenance/ticketing/ticketsend/', $("#mailticketform").serialize(),'pagereload');	
}


function annulerenticket(orderid){
	if(orderid == '-1'){
		alert('Order is onbekend');
	}
	else{
		if(confirm('Weet u zeker dat u deze boeking wilt annuleren?') == true){
			makeGetRequest('/xml/maintenance/ticketing/annuleren/', orderid,'pagereload');
		}		
	}
}



function setautoticketing(trid,soort){
	if(trid  == '1'){
		alert('Superbeheerders hebben altijd alle rechten');
	}
	else{
		makeGetRequest('/xml/maintenance/ticketing/autorisatie/', trid+"/"+soort,'pagereload');
	}
}

function bezettingdagofrit(){
	var ritid = $('#reporting_rit').attr('value');
	var dag = $('#reporting_dag').attr('value');
	reporting(ritid,dag,'-','-');
}

function bezettingperperiode(){

	var van = $('#reporting_dag_van').attr('value');
	var tot = $('#reporting_dag_tot').attr('value');

	
	if(van == ""){
		alert('Geef de startdatum op, van de weer te geven periode');
	}
	else if(tot == ""){
		alert('Geef de einddatum op, van de weer te geven periode');
	}
	else{
		var periode = van+"_"+tot;
		var trein = $('#ritsoort').attr('value');
		reporting('-','-',periode,trein);
	}
}


function reporting(ritid,dag,periode,treinsoort){

	Highcharts.visualize = function(table, options) {
		// the categories
		options.xAxis.categories = [];
		$('tbody th', table).each( function(i) {
			options.xAxis.categories.push(this.innerHTML);
		});
		
		// the data series
		options.series = [];
		$('tr', table).each( function(i) {
			var tr = this;
			$('th, td', tr).each( function(j) {
				if (j > 0) { // skip first column
					if (i == 0) { // get the name and init the series
						options.series[j - 1] = { 
							name: this.innerHTML,
							data: []
						};
					} else { // add values
						options.series[j - 1].data.push(parseFloat(this.innerHTML));
					}
				}
			});
		});
		
		var chart = new Highcharts.Chart(options);
	}

	//bezetting per dag of rit
	
	if(dag != '-'){
		if(ritid == '-1'){ // per dag
			if(dag == ""){
				alert('Selecteer een datum');
				return false;
			}
			
			var stations;
			var dagu = dag.replace(/\//gi, '-');
			$.ajax({
			  url: '/json/stations',
			  dataType: 'json',
			  success: function(data) {
				stations = data;
				if(ritid == '-1'){
					$.ajax({
					url: '/json/reporting/bezetting/dag/('+dagu+')',
					dataType: 'json',
					success: function(jsondata) {
							if(jsondata['returncode'] == '200'){
								var t = "<table>";
								t += "<thead>";
									t += "<tr><th></th><th>verkocht</th><th>totaal</th></tr>";
								t += "</thead>";
									t += "<tbody>";
										for(var key in jsondata['bezetting']) {
											var tijd = jsondata['bezetting'][key]['tijd'];				
											var nummer = jsondata['bezetting'][key]['nummer'];
											var totaal = jsondata['bezetting'][key]['totaal'];	
											var verkocht = jsondata['bezetting'][key]['verkocht'];	
											t += "<tr><th>"+tijd+" ("+nummer+")</th><td>"+verkocht+"</td><td>"+totaal+"</td></tr>";
										}
									t += "</tbody>";
								t += "</table>";

								var options = {
									   chart: {
										  renderTo: 'bezettingsgraad',
										  defaultSeriesType: 'column'
									   },
									   title: {
										  text: 'Bezetting van '+dag
									   },
									   xAxis: {
										  title: {
											 text: 'rit'
										  }					   
									   },
									   yAxis: {
										  title: {
											 text: 'eenheden'
										  }
									   },
									   tooltip: {
										  formatter: function() {
											 return '<b>'+ this.series.name +'</b><br/>'+
												this.y +' '+ this.x.toLowerCase();
										  }
									   }
									};

								Highcharts.visualize(t, options);
								
							}
							else{
								alert(jsondata['fout']);
							}

						}
					});	
					
				}
				else{
					alert('reportage onbekend');
				}
			  }
			});
		
		}
		else{ // per rit
			var stations;
			$.ajax({
			  url: '/json/stations',
			  dataType: 'json',
			  success: function(data) {
				stations = data;
				if(ritid != '0'){
					$.ajax({
					url: '/json/reporting/bezetting/rit/'+ritid,
					dataType: 'json',
					success: function(jsondata) {

							if(jsondata['returncode'] == '200'){
								var t = "<table>";
								t += "<thead>";
									t += "<tr><th></th><th>verkocht</th><th>totaal</th></tr>";
								t += "</thead>";
									t += "<tbody>";
										var showgraphic = false;
										var treinnummer = "";
										for(var key in jsondata['bezetting']) {
											treinnummer =  jsondata['bezetting'][key]['nummer'];
											for(var key2 in jsondata['bezetting'][key]['stations']) {
												var station = jsondata['bezetting'][key]['stations'][key2]['station'];	
												var voorraad = jsondata['bezetting'][key]['stations'][key2]['voorraad'];	
												var verkocht = jsondata['bezetting'][key]['stations'][key2]['verkocht'];				
												t += "<tr><th>"+stations['stations'][station]+"</th><td>"+verkocht+"</td><td>"+voorraad+"</td></tr>";
											}
											showgraphic = true;
										}
									t += "</tbody>";
								t += "</table>";
								
								var options = {
									   chart: {
										  renderTo: 'bezettingsgraad',
										  defaultSeriesType: 'column'
									   },
									   title: {
										  text: 'Bezetting trein '+treinnummer
									   },
									   xAxis: {
										  title: {
											 text: 'stations'
										  }					   
									   },
									   yAxis: {
										  title: {
											 text: 'eenheden'
										  }
									   },
									   tooltip: {
										  formatter: function() {
											 return '<b>'+ this.series.name +'</b><br/>'+
												this.y +' '+ this.x.toLowerCase();
										  }
									   }
									};

								if(showgraphic == true){
									Highcharts.visualize(t, options);
								}
								else{
									alert('Er is op dit moment geen data beschikbaar over deze rit');
								}
								
							}
							else{
								alert('er is een fout opgetreden (1) ');
							}

						}
					});	
					
				}
				else{
					alert('reportage onbekend');
				}
			  }
			});			
		}
		
	}
	else{
		// bezetting per periode
		var periode = periode.replace(/\//gi, '-');
		var toonperiode = periode.replace(/_/gi, ' t/m ');
		
		$.ajax({
		url: '/json/reporting/bezetting/periode/('+periode+')/'+treinsoort,
		dataType: 'json',
		success: function(jsondata) {
				if(jsondata['returncode'] == '200'){
					var t = "<table>";
					t += "<thead>";
						t += "<tr><th></th><th>bezetting per dag</th><th>gemiddelde bezetting</th></tr>";
					t += "</thead>";
						t += "<tbody>";
						
							for(var key in jsondata['bezetting']) {
								var datum = jsondata['bezetting'][key]['tijd'];				
								var totaal = jsondata['bezetting'][key]['totaal'];	
								var verkocht = jsondata['bezetting'][key]['verkocht'];	
								var bezetting = jsondata['bezetting'][key]['percentage'];	
							
								t += "<tr><th>"+datum+"</th><td>"+bezetting+"</td><td>"+jsondata['gemiddeldebezetting']+"</td></tr>";
								
							}
						t += "</tbody>";
					t += "</table>";

					var options = {
						   chart: {
							  renderTo: 'bezettingsgraad',
							  defaultSeriesType: 'line'
						   },
						   title: {
							  text: 'Bezetting van '+toonperiode
						   },						   
						   xAxis: {
							tickInterval: 5,
							  title: {
								 text: 'periode'
							  }					    
						   },
						   yAxis: {
							  min: 0,
							  max: 100,
							  title: {
								 text: 'bezettingsgraad (%)'
							  }
						   },
						   tooltip: {
							  formatter: function() {
								 return '<b>'+ this.series.name +'</b><br/>'+
									this.y +' '+ this.x.toLowerCase();
							  }
						   }
						};

					Highcharts.visualize(t, options);
					//$('#bezettingsgraad').html(t);
					
				}
				else{
					alert(jsondata['fout']);
				}

			}
		});	
			
		
	
	}
}


function omzetdagofrit(){
	var ritid = $('#omzet_reporting_rit').attr('value');
	var dag = $('#omzet_reporting_dag').attr('value');
	omzetreporting(ritid,dag,'-','-');
}

function omzetperperiode(){

	var van = $('#omzet_reporting_dag_van').attr('value');
	var tot = $('#omzet_reporting_dag_tot').attr('value');

	
	if(van == ""){
		alert('Geef de startdatum op, van de weer te geven periode');
	}
	else if(tot == ""){
		alert('Geef de einddatum op, van de weer te geven periode');
	}
	else{
		var periode = van+"_"+tot;
		var trein = $('#omzet_ritsoort').attr('value');
		var reseller = $('#reseller').attr('value');
		omzetreporting('-','-',periode,trein,reseller);
	}
}

function omzetreporting(ritid,dag,periode,treinsoort,reseller){

	Highcharts.visualize = function(table, options) {
		// the categories
		options.xAxis.categories = [];
		$('tbody th', table).each( function(i) {
			options.xAxis.categories.push(this.innerHTML);
		});
		
		// the data series
		options.series = [];
		$('tr', table).each( function(i) {
			var tr = this;
			$('th, td', tr).each( function(j) {
				if (j > 0) { // skip first column
					if (i == 0) { // get the name and init the series
						options.series[j - 1] = { 
							name: this.innerHTML,
							data: []
						};
					} else { // add values
						options.series[j - 1].data.push(parseFloat(this.innerHTML));
					}
				}
			});
		});
		
		var chart = new Highcharts.Chart(options);
	}

	//omzet per dag of rit
	
	if(dag != '-'){
		if(ritid == '-1'){ // per dag
			if(dag == ""){
				alert('Selecteer een datum');
				return false;
			}
			
			var stations;
			var dagu = dag.replace(/\//gi, '-');
			$.ajax({
			  url: '/json/stations',
			  dataType: 'json',
			  success: function(data) {
				stations = data;
				if(ritid == '-1'){
					$.ajax({
					url: '/json/reporting/omzet/dag/('+dagu+')',
					dataType: 'json',
					success: function(jsondata) {
							if(jsondata['returncode'] == '200'){
								var t = "<table>";
								t += "<thead>";
									t += "<tr><th></th><th>rit omzet</th><th>dag omzet</th></tr>";
								t += "</thead>";
									t += "<tbody>";
										for(var key in jsondata['omzetperrit']) {
											var o = jsondata['omzetperrit'][key]['opbrengst'];
											var n = jsondata['omzetperrit'][key]['nummer'];
											var totaal = jsondata['totaal'];
											
											t += "<tr><th>"+n+"</th><td>"+setmoneyvaleu('returnvalue',o)+"</td><td>"+setmoneyvaleu('returnvalue',totaal)+"</td></tr>";											
										}
										
									t += "</tbody>";
								t += "</table>";

								var options = {
									   chart: {
										  renderTo: 'omzet',
										  defaultSeriesType: 'column'
									   },
									   title: {
										  text: 'Omzet van '+dag
									   },
									   xAxis: {
										  title: {
											 text: 'rit'
										  }					   
									   },
									   yAxis: {
										  title: {
											 text: 'euro'
										  }
									   },
									   tooltip: {
										  formatter: function() {
										  
											var euro =  this.y*100;
												euro = setmoneyvaleu('returnvalue',euro);
											 return '<b>'+ this.series.name +'</b><br/>'+
												'' + euro +' euro ('+ this.x.toLowerCase()+')';
										  }
									   }
									};

								Highcharts.visualize(t, options);
								
							}
							else{
								alert(jsondata['fout']);
							}

						}
					});	
					
				}
				else{
					alert('reportage onbekend');
				}
			  }
			});
		
		}
		else{ // per rit
			var stations;
			$.ajax({
			  url: '/json/stations',
			  dataType: 'json',
			  success: function(data) {
				stations = data;
				if(ritid != '0'){
					$.ajax({
					url: '/json/reporting/omzet/rit/'+ritid,
					dataType: 'json',
					success: function(jsondata) {
							if(jsondata['returncode'] == '200'){
								var t = "<table>";
								t += "<thead>";
									t += "<tr><th></th><th>verkocht</th></tr>";
								t += "</thead>";
									t += "<tbody>";
										var n = "";
										for(var key in jsondata['omzetperrit']) {
											var o = jsondata['omzetperrit'][key]['opbrengst'];
											n = jsondata['omzetperrit'][key]['nummer'];
											t += "<tr><th>"+n+"</th><td>"+setmoneyvaleu('returnvalue',o)+"</td></tr>";
										}
									t += "</tbody>";
								t += "</table>";

								var options = {
									   chart: {
										  renderTo: 'omzet',
										  defaultSeriesType: 'column'
									   },
									   title: {
										  text: 'Omzet van rit: '+n
									   },
									   xAxis: {
										  title: {
											 text: 'rit'
										  }					   
									   },
									   yAxis: {
										  title: {
											 text: 'euro'
										  }
									   },
									   tooltip: {
										  formatter: function() {
										  
											var euro =  this.y*100;
												euro = setmoneyvaleu('returnvalue',euro);
											 return '<b>'+ this.series.name +'</b><br/>'+
												'' + euro +' euro';
										  }
									   }
									};

								Highcharts.visualize(t, options);								
							}
							else{
								alert(jsondata['fout']);
							}

						}
					});	
					
				}
				else{
					alert('reportage onbekend');
				}
			  }
			});			
		}
		
	}
	else{
		// omzet per periode
		var periode = periode.replace(/\//gi, '-');
		var toonperiode = periode.replace(/_/gi, ' t/m ');
		$.ajax({
		url: '/json/reporting/omzet/periode/('+periode+')/'+treinsoort+'/'+reseller,
		dataType: 'json',
		success: function(jsondata) {
				if(jsondata['returncode'] == '200'){
					var t = "<table>";
					t += "<thead>";
						t += "<tr><th></th><th>omzet per dag</th><th>gemiddelde omzet</th></tr>";
					t += "</thead>";
						t += "<tbody>";
							for(var key in jsondata['omzetperrit']) {
								var dag = jsondata['omzetperrit'][key]['dag'];
								var omzet = jsondata['omzetperrit'][key]['omzet'];
								var gem = jsondata['gemiddelde'];
								t += "<tr><th>"+dag+"</th><td>"+setmoneyvaleu('returnvalue',omzet)+"</td><td>"+setmoneyvaleu('returnvalue',gem)+"</td></tr>";
							}
						t += "</tbody>";
					t += "</table>";

					var options = {
						   chart: {
							  renderTo: 'omzet',
							  defaultSeriesType: 'line'
						   },
						   title: {
							  text: 'Omzet van '+toonperiode
						   },						   
						   xAxis: {
							tickInterval: 5,
							  title: {
								 text: 'periode'
							  }					    
						   },
						   yAxis: {
							  title: {
								 text: 'omzet (euro)'
							  }
						   },
						   tooltip: {
							  formatter: function() {
								var euro =  this.y*100;
									euro = setmoneyvaleu('returnvalue',euro);
								 return '<b>'+ this.series.name +'</b><br/>'+
									'' + euro +' euro';
							  }
						   }
						};

					Highcharts.visualize(t, options);
				}
				else{
					alert(jsondata['fout']);
				}

			}
		});	
			
		
	
	}
}

function showordersuser(userid){
	makeGetRequest('/xml/maintenance/ticketing/userorders/', userid,'processshowordersuser');	
}

function processshowordersuser(xmldata){

	var html = "<table class=\"windowoverzicht\" width=\"100%\" cellpadding=\"4\" cellspacing=\"0\" border=\"0\">";
	html += "<tr><th>Order</th><th>Achternaam</th><th>Datum</th><th>Betaald</th></tr>";
		$(xmldata).find("orders").find("entry").each(function(){
			
			var orderid = $(this).find("orderid").text();
			var naam = $(this).find("naam").text();
			var datum = $(this).find("datum").text();
			var factuurbedrag = $(this).find("factuurbedrag").text();
			
			
			
			html += "<tr onclick=\"switchtodetails('"+orderid+"');\"><td>"+orderid+"</td><td>"+naam+"</td><td>"+datum+"</td><td>"+factuurbedrag+"</td></tr>";
		});		
	
		html += "</table>";


	infowindow('Overzicht orders per gebruiker',html);
	$('#contentwindow').css('width','500px');
	
		
}

function switchtodetails(orderid){
	$('#infowindow').remove(); 
	$('#contentwindow').remove(); 
	ticketdetails(orderid);
}


var openmailtab = "-1";

function openmailtabf(taal){
	if(openmailtab != taal && openmailtab != '-1'){
		$('#tab'+openmailtab).css('display','none');
	}
	
	$('#tab'+taal).css('display','block');
	openmailtab = taal;
	
}

function changemailtxt(mailid){
	var html = "";
	
		$.ajax({
		url: '/json/standardmails/'+mailid,
		dataType: 'json',
		success: function(jsondata) {
				if(jsondata['returncode'] == '200'){	
					html += "<form id=\"emailmsg\">";
						html += "<fieldset><legend>Email instellingen</legend><table>";
							html += "<tr><td>Naam</td></tr>";
							html += "<tr><td><input type=\"text\" name=\"name\" value=\""+jsondata['mail']['author_name']+"\" /></td></tr>";
							html += "<tr><td>Email</td></tr>";
							html += "<tr><td><input type=\"text\" name=\"email\" value=\""+jsondata['mail']['author_email']+"\" /></td></tr>";
						html += "</table></fieldset>";
					
						html += "<fieldset><legend><a href=\"#\" onclick=\"openmailtabf('nl');\">Nederlands</a></legend><table id=\"tabnl\" style=\"display:none;\">";
							html += "<tr><td>Mail onderwerp</td></tr>";
							html += "<tr><td><input type=\"text\" name=\"subject_nl\" value=\""+jsondata['mail']['subject_nl']+"\"></td></tr>";
							html += "<tr><td>Mail tekst</td></tr>";
							html += "<tr><td><textarea name=\"mail_nl\">"+jsondata['mail']['mail_nl']+"</textarea></td></tr>";
						html += "</table></fieldset>";

						html += "<fieldset><legend><a href=\"#\" onclick=\"openmailtabf('de');\">Duits</a></legend><table id=\"tabde\" style=\"display:none;\">";
							html += "<tr><td>Mail onderwerp</td></tr>";
							html += "<tr><td><input type=\"text\" name=\"subject_de\" value=\""+jsondata['mail']['subject_de']+"\"></td></tr>";
							html += "<tr><td>Mail tekst</td></tr>";
							html += "<tr><td><textarea name=\"mail_de\">"+jsondata['mail']['mail_de']+"</textarea></td></tr>";
						html += "</table></fieldset>";
						
						html += "<fieldset><legend><a href=\"#\" onclick=\"openmailtabf('en');\">Engels</a></legend><table id=\"taben\" style=\"display:none;\">";
							html += "<tr><td>Mail onderwerp</td></tr>";
							html += "<tr><td><input type=\"text\" name=\"subject_en\" value=\""+jsondata['mail']['subject_en']+"\"></td></tr>";
							html += "<tr><td>Mail tekst</td></tr>";
							html += "<tr><td><textarea name=\"mail_en\">"+jsondata['mail']['mail_en']+"</textarea></td></tr>";
						html += "</table></fieldset>";
							
						html += "<fieldset><legend><a href=\"#\" onclick=\"openmailtabf('fr');\">Fries</a></legend><table id=\"tabfr\" style=\"display:none;\">";
							html += "<tr><td>Mail onderwerp</td></tr>";
							html += "<tr><td><input type=\"text\" name=\"subject_fr\" value=\""+jsondata['mail']['subject_fr']+"\"></td></tr>";
							html += "<tr><td>Mail tekst</td></tr>";
							html += "<tr><td><textarea name=\"mail_fr\">"+jsondata['mail']['mail_fr']+"</textarea></td></tr>";
						html += "</table></fieldset>";
						
						
						html += "<div align=\"right\"><input type=\"button\" value=\"wijzigen\" class=\"button\" style=\"width:100px;\" onclick=\"savemailtxt('"+mailid+"');\" /></div>";
					html += "</form>";
					infowindow('Standaard emailteksten wijzigen',html);
					$('#contentwindow').css('width','350px');	

				}
				else{
					alert(jsondata['fout']);
				}

			}
		});	
	
}

function savemailtxt(mailid){
	$('#tabnl').css('display','block');
	$('#tabde').css('display','block');
	$('#taben').css('display','block');
	$('#tabfr').css('display','block');

	makePostRequest('/json/standardmails/'+mailid, $("#emailmsg").serialize(),'pagereload');

	$('#infowindow').remove(); 
	$('#contentwindow').remove(); 	
}

function calendarreporting(response,target){
	var v = response.value;
	
	$('#'+target).attr('value',v);
	var dagu = v.replace(/\//gi, '-');
		
	if(target == "omzet_reporting_dag"){
		var t = "omzet_reporting_rit";
	}
	else{
		var t = "reporting_rit";
	}	
	
	if(target == 'reporting_dag' || target == 'omzet_reporting_dag'){
		$('#'+t).empty();		
		$('#'+t).append('<option value=\"-1\">gehele dag</option>');
		$('#'+t).attr('disabled','');
				
		$.ajax({
		url: '/json/ritten/'+dagu,
		dataType: 'json',
		success: function(jsondata){
			if(jsondata['returncode'] == '200'){

				var ritten = "";
				for(var key in jsondata['ritten']) {
					var ritid = jsondata['ritten'][key]['rit_id'];
					var treinnummer = jsondata['ritten'][key]['treinnummer'];
					var tijd = jsondata['ritten'][key]['tijd'];
										
					$('#'+t).append('<option value=\"'+ritid+'\">'+treinnummer+' - '+tijd+' uur</option>');
				} 					
			
			}
			else{
				alert(jsondata['fout']);
			}
		}
		});		
	}
}

var bkortingid = 0;
function savepromotion(formid,soortopslag){
	var d = new Date();
	var maandnu  = d.getMonth()+1;
	var dagnu = d.getDate();
	var jaarnu = d.getFullYear();
	
	var nowtimestamp = mktime(0,0,0,maandnu,dagnu,jaarnu);
	
	if(formid == 'formvoucher'){
		
		var code = $('#promotionvoucher #code').attr('value');
		var soort = $('#promotionvoucher #actiesoort').attr('value');
		var waarde = $('#promotionvoucher #waarde').attr('value');
		var uitgiftes = $('#promotionvoucher #aantaluitgiftes').attr('value');
		var dag = $('#promotionvoucher #dag').attr('value');
		var maand = $('#promotionvoucher #maand').attr('value');
		var jaar = $('#promotionvoucher #jaar').attr('value');
		
		var promotiontimestamp = mktime(0, 0, 0, maand, dag, jaar);
				
	}
	else if(formid == 'formactiecode'){
		
		var code = $('#promotionactiecode #code').attr('value');
		var soort = $('#promotionactiecode #actiesoort').attr('value');
		var waarde = $('#promotionactiecode #waarde').attr('value');
		var uitgiftes = $('#promotionactiecode #aantaluitgiftes').attr('value');
		var dag = $('#promotionactiecode #dag').attr('value');
		var maand = $('#promotionactiecode #maand').attr('value');
		var jaar = $('#promotionactiecode #jaar').attr('value');
		
		var promotiontimestamp = mktime(0, 0, 0, maand, dag, jaar);
				
	}	
	else{
		alert('formid: '+formid+' is onbekend');
		return false;
	}

	if(promotiontimestamp < nowtimestamp){
		alert('De door u ingevulde datum ligt in het verleden. Deze datum moet minimaal die van vandaag zijn.');
		return false;
	}

	
	//afhandeling
	
	if(code == ''){
		alert('U heeft geen promotiecode ingevoerd');
		return false;
	}
	if(code.length != 6){
		alert('De promotiecode dient 6 karakters te zijn');
		return false;
	}	
	else{
		if(waarde == ''){
			alert('U heeft geen waarde ingevoerd');
			return false;		
		}
		else{
		
			if(soort == 'percentage'){ //percentage
				if((parseFloat(waarde) == parseInt(waarde)) && !isNaN(waarde)){
					if(waarde > 100){
						alert('Het door u ingevoerde kortingspercentage is te hoog. (max. 100)');
						return false;
					}
					else if(waarde < 0){
						alert('Het door u ingevoerde kortingspercentage is te laag. (min. 100)');
						return false;				
					}
					else{
						
						if(uitgiftes == ''){
							alert('U dient het maximale aantal uitgiftes in te voeren.');
							return false;		
						}
						else{
							if((parseFloat(uitgiftes) == parseInt(uitgiftes)) && !isNaN(uitgiftes)){
								
								//hier wordt de code op zijn uniekheid gecontroleerd
								
								$.ajax({
								url: '/json/checkpromotion/'+code,
								dataType: 'json',
								success: function(jsondata){
									if(jsondata['returncode'] == '200'){
										if(jsondata['validpromotion'] === true && soortopslag == 'insert'){
											alert('Deze promotiecode werd al eerder gebruikt, voer een andere code in');
										}
										else{
											//versturen
											if(soortopslag == 'insert'){
												makePostRequest('/xml/maintenance/ticketing/promotion/create/'+formid, $("#"+formid).serialize(),'pagereload');	
											}
											else if(soortopslag == 'update'){
												makePostRequest('/xml/maintenance/ticketing/promotion/update/'+formid+"/"+bkortingid, $("#"+formid).serialize(),'pagereload');	
											}
											
										}
									}
									else{
										alert('er is een fout opgetreden bij de controle van de promotie code');
									}
								}
								});									
							}	
							else{
								alert('De maximale aantal uitgiftes mag alleen bestaan uit een numerieke [0-9] invoer ');
								return false;								
							}
						}
					}
				}
				else{
					alert('De ingevoerde waarde mag alleen bestaan uit een numerieke [0-9] invoer ');
					return false;					
				}
			}
			else{ //vast bedrag
				if((parseFloat(waarde) == parseInt(waarde)) && !isNaN(waarde)){
					if(waarde < 0){
						alert('Het door u ingevoerde korting is te laag. (min. 1 cent)');
						return false;				
					}
					else{
						
						if(uitgiftes == ''){
							alert('U dient het maximale aantal uitgiftes in te voeren.');
							return false;		
						}
						else{
							if((parseFloat(uitgiftes) == parseInt(uitgiftes)) && !isNaN(uitgiftes)){
								
								//hier wordt de code op zijn uniekheid gecontroleerd
								
								$.ajax({
								url: '/json/checkpromotion/'+code,
								dataType: 'json',
								success: function(jsondata){
									if(jsondata['returncode'] == '200'){
										if(jsondata['validpromotion'] === true  && soortopslag == 'insert'){
											alert('Deze promotiecode werd al eerder gebruikt, voer een andere code in');
										}
										else{
											//versturen
										//	makePostRequest('/xml/maintenance/ticketing/promotion/create/'+formid, $("#"+formid).serialize(),'pagereload');	
										
											if(soortopslag == 'insert'){
												makePostRequest('/xml/maintenance/ticketing/promotion/create/'+formid, $("#"+formid).serialize(),'pagereload');	
											}
											else if(soortopslag == 'update'){
												makePostRequest('/xml/maintenance/ticketing/promotion/update/'+formid+"/"+bkortingid, $("#"+formid).serialize(),'pagereload');	
											}										
										
										}
									}
									else{
										alert('er is een fout opgetreden bij de controle van de promotie code');
									}
								}
								});									
																
							}	
							else{
								alert('De maximale aantal uitgiftes mag alleen bestaan uit een numerieke [0-9] invoer ');
								return false;								
							}
						}
					}
				}
				else{
					alert('De ingevoerde waarde mag alleen bestaan uit een numerieke [0-9] invoer ');
					return false;					
				}			
			}
				
		}
	}
		
}

function mktime(){
    var d = new Date(),
        r = arguments,
        i = 0,
        e = ['Hours', 'Minutes', 'Seconds', 'Month', 'Date', 'FullYear']; 
		
    for (i = 0; i < e.length; i++) {
        if (typeof r[i] === 'undefined') {
            r[i] = d['get' + e[i]]();
            r[i] += (i === 3); 
			} else {
            r[i] = parseInt(r[i], 10);
            if (isNaN(r[i])) {
                return false;
            }        
		}
    }

    r[5] += (r[5] >= 0 ? (r[5] <= 69 ? 2e3 : (r[5] <= 100 ? 1900 : 0)) : 0); 
    d.setFullYear(r[5], r[3] - 1, r[4]);
    d.setHours(r[0], r[1], r[2]);
	return (d.getTime() / 1e3 >> 0) - (d.getTime() < 0);

}





function newpromotion(){

	var d = new Date();
	var maandnu  = d.getMonth()+1;
	var dagnu = d.getDate();
	var jaarnu = d.getFullYear();

	var html = "";
		html = html+"<fieldset style=\"margin-bottom:10px;\"><legend><strong>Kies promotie type</strong></legend><table cellpadding=\"4\" cellspacing=\"0\" border=\"0\">";
			html = html+"<tr><td valign=\"top\"><input type=\"radio\" name=\"promotiontype\" value=\"promotionvoucher\" style=\"border:0px;width:20px;\" onclick=\"promotionchoice(this);\" /></td><td valign=\"top\"><div style=\"margin-top:2px;\">Voucher</div></td></tr>";	
			html = html+"<tr><td valign=\"top\"><input type=\"radio\" name=\"promotiontype\" value=\"promotionactiecode\" style=\"border:0px;width:20px;\" onclick=\"promotionchoice(this);\" /></td><td valign=\"top\"><div style=\"margin-top:2px;\">Actiecode</div></td></tr>";	
		html = html+"</table></fieldset>";	
	
		html = html+"<div id=\"promotionvoucher\" class=\"newpromotion\"><fieldset style=\"margin-bottom:10px;\"><legend><strong>Voucher aanmaken</strong></legend>";
			html = html+"<form id=\"formvoucher\" name=\"formvoucher\" method=\"post\" action=\"\">";	
				html = html+"<table cellpadding=\"2\" cellspacing=\"0\" border=\"0\">";
					html = html+"<tr><td>Voucher code</td><td><input style=\"width:80px;margin-top:10px;\" type=\"text\" id=\"code\" name=\"code\" maxlength=\"6\"/></td></tr>";
					html = html+"<tr><td>Actiesoort</td><td><select style=\"width:100px;margin-top:10px;\" id=\"actiesoort\" name=\"actiesoort\" onchange=\"setdeel('formvoucher',this);\"><option value=\"percentage\">percentage</option><option value=\"vastbedrag\">vaste waarde</option></select></td></tr>";
					html = html+"<tr><td>Waarde</td><td><input style=\"width:80px;margin-top:10px;\" type=\"text\" id=\"waarde\" name=\"waarde\" maxlength=\"6\"/> <span id=\"deel\">%</span></td></tr>";
					html = html+"<tr><td>Geldig t/m</td><td><table style=\"margin-top:10px;\" cellpadding=\"1\" cellspacing=\"0\" border=\"0\"><tr><td><select id=\"dag\" name=\"dag\" style=\"width:40px;\">";
						var i = 1;
						while (i<=31){
							if(i == dagnu){
								html = html+"<option value=\""+i+"\" selected=\"selected\">"+i+"</option>";
							}
							else{
								html = html+"<option value=\""+i+"\">"+i+"</option>";
							}
							i++;
						}												
					html = html+"</select></td><td><select id=\"maand\" name=\"maand\" style=\"width:40px;\">";
						var i = 1;
						while (i<=12){
							if(i == maandnu){
								html = html+"<option value=\""+i+"\" selected=\"selected\">"+i+"</option>";
							}
							else{						
								html = html+"<option value=\""+i+"\">"+i+"</option>";
							}
							i++;
						}												
					html = html+"</select></td><td><select id=\"jaar\" name=\"jaar\" style=\"width:80px;\">";
						var i = 2011;
						while (i<=2020){
							if(i == jaarnu){
								html = html+"<option value=\""+i+"\" selected=\"selected\">"+i+"</option>";
							}
							else{
								html = html+"<option value=\""+i+"\">"+i+"</option>";
							}
							i++;
						}												
					html = html+"</select></td></tr></table></td></tr>";
					html = html+"<tr><td>Aantal uitgiftes</td><td><input style=\"width:80px;margin-top:10px;\" type=\"text\" id=\"aantaluitgiftes\" name=\"aantaluitgiftes\" maxlength=\"6\"/></td></tr>";
				html = html+"</table>"; 
				html = html+"<div align=\"right\"><input style=\"width:100px;\" type=\"button\" value=\"aanmaken\" onclick=\"savepromotion('formvoucher','insert');\" /></div>"; 
			html = html+"</form>";	
		html = html+"</fieldset></div>";
		
		html = html+"<div id=\"promotionactiecode\" class=\"newpromotion\"><fieldset style=\"margin-bottom:10px;\"><legend><strong>Actiecode aanmaken</strong></legend>";
			html = html+"<form id=\"formactiecode\" name=\"formactiecode\" method=\"post\" action=\"\">";	
				html = html+"<table cellpadding=\"2\" cellspacing=\"0\" border=\"0\">";
					html = html+"<tr><td>Actiecode</td><td><input style=\"width:80px;margin-top:10px;\" type=\"text\" id=\"code\" name=\"code\" maxlength=\"6\"/></td></tr>";
					html = html+"<tr><td>Actiesoort</td><td><select style=\"width:100px;margin-top:10px;\" id=\"actiesoort\" name=\"actiesoort\" onchange=\"setdeel('formactiecode',this);\"><option value=\"percentage\">percentage</option><option value=\"vastbedrag\">vaste waarde</option></select></td></tr>";
					html = html+"<tr><td>Waarde</td><td><input style=\"width:80px;margin-top:10px;\" type=\"text\" id=\"waarde\" name=\"waarde\" maxlength=\"6\"/> <span id=\"deel\">%</span></td></tr>";
					html = html+"<tr><td>Geldig t/m</td><td><table style=\"margin-top:10px;\" cellpadding=\"1\" cellspacing=\"0\" border=\"0\"><tr><td><select id=\"dag\" name=\"dag\" style=\"width:40px;\">";
						var i = 1;
						while (i<=31){
							if(i == dagnu){
								html = html+"<option value=\""+i+"\" selected=\"selected\">"+i+"</option>";
							}
							else{
								html = html+"<option value=\""+i+"\">"+i+"</option>";
							}
							i++;
						}												
					html = html+"</select></td><td><select id=\"maand\" name=\"maand\" style=\"width:40px;\">";
						var i = 1;
						while (i<=12){
							if(i == maandnu){
								html = html+"<option value=\""+i+"\" selected=\"selected\">"+i+"</option>";
							}
							else{						
								html = html+"<option value=\""+i+"\">"+i+"</option>";
							}
							i++;
						}												
					html = html+"</select></td><td><select id=\"jaar\" name=\"jaar\" style=\"width:80px;\">";
						var i = 2011;
						while (i<=2020){
							if(i == jaarnu){
								html = html+"<option value=\""+i+"\" selected=\"selected\">"+i+"</option>";
							}
							else{
								html = html+"<option value=\""+i+"\">"+i+"</option>";
							}
							i++;
						}												
					html = html+"</select></td></tr></table></td></tr>";
					html = html+"<tr><td>Aantal uitgiftes</td><td><input style=\"width:80px;margin-top:10px;\" type=\"text\" id=\"aantaluitgiftes\" name=\"aantaluitgiftes\" maxlength=\"6\"/></td></tr>";
				html = html+"</table>"; 
				html = html+"<div align=\"right\"><input style=\"width:100px;\" type=\"button\" value=\"aanmaken\" onclick=\"savepromotion('formactiecode','insert');\" /></div>"; 
			html = html+"</form>";			
		html = html+"</fieldset></div>";			
	
	infowindow('Nieuwe promotie aanmaken',html);
	$('#contentwindow').css('width','300px');
	
}

function setdeel(formid, w){
	if(w.value == 'percentage'){
		var d = "%";
	}
	else{
		var d = "centen";
	}
	
	$('#'+formid+' #deel').html(d);
	
}

function editpromotion(promotionid){
	makeGetRequest('/xml/maintenance/ticketing/promotion/edit/', promotionid,'editpromotion2');	
}


function phpgetdate(timestamp){

    var _m = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
    var d = ((typeof(timestamp) == 'undefined') ? new Date() :  (typeof(timestamp) == 'object') ? new Date(timestamp) :  new Date(timestamp * 1000));
    var w = d.getDay();
    var m = d.getMonth();
    var y = d.getFullYear();
    var r = {}; 
    r.seconds = d.getSeconds();
    r.minutes = d.getMinutes();
    r.hours = d.getHours();
    r.mday = d.getDate();    r.wday = w;
    r.mon = m + 1;
    r.year = y;
    r.yday = Math.floor((d - (new Date(y, 0, 1))) / 86400000);
    r.weekday = w[w];    r.month = _m[m];
    r['0'] = parseInt(d.getTime() / 1000, 10);
 
    return r;
}

var openprlist = "-";
function editpromotion2(xmldata){
	$(xmldata).find("promotie").find("entry").each(function(){

		
	
		var maandnu  = "-";
		var dagnu = "-";
		var jaarnu = "-";
		
		var korting_id = $(this).find("korting_id").text();
			bkortingid = korting_id;
		
		var voucher = $(this).find("voucher").text();
		var actiecode = $(this).find("actiecode").text();
		
		var percentage = $(this).find("percentage").text();
		var vastbedrag = $(this).find("vastbedrag").text();
		
		var waarde = $(this).find("waarde").text();
		var code = $(this).find("code").text();
		
		var geldig = $(this).find("geldig").text();
		var ge = phpgetdate(geldig);

		maandnu = ge['mon'];
		dagnu = ge['mday'];
		jaarnu = ge['year'];
		
		
		var status = $(this).find("status").text();
		
		var aantaluitgiftes = $(this).find("aantaluitgiftes").text();
		
		var html = "";
		if(voucher == '1' || actiecode == '1'){

			html = html+"<fieldset style=\"margin-bottom:10px;\"><legend><strong>Kies promotie type</strong></legend><table cellpadding=\"4\" cellspacing=\"0\" border=\"0\">";
				if(voucher == '1'){
					openprlist = "voucher";
					html = html+"<tr><td valign=\"top\"><input type=\"radio\" name=\"promotiontype\" value=\"promotionvoucher\" style=\"border:0px;width:20px;\" checked=\"checked\" onclick=\"promotionchoice(this);\" /></td><td valign=\"top\"><div style=\"margin-top:2px;\">Voucher</div></td></tr>";	
				}
				else{
					html = html+"<tr><td valign=\"top\"><input type=\"radio\" name=\"promotiontype\" value=\"promotionvoucher\" style=\"border:0px;width:20px;\" onclick=\"promotionchoice(this);\" /></td><td valign=\"top\"><div style=\"margin-top:2px;\">Voucher</div></td></tr>";	
				}
				
				if(actiecode == '1'){
					openprlist = "actiecode";
					html = html+"<tr><td valign=\"top\"><input type=\"radio\" name=\"promotiontype\" value=\"promotionactiecode\" style=\"border:0px;width:20px;\" checked=\"checked\" onclick=\"promotionchoice(this);\" /></td><td valign=\"top\"><div style=\"margin-top:2px;\">Actiecode</div></td></tr>";	
				}
				else{
					html = html+"<tr><td valign=\"top\"><input type=\"radio\" name=\"promotiontype\" value=\"promotionactiecode\" style=\"border:0px;width:20px;\" onclick=\"promotionchoice(this);\" /></td><td valign=\"top\"><div style=\"margin-top:2px;\">Actiecode</div></td></tr>";	
				}
			html = html+"</table></fieldset>";	
		
			html = html+"<div id=\"promotionvoucher\" class=\"newpromotion\"><fieldset style=\"margin-bottom:10px;\"><legend><strong>Voucher wijzigen</strong></legend>";
				html = html+"<form id=\"formvoucher\" name=\"formvoucher\" method=\"post\" action=\"\">";	
					html = html+"<table cellpadding=\"2\" cellspacing=\"0\" border=\"0\">";
						html = html+"<tr><td>Voucher code</td><td><input style=\"width:80px;margin-top:10px;\" type=\"text\" id=\"code\" name=\"code\" value=\""+code+"\" maxlength=\"6\"/></td></tr>";
						
						if(percentage == '1'){
							html = html+"<tr><td>Actiesoort</td><td><select style=\"width:100px;margin-top:10px;\" id=\"actiesoort\" name=\"actiesoort\" onchange=\"setdeel('formvoucher',this);\"><option value=\"percentage\">percentage</option><option value=\"vastbedrag\">vaste waarde</option></select></td></tr>";
							html = html+"<tr><td>Waarde</td><td><input style=\"width:80px;margin-top:10px;\" type=\"text\" id=\"waarde\" name=\"waarde\" maxlength=\"6\" value=\""+waarde+"\"/> <span id=\"deel\">%</span></td></tr>";
						}
						else{
							html = html+"<tr><td>Actiesoort</td><td><select style=\"width:100px;margin-top:10px;\" id=\"actiesoort\" name=\"actiesoort\" onchange=\"setdeel('formvoucher',this);\"><option value=\"percentage\">percentage</option><option selected=\"selected\" value=\"vastbedrag\">vaste waarde</option></select></td></tr>";
							html = html+"<tr><td>Waarde</td><td><input style=\"width:80px;margin-top:10px;\" type=\"text\" id=\"waarde\" name=\"waarde\" maxlength=\"6\" value=\""+waarde+"\"/> <span id=\"deel\">euro</span></td></tr>";						
						}
						
						html = html+"<tr><td>Geldig t/m</td><td><table style=\"margin-top:10px;\" cellpadding=\"1\" cellspacing=\"0\" border=\"0\"><tr><td><select id=\"dag\" name=\"dag\" style=\"width:40px;\">";
							var i = 1;
							while (i<=31){
								if(i == dagnu){
									html = html+"<option value=\""+i+"\" selected=\"selected\">"+i+"</option>";
								}
								else{
									html = html+"<option value=\""+i+"\">"+i+"</option>";
								}
								i++;
							}												
						html = html+"</select></td><td><select id=\"maand\" name=\"maand\" style=\"width:40px;\">";
							var i = 1;
							while (i<=12){
								if(i == maandnu){
									html = html+"<option value=\""+i+"\" selected=\"selected\">"+i+"</option>";
								}
								else{						
									html = html+"<option value=\""+i+"\">"+i+"</option>";
								}
								i++;
							}												
						html = html+"</select></td><td><select id=\"jaar\" name=\"jaar\" style=\"width:80px;\">";
							var i = 2011;
							while (i<=2020){
								if(i == jaarnu){
									html = html+"<option value=\""+i+"\" selected=\"selected\">"+i+"</option>";
								}
								else{
									html = html+"<option value=\""+i+"\">"+i+"</option>";
								}
								i++;
							}												
						html = html+"</select></td></tr></table></td></tr>";
						html = html+"<tr><td>Aantal uitgiftes</td><td><input style=\"width:80px;margin-top:10px;\" type=\"text\" id=\"aantaluitgiftes\" name=\"aantaluitgiftes\" value=\""+aantaluitgiftes+"\" maxlength=\"6\"/></td></tr>";
					html = html+"</table>"; 
					html = html+"<div align=\"right\"><input style=\"width:100px;\" type=\"button\" value=\"wijzigen\" onclick=\"savepromotion('formvoucher','update');\" /></div>"; 
				html = html+"</form>";	
			html = html+"</fieldset></div>";
			
			html = html+"<div id=\"promotionactiecode\" class=\"newpromotion\"><fieldset style=\"margin-bottom:10px;\"><legend><strong>Actiecode aanmaken</strong></legend>";
				html = html+"<form id=\"formactiecode\" name=\"formactiecode\" method=\"post\" action=\"\">";	
					html = html+"<table cellpadding=\"2\" cellspacing=\"0\" border=\"0\">";
						html = html+"<tr><td>Actiecode</td><td><input style=\"width:80px;margin-top:10px;\" type=\"text\" id=\"code\" name=\"code\" value=\""+code+"\" maxlength=\"6\"/></td></tr>";
						if(percentage == '1'){
							html = html+"<tr><td>Actiesoort</td><td><select style=\"width:100px;margin-top:10px;\" id=\"actiesoort\" name=\"actiesoort\" onchange=\"setdeel('formactiecode',this);\"><option value=\"percentage\">percentage</option><option value=\"vastbedrag\">vaste waarde</option></select></td></tr>";
							html = html+"<tr><td>Waarde</td><td><input style=\"width:80px;margin-top:10px;\" type=\"text\" id=\"waarde\" name=\"waarde\" maxlength=\"6\" value=\""+waarde+"\"/> <span id=\"deel\">%</span></td></tr>";
						}
						else{
							html = html+"<tr><td>Actiesoort</td><td><select style=\"width:100px;margin-top:10px;\" id=\"actiesoort\" name=\"actiesoort\" onchange=\"setdeel('formactiecode',this);\"><option value=\"percentage\">percentage</option><option selected=\"selected\" value=\"vastbedrag\">vaste waarde</option></select></td></tr>";
							html = html+"<tr><td>Waarde</td><td><input style=\"width:80px;margin-top:10px;\" type=\"text\" id=\"waarde\" name=\"waarde\" maxlength=\"6\" value=\""+waarde+"\"/> <span id=\"deel\">euro</span></td></tr>";						
						}
						html = html+"<tr><td>Geldig t/m</td><td><table style=\"margin-top:10px;\" cellpadding=\"1\" cellspacing=\"0\" border=\"0\"><tr><td><select id=\"dag\" name=\"dag\" style=\"width:40px;\">";
							var i = 1;
							while (i<=31){
								if(i == dagnu){
									html = html+"<option value=\""+i+"\" selected=\"selected\">"+i+"</option>";
								}
								else{
									html = html+"<option value=\""+i+"\">"+i+"</option>";
								}
								i++;
							}												
						html = html+"</select></td><td><select id=\"maand\" name=\"maand\" style=\"width:40px;\">";
							var i = 1;
							while (i<=12){
								if(i == maandnu){
									html = html+"<option value=\""+i+"\" selected=\"selected\">"+i+"</option>";
								}
								else{						
									html = html+"<option value=\""+i+"\">"+i+"</option>";
								}
								i++;
							}												
						html = html+"</select></td><td><select id=\"jaar\" name=\"jaar\" style=\"width:80px;\">";
							var i = 2011;
							while (i<=2020){
								if(i == jaarnu){
									html = html+"<option value=\""+i+"\" selected=\"selected\">"+i+"</option>";
								}
								else{
									html = html+"<option value=\""+i+"\">"+i+"</option>";
								}
								i++;
							}												
						html = html+"</select></td></tr></table></td></tr>";
						html = html+"<tr><td>Aantal uitgiftes</td><td><input style=\"width:80px;margin-top:10px;\" type=\"text\" id=\"aantaluitgiftes\" name=\"aantaluitgiftes\"  value=\""+aantaluitgiftes+"\" maxlength=\"6\"/></td></tr>";
					html = html+"</table>"; 
					html = html+"<div align=\"right\"><input style=\"width:100px;\" type=\"button\" value=\"wijzigen\" onclick=\"savepromotion('formactiecode','update');\" /></div>"; 
				html = html+"</form>";			
			html = html+"</fieldset></div>";		
		
			html = html+"<div id=\"mailen\"><fieldset style=\"margin-bottom:10px;\"><legend><strong>Promotie mailen</strong></legend>";
				html = html+"<form id=\"mailvoucher\" action=\"#\" method=\"post\"><table>";
					html = html+"<tr><td>Uw naam<br/><input type=\"text\" name=\"uwnaam\" style=\"width:260px\" /></td></tr>";
					html = html+"<tr><td>Uw email<br/><input type=\"text\" name=\"uwemail\" style=\"width:260px\" /></td></tr>";
					html = html+"<tr><td>Email ontvanger<br/><input type=\"text\"  name=\"ontvanger\" style=\"width:260px\" /></td></tr>";
					html = html+"<tr><td>E-mail bericht<br/><textarea name=\"bericht\" style=\"width:260px\">Geachte heer/mevrouw,\n\r Hierbij ontvangt u de actiecode voor de Friese Stoomtrein Maatschappij;\n\r Uw actiecode: "+code+" \n\r Met vriendelijke groet,\n\r</textarea></td></tr>";
				html = html+"</table></form>";
				html = html+"<div align=\"right\"><input style=\"width:100px;\" type=\"button\" value=\"versturen\" onclick=\"sendpromotion();\" /></div>"; 
			html = html+"</fieldset></div>";
		}
		else{
			html = "Deze promotie is geen voucher maar ook geen actiecode. U kunt deze op dit moment niet bewerken.";
		}
		
		callbackinfowindow = "callbackopenpromotionlist"; //roep na het laden de volgende functie aan 'callbackopenpromotionlist'
		infowindow('Promotie wijzigen',html);
		$('#contentwindow').css('width','300px');
		
	});
	
}

function sendpromotion(){
	makePostRequest('/xml/maintenance/ticketing/promotion/send', $("#mailvoucher").serialize(),'pagereload');	
}


var promotioncode = false;
function promotionchoice(v){
	if(promotioncode == false){
		var e = "#"+v.value;
		$(e).slideDown('Fast', function(){});
		promotioncode = e;
	}
	else{
		$(promotioncode).slideUp('Fast', function(){
			promotioncode = false;
			promotionchoice(v);
		});
	}
}


function callbackopenpromotionlist(){ //deze functie regelt de init van de bewerking. 
	if(openprlist == 'voucher'){
		promotioncode = "#promotionvoucher";
		$(promotioncode).slideDown('Fast', function(){});
	}
	else if(openprlist == 'actiecode'){
		promotioncode = "#promotionactiecode";		
		$(promotioncode).slideDown('Fast', function(){});
	}
	else{
		alert('Onbekende promotion list');
	}
}


var showpromo = "lopendepromoties";
function showpromotions(n){
	if(showpromo != n){
		$('#'+showpromo).css('display','none');
		$('#'+n).css('display','block');
		
		$('#btn'+showpromo).css('backgroundColor','');
		$('#btn'+n).css('backgroundColor','#ffffff');		
		
		
		showpromo = n;
	}
}

var reselleriddetails = 0;
function getresellerdetails(uid){
	reselleriddetails = uid;
	makeGetRequest('/xml/maintenance/ticketing/resellers/get/', uid,'resellerdetails');	
}


function resellerdetails(xmldata){
	
	var preselect = "0";
	$(xmldata).find("resellerid").each(function(){
		preselect = $(this).find("company").text();
	});
		
	$.ajax({
	url: '/json/resellers/',
	dataType: 'json',
	success: function(jsondata) {
		var pro = "0";
		var html = "";
			html = "<form method=\"post\" id=\"resellerdetails\"><table>";
				html += "<tr><td valign=\"top\">Bedrijf</td><td>";
					html += "<select id=\"bedrijf\" name=\"bedrijf\" onchange=\"setresellername(this);\">";	
					html += "<option value=\"-2\"></option>";
					for(var key in  jsondata['resellers']) {
						var rid = jsondata['resellers'][key]['reseller_id'];
						if(rid != '1'){
							var rname = jsondata['resellers'][key]['bedrijfsnaam'];
							var rprovisie = jsondata['resellers'][key]['provisie'];
							if(preselect == rid){
								html += "<option value=\""+rid+"||"+rprovisie+"\" selected=\"selected\">"+rname+"</option>";
								pro = rprovisie;
							}
							else{
								html += "<option value=\""+rid+"||"+rprovisie+"\">"+rname+"</option>";
							}
						}
					}
					html += "<option value=\"-1\">Nieuw bedrijf aanmaken</option>";
				html += "</select>";
				html += "<div id=\"newnamel\" style=\"display:none;\">Bedrijfsnaam: <input type=\"text\" id=\"newname\" name=\"newname\" value=\"\"></div>";
			html += "</td></tr>";
			html += "<tr><td valign=\"top\">Provicie</td><td><input type=\"text\" id=\"provisie\" name=\"provisie\" value=\""+pro+"\" style=\"width:100px;\"> %</td></tr>";
		html += "</table>";
		html += "<input type=\"hidden\" id=\"userid\" name=\"userid\" value=\""+reselleriddetails+"\" />";
		html += "<div align=\"right\"><input type=\"button\" value=\"wijzigen\" class=\"btn\" style=\"width:100px;\" onclick=\"saveresellerdata();\"></div></form>";
	
		infowindow('Reseller details',html);
		$('#contentwindow').css('width','500px');							
			
		}
	});						

}

function setresellername(n){

	$('#newnamel').css('display','none');
	if(n.value == '-1'){
		$('#newnamel').css('display','block');
		$('#provicie').attr('value','0');
	}
	else{
		var pr = n.value.split('||');
		if(pr[0] == '-2'){
			$('#provicie').attr('value','0');
		}
		else{
			$('#provicie').attr('value',pr[1]);
		}
	}
	
}

function saveresellerdata(){
	if($('#provisie').val() <= 100){
		makePostRequest('/xml/maintenance/ticketing/resellers/set', $("#resellerdetails").serialize(),'pagereload');		
	}
	else{
		alert('De provisie dient een percentage te zijn, van 0 tot 100 %');
	}
}

function toonafrekening(billid){
	$.ajax({
	url: '/json/billdetails/'+billid,
	dataType: 'json',
	success: function(jsondata) {
	
			var html = "<table width=\"100%\" cellpadding=\"4\" cellspacing=\"0\" class=\"windowoverzicht\">";
			var ci = 0;
			for(var key in  jsondata['afrekening']['bills'][billid]['orders']) {
				var boeking = jsondata['afrekening']['bills'][billid]['orders'][key]['boeking'];
				var factuur = jsondata['afrekening']['bills'][billid]['orders'][key]['totaal']/100;	
				var orderid = key;
				if(ci == 0){
					html += "<tr><th>Boeking</th><th>Factuurbedrag</th></tr>";
				}
				html += "<tr onclick=\"ticketdetails('"+orderid+"');\"><td>"+boeking+"</td><td>&euro; "+factuur+"</td></tr>";
				ci++;
			}
			html += "</table>";
			
			if(ci == 0){
				html = "Er zijn op dit moment geen order in deze periode gevonden";
			}
		
			infowindow('Order overzicht ('+billid+')',html);
			$('#contentwindow').css('width','500px');			

		}
	});	
	
}

