// variables //
var user_type = null;
var user_id = null;
var user_nm = null;
var user_pw = null;

var program_id = null;
var event_id = null;

var upload_target;
var upload_field;
var upload_indicator;
var upload_type;
var upload_ref;


// global functions //
function showLoader(indicator) {
	//new Effect.Appear($(indicator), {duration: 0.5});
	$(indicator).style.display = 'block';
}
function hideLoader(indicator){ 
	//new Effect.Fade($(indicator), {duration: 0.5});
	$(indicator).style.display = 'none';
}
function upload(form, target, field, filetype, extension, indicator) {
	upload_indicator = indicator;
	showLoader(upload_indicator);
	var filename = $F(field);
	if (filename == '') {
		return handleUploadError('Gelieve het bestand te selecteren die moet opgeladen worden.');
	}else if (extension == 'sound' && !fileIsSoundtrack(filename)) { 
		return handleUploadError('U dient een geluidsbestand op te laden (.mp3, .mp4, .wav, .m4a of .wma).<br>U koos '+ filename +'.');
	}else if (extension == 'document' && !fileIsDocument(filename)) {
		return handleUploadError('U dient een document op te laden (.txt, .doc, .docx, .xls of .pdf).<br>U koos '+ filename +'.');
	}else if (extension == 'picture' && !fileIsPicture(filename)) {
		return handleUploadError('U dient een beeldfragment op te laden (.jpg, .png, .gif of .flv).<br>U koos '+ filename +'.');
	}else if (extension == 'sound' || extension == 'document' || extension == 'picture'){	
		handleResponse('');
		upload_target = target;
		upload_field = field;
		$(form).target = 'response';
		$(form).method = 'post';
		$(form).enctype = 'multipart/form-data';
		$(form).action = '/inc/file_upload.dhtml?type='+ upload_type +'&ref=' + upload_ref + '&filetype=' + filetype;
		$(form).submit();
	}else{
		return handleUploadError('Er deed zich een fout voor bij het opladen van het bestand.');
	}
}
function checkExtension(filename, extensions) {
	filename = filename.toLowerCase();
	for (var i=0 ; i<extensions.length ; i++) {
		if(filename.lastIndexOf(extensions[i]) != -1) { 
			return true;
		}		
	}
	return false;	
}
function fileIsSoundtrack(file) {
	var array = ['.mp3','.mp4','.wav','.m4a', '.wma'];
	return checkExtension(file, array);
}
function fileIsDocument(file) {
	var array = ['.txt','.doc','.docx','.xls','.pdf'];
	return checkExtension(file, array);	
}
function fileIsDocument2(file) {
	var array = ['.txt','.doc','.docx','.xls','.pdf','.jpg'];
	return checkExtension(file, array);	
}
function fileIsPicture(file) {
	var array = ['.jpg','.png','.gif','.flv'];
	return checkExtension(file, array);
}
function handleUploadResponse(id,addFileToList) {
	$(upload_field).setAttribute('value','');
	hideLoader(upload_indicator);
	if(addFileToList) {
		new Ajax.Updater(upload_target, '/inc/file_info.dhtml?file='+ id +'&'+ upload_type +'='+ upload_ref, {insertion:Insertion.Bottom, onComplete:function(){ hideLoader(upload_indicator); }});
	}
}
function handleUploadError(errormsg) {
	hideLoader(upload_indicator);
	$('message').innerHTML = '<p class="error">' + errormsg + '</p>';
	$('message').scrollTo();
	return false;
}
function handleResponse(text) {
	$('message').innerHTML = text;
	//$('message').scrollTo();
}
function showField(chkbox, field) {
	(chkbox.checked) ? ($(field).style.display = 'block') : ($(field).style.display = 'none');
}
function selectCheckbox(field, chkbox) {
	($(field).value == '') ? ($(chkbox).checked = false) : ($(chkbox).checked = true);
}
function doShowHide(field_show, field_hide) {
	$(field_hide).style.display = 'none';
	$(field_show).style.display = 'block';
}
function countText(field, countfield, maxlimit) {
	if ($(field).value.length > maxlimit) {
		$(field).value = $(field).value.substring(0, maxlimit);		
	} else {
		$(countfield).innerHTML = maxlimit - $(field).value.length;	
	}
}


// functions for registration //
function submitRegistration(usertype, rform, part) {
	if ($('website') && $F('website') == 'http://') { $('website').value = ''; }
    var valid = new Validation(rform, {onSubmit:false, useTitles:true, immediate:false});
	if (valid.validate()) {
		new Ajax.Updater('message', '/inc/registration.dhtml?part='+ part +'&usertype='+ usertype +'&'+ usertype +'='+ user_id +'&nm='+ user_nm +'&pw='+ user_pw, {evalScripts:true, parameters:Form.serialize($(rform))});
	}
	return false;
}
function showRegistrationForm2() {
	$('reg_title').innerHTML = 'Registreer Stap 2/3';
	$('reg_part1').style.display = 'none';
	$('reg_part2').style.display = 'block';
}
function showRegistrationForm3() {
	if ($('reg_title')) { 
		$('reg_title').innerHTML = 'Registreer Stap 3/3';
		$('reg_part2').style.display = 'none';
		$('reg_part3').style.display = 'block';
	}
}
function setUser(usertype, id, nm, pw) {
	if (usertype == 'artist') {
		setArtist(id, nm, pw);
	}else if (usertype == 'organizer'){
		setOrganizer(id, nm, pw);
	}
}
function setArtist(id, nm, pw) {
	user_type = 'artist';
	user_id = id;
	user_nm = nm;
	user_pw = pw;
	upload_type = 'artist';
	upload_ref = id;
}
function setOrganizer(id, nm, pw) {
	user_type = 'organizer';
	user_id = id;
	user_nm = nm;
	user_pw = pw;
	upload_type = 'organizer';
	upload_ref = id;
}
function fillAccountInfo(chkbox) {
	if (chkbox.checked) {
		$('accountname').value = $('contactname').value;
		$('accountstreet').value = $('contactstreet').value;
		$('accountzip').value = $('contactzip').value;
		$('accountcity').value = $('contactcity').value;	
	}else{
		$('accountname').value = '';
		$('accountstreet').value = '';
		$('accountzip').value = '';
		$('accountcity').value = '';
	}
}


// functions for programs //
function submitProgram(pform, sts) {
	var todayDate = new Date();
	var inputDate = new Date();
	inputDate.setFullYear( $F('date_start').substring(6,10), $F('date_start').substring(3,5), $F('date_start').substring(0,2) );
	if (inputDate < todayDate) {
		alert('De opgegeven aanvangsdatum ligt in het verleden. Gelieve dit aan te passen.');
		$('date_start').focus();
	}else{
		var v = new Validation(pform, {onSubmit:false, useTitles:true, immediate:false});
		if (v.validate()) {
			new Ajax.Updater('message', '/inc/program.dhtml?oper=save&pg='+ program_id + '&nm='+ user_nm +'&pw='+ user_pw +'&sts='+ sts, {evalScripts:true, parameters:Form.serialize($(pform))});
			$('top').scrollTo();
		}
	}
}
function flipProgramForm(button) {
	if ($('frm_program').style.display == 'none') {
		$('frm_program').style.display = 'block';
		$('frm_program_upload').style.display = 'none';
		if ($(button+'1')) { $(button+'1').innerHTML = 'wijzig bijlagen'; }
		if ($(button+'2')) { $(button+'2').innerHTML = 'wijzig bijlagen'; }
	}else{
		$('frm_program').style.display = 'none';
		$('frm_program_upload').style.display = 'block';
		if ($(button+'1')) { $(button+'1').innerHTML = 'wijzig programmagegevens'; }
		if ($(button+'2')) { $(button+'2').innerHTML = 'wijzig programmagegevens'; }
	}
	return false;
}
function setProgramId(id) {
	program_id = id;
	upload_type = 'program';
	upload_ref = id;
}
function saveProgramAttachment(chkbox, attachementtype) {
	if (chkbox.checked) {
		new Ajax.Updater('message','/inc/program.dhtml?oper=attachement&pg='+ program_id +'&nm='+ user_nm +'&pw='+ user_pw +'&attachementtype='+ attachementtype +'&value=Y', {evalScripts:true});
	}else{
		new Ajax.Updater('message','/inc/program.dhtml?oper=attachement&pg='+ program_id +'&nm='+ user_nm +'&pw='+ user_pw +'&attachementtype='+ attachementtype +'&value=N', {evalScripts:true});			
	}
}
function saveUserAttachment(chkbox, attachementtype) {
	if (chkbox.checked) {
		new Ajax.Updater('message','/inc/registration.dhtml?oper=attachement&i='+ user_id +'&attachementuser='+ user_type +'&nm='+ user_nm +'&pw='+ user_pw +'&attachementtype='+ attachementtype +'&value=Y', {evalScripts:true});
	}else{
		new Ajax.Updater('message','/inc/registration.dhtml?oper=attachement&i='+ user_id +'&attachementuser='+ user_type +'&nm='+ user_nm +'&pw='+ user_pw +'&attachementtype='+ attachementtype +'&value=N', {evalScripts:true});			
	}
}
function checkMaxSelections(checkbox, nbr) {
	var chkboxes = $('frm_publish_program').getInputs('checkbox', checkbox.name);
	var counter = 0;
	for (var i=0 ; i<chkboxes.length ; i++) {
		if (chkboxes[i].checked) { counter++; }
	}
	if (counter > nbr) {
		checkbox.checked = false;
		if (nbr == 1) {
			alert('U kunt slechts één keuze maken.');
		}else{
			alert('U kunt slechts '+ nbr + ' keuzes maken.');
		}
	}
}


// function for events //
function setEventId(id) {
	event_id = id;
	upload_type = 'event';
	upload_ref = id;
}
var maxcost = null;
function recalculateParticipation(program, cost) {
	cost = parseFloat(cost.replace(/,/g,'.'));
	if (maxcost == null) {
		maxcost = cost;
	}else if (maxcost < cost){
		cost = maxcost + '';
		$('eventcosts').value = cost.replace(/\./g,',');
	}
	var Caller = { 
		makeRequest: function() { 
			new Ajax.Request('/inc/helpers.dhtml?program='+ program +'&cost='+ cost +'&oper=calcparticipation', {onSuccess:Caller.makeRequestCallback});
		}, 
		makeRequestCallback: function(r) { 
	    	$('pcorg').innerHTML = 'Participatie: '+ r.responseText +'€';
	  } 
	}
	Caller.makeRequest();
}
function setSelectedId(text, li) {
	if (text.id == 'program_name') {
		var arr = li.id.split('|');
		$('program').value = arr[1];
		$('program_date_from').value = arr[3];
		$('program_date_to').value = arr[4];
		var Caller = { 
			makeRequest: function() { 
				new Ajax.Request('/inc/get_program.dhtml?program='+ arr[1] +'&oper=cost', {onSuccess:Caller.makeRequestCallback});
			}, 
			makeRequestCallback: function(r) { 
				$('eventcosts').value = r.responseText.replace(/\./g,'\,');
				$('eventcosts').activate();
			} 
		}
		Caller.makeRequest();
	} else if (text.id == 'organizer_name') {
		$('organizer').value = li.id;
	}
}
function submitEvent(e, action) {

	var form = 'frm_participation';
	var v = new Validation(form, {onSubmit:false, useTitles:true, immediate:false});
		
	if (action == 'confirm') {
		$(form).method = 'post';
		$(form).action = '?oper='+ action +'participation';
	} else {
	    if ($('program').value == '') {
	    	$('message').innerHTML = '<p class="error">' + lbl_event_program_notice + '</p>';
			$('message').scrollTo();
			Event.stop(e);
		} else if ($('organizer').value == '') {
	    	$('message').innerHTML = '<p class="error">' + lbl_event_organizer_notice + '</p>';
			$('message').scrollTo();
			Event.stop(e);
	    } else if ($F('contractfile') != "" && !fileIsDocument2($F('contractfile'))) {
			$('message').innerHTML = '<p class="error">U kunt enkel bestanden met extentie .txt, .doc, .docx, .xls, .jpg en .pdf opladen.<br>U koos '+ $F('contractfile') +'.</p>';
			$('message').scrollTo();
			Event.stop(e);
		} else if ($('communication_cultuurweb').checked == false && $('communication_other').checked == false) {
			$('message').innerHTML = '<p class="error">Gelieve communicatie gegevens in te vullen.</p>';
			$('message').scrollTo();
			Event.stop(e);
		} else if (v.validate()) {
			var e_date = $('eventdate').value.substring(6,10) + $('eventdate').value.substring(3,5) + $('eventdate').value.substring(0,2);
			if ($('program_date_from').value > e_date || $('program_date_to').value < e_date) {
				$('message').innerHTML = '<p class="error">De datum van uw manifestatie valt niet binnen periode waarin het programma opgenomen is in het aanbod.</p>';
				$('message').scrollTo();
				Event.stop(e);
			}
			else {
				$('message').innerHTML = '';
				$(form).method = 'post';
				$(form).action = '?oper='+ action +'participation';
			}	
		} else {
		    $('message').innerHTML = '';
			Event.stop(e);
		}
	}
}

function submitEvaluation(e) {
	var form = 'frm_evaluation';
	var v = new Validation(form, {onSubmit:false, useTitles:true, immediate:false});
	if (v.validate()) {
		$(form).method = 'post';
		$(form).action = '?oper=finalizeparticipation';
	}else{
		Event.stop(e);
	}
}

function clearOrganizer(org){
	if (org.id == 'program_name') {
		$('program').value = '';
	} else if (org.id == 'organizer_name') {
		$('organizer').value = '';
	}
}

// observers //
function initializeEvents() {
	// artist registration form
	if (user_id == null && user_type == null && $('legalperson')) {$('legalperson').observe('click', function(event){ showField(this,'frm_sts'); }); }
	if (user_id == null && user_type == null && $('laureate')) {$('laureate').observe('keyup', function(event){ if ($F('laureate') == '') { $('frm_lau').hide(); }else{ $('frm_lau').show(); } }); }
	if ($('costInclBtw')) { $('costInclBtw').observe('click', function(event){ $('extracosts').hide(); }); }
	if ($('costExclBtw')) { $('costExclBtw').observe('click', function(event){ $('extracosts').show(); }); }
	
	// organizer registration form
	if ($('fill_account_info')) { $('fill_account_info').observe('click', function(event){ fillAccountInfo(this); }); }
	if ($('statuteA')) { $('statuteA').observe('click', function(event){ doShowHide('association','company'); }); }
	if ($('statuteC')) { $('statuteC').observe('click', function(event){ doShowHide('company','association'); }); }

	// program form
	if ($('frm_program')) { $('frm_program').observe('keydown', function(event){ if (event.keyCode == Event.KEY_RETURN){ Event.stop(event); } }); }
	if ($('btn_program_save')) { $('btn_program_save').observe('click', function(event) { submitProgram('frm_program', 'save'); Event.stop(event); }); }
	if ($('btn_program_send')) { $('btn_program_send').observe('click', function(event) { submitProgram('frm_program', 'send'); Event.stop(event); }); }
	
	// form - tooltips
	/*
	if ($('frm_part1') || $('frm_part2') || $('frm_part3') || $('frm_program') || $('frm_participation')) {
		var inputs = $$('span.tooltip_content');
		for (var i=0 ; i<inputs.length ; i++) {
			new Tooltip(inputs[i], inputs[i].innerHTML);
		}
	}
	*/
	
	// program form - publish
	if ($('frm_publish_program')) {
		var chkboxes = $('frm_publish_program').getInputs('checkbox', 'pub_visual[]');
		for (var i=0 ; i<chkboxes.length ; i++) {
			chkboxes[i].observe('change', function(event){ checkMaxSelections(this, 2); });
		}
		var chkboxes = $('frm_publish_program').getInputs('checkbox', 'pub_sound[]');
		for (var i=0 ; i<chkboxes.length ; i++) {
			chkboxes[i].observe('change', function(event){ checkMaxSelections(this, 1); });
		}
	}
	
	// event form
	if ($('frm_participation')) {
		new Ajax.Autocompleter('program_name', 'autocomplete_choices', '/inc/get_programs.dhtml?oper=listbyartist', {minChars:2, paramName:'value', afterUpdateElement:setSelectedId});
		new Ajax.Autocompleter('organizer_name', 'autocomplete_choices', '/inc/get_organizers.dhtml', {minChars:2, paramName:'value', afterUpdateElement:setSelectedId});
		$('frm_participation').observe('keydown', function(event){ if (event.keyCode == Event.KEY_RETURN){ Event.stop(event); } });
		$('eventcosts').observe('change', function(event){ recalculateParticipation($F('program'),$F('eventcosts')); });
		$('eventcosts').observe('focus', function(event){ recalculateParticipation($F('program'),$F('eventcosts')); });
		recalculateParticipation($F('program'),$F('eventcosts'));
		if ($('communication_container')) { $('communication_other').observe('click', function(event){ showField(this,'communication_container'); }); }
		if ($('communication_container')) { $('communication_cultuurweb').observe('click', function(event){ showField($('communication_other'),'communication_container'); }); }
	 	if ($('eventadmission')) { $('eventadmission').observe('keyup', function(event){ ($F('eventadmission') == 0) ? $('reduction').hide() : $('reduction').show() }); }
		if($('btn_participation_save')) { $('btn_participation_save').observe('click', function(event){ submitEvent(event, 'save'); }); }
		if($('btn_participation_send')) $('btn_participation_send').observe('click', function(event){ submitEvent(event, 'savesend'); });
		if($('btn_participation_confirm')) $('btn_participation_confirm').observe('click', function(event){ submitEvent(event, 'confirm'); });
	}
	
	// evaluation form
	if ($('frm_evaluation')) {
		$('frm_evaluation').observe('keydown', function(event){ if (event.keyCode == Event.KEY_RETURN){ Event.stop(event); } });
		if($('btn_evaluation_send')) { $('btn_evaluation_send').observe('click', function(event){ submitEvaluation(event); }); }
		
	}
}

Validation.add('validate-time', 'Please enter a valid time.', function(v) {
	var arr = v.split(':');
	if (arr.length == 1) {
		return false;
	}else{
		var test = new Date();
		test.setUTCHours(arr[0],arr[1]);
		return Validation.get('IsEmpty').test(v) || !isNaN(test);
	}
});
	
Validation.add('validate-currency', 'Please enter a valid currency.', function(v) {
	return Validation.get('IsEmpty').test(v) || /^\d+(,)*(\d+)*$/.test(v);
});
	
Event.observe(window, 'load', initializeEvents);

