// Functies uit te voeren bij laden van de pagina
$(function() {
	windowResize();
	$(window).bind("resize", windowResize);
	
	// Form validation
	$("#frmInschrijven").validate();
	
	// Tweedekansdoop 2012
	$("#doopLijst").on('ajaxSuccess', function() { addViewByIdAction("#tweedekansdoop"); });
	$("#btnEditInDoopLijst").on('click', function() { toggleEditAction("#tweedekansdoop"); });
	$("#btnDeleteInDoopLijst").on('click', function() { toggleDeleteAction("#tweedekansdoop"); });
	$("#btnRefreshDoopLijst").on('click', function() { getDoopCount(); doDoopFindAll(); });
	
	// Ledenweekend 2012
	$("#weekendLijst").on('ajaxSuccess', function() { addViewByIdAction("#ledenweekend"); });
	$("#btnEditInWeekendLijst").on('click', function() { toggleEditAction("#ledenweekend"); });
	$("#btnDeleteInWeekendLijst").on('click', function() { toggleDeleteAction("#ledenweekend"); });
	$("#btnRefreshWeekendLijst").on('click', function() { getWeekendCount(); getCarsCount(); doWeekendFindAll(); });
});

// Schild aan de linkerkant weghalen indien te smal
function windowResize() {
	if($(window).width() < 1230)
		$('#bgImage').hide();
	else
		$('#bgImage').show();
}

// Make rows clickable, show dialog with row details
function addViewByIdAction(elTable) {
	var elColumn = elTable + " .naamColumn";
	
	$(elColumn).each(function(i, val) {		
		var phtId = $(this).parent().attr('id').substring(3);
		$(this) .on('click', {value: phtId}, doViewRow)
				.css('cursor', 'pointer')
				.hover(
					function() { $(this).css('text-decoration', 'underline'); },
					function() { $(this).css('text-decoration', 'none'); }
				);
				
		return true;
	});
}
	

// Show and hide edit action columns
function toggleEditAction(elTable) {
	var elColumn = elTable + " .actionColumn";
	
	$(elColumn).each(function(i, val) {
		if(i == 0)
			return true;
		
		var phtId = $(this).parent().attr('id').substring(3);
		$(this)	.html($('<img/>')
				.attr('id', 'pht' + phtId)
				.attr('class', 'imgEdit')
				.attr('src', '/public/themes/PHT_default/icons/pencil.png')
				.css('cursor', 'pointer')
				.on('click', doEditRow)
				);
		$(this).toggle();
		return true;
	});
}

// Show and hide delete action columns
function toggleDeleteAction(elTable) {
	var elColumn = elTable + " .actionColumn";
	
	$(elColumn).each(function(i, val) {
		if(i == 0)
			return true;
		
		var phtId = $(this).parent().attr('id').substring(3);
		$(this)	.html($('<img/>')
				.attr('id', 'pht' + phtId)
				.attr('class', 'imgDelete')
				.attr('src', '/public/themes/PHT_default/icons/cross.png')
				.css('cursor', 'pointer')
				.on('click', doDeleteRow)
				);
		$(this).toggle();
		return true;
	});
}

//Do findById action for a row, delegate by table id
function doViewRow() {
	var tableId = $(this).parent().parent().parent().attr('id');
	var phtId = $(this).parent().attr('id').substring(3);
	
	switch (tableId){
		case "tweedekansdoop":
			doSchachtById(phtId);
			break;
			
		case "ledenweekend":
			doWeekendById(phtId);
			break;
	
		default :
			alert("Fout bij het uitvoeren van de 'details bekijken' actie.");
			break;
	}
}

// Do edit action for a row, delegate by table id
function doEditRow() {
	var tableId = $(this).parent().parent().parent().parent().attr('id');
	var phtId = $(this).attr('id').substring(3);
	
	switch (tableId){
		case "tweedekansdoop":
			doEditSchacht(phtId);
			break;
			
		case "ledenweekend":
			doEditWeekend(phtId);
			break;
	
		default :
			alert("Fout bij het uitvoeren van de 'bewerken' actie.");
			break;
	}
}

// Do delete action for a row, delegate by table id
function doDeleteRow() {
	var tableId = $(this).parent().parent().parent().parent().attr('id');
	var phtId = $(this).attr('id').substring(3);

	switch (tableId){
		case "tweedekansdoop":
			doDeleteSchacht(phtId);
			break;
			
		case "ledenweekend":
			doDeleteWeekend(phtId);
			break;
	
		default :
			alert("Fout bij het uitvoeren van de 'verwijderen' actie.");
			break;
	}
}

/*
 * Tweedekansdoop ajax functions
 */
function getDoopCount() {
	$.ajax({
			url: "http://phtclub.be/admin/php/ajax_actions.php",
			type: "post",
			data: {
				ajax_action: "count",
				table_name: "tweedekansdoop"
			},
			dataType: "json",
			success: function(result) {
				if(result.isSucces == "true"){
					$("#doopAantal").empty().html(result.doopAantal);
				}
				else
					alert ("Probleem met het verversen van de lijst.");
			}
	});
}

function doDoopFindAll() {
	$.ajax({
			url: "http://phtclub.be/admin/php/ajax_actions.php",
			type: "post",
			data: {
				ajax_action: "findAll",
				table_name: "tweedekansdoop"
			},
			dataType: "html",
			success: function(result) {
				if(result.length  > 7)
					$("#doopLijst").html(result);
				else
					alert ("Probleem met het verversen van de lijst.");
			}
	});
}

function doSchachtById(phtId) {
	$.ajax({
		url: "http://phtclub.be/admin/php/ajax_actions.php",
		type: "post",
		data: {
			ajax_action: "findById",
			table_name: "tweedekansdoop",
			pk_id: phtId
		},
		dataType: "html",
		success: function(result) {
			if(result.length  > 7) {
				$("#doopRecord").html(result);
				$("#doopRecord").dialog('open');
			}
			else
				alert ("Probleem met het ophalen van details van een inschrijving.");
		}
	});
}

function doEditSchacht(phtId) {
	alert("Not yet implemented");
}

function doDeleteSchacht(phtId) {
	rowId = "#row" + phtId;
	var schachtNaam = $(rowId).children('.naamColumn').text() + " " + $(rowId).children('.voornaamColumn').text();
	
	if(confirm("Ben je zeker dat je " + schachtNaam + " wil verwijderen?")) {
		// Do Ajax call
		$.ajax({
				url: "http://phtclub.be/admin/php/ajax_actions.php",
				type: "post",
				data: {
					ajax_action: "delete",
					table_name: "tweedekansdoop",
					pk_id: phtId
				},
				dataType: "json",
				success: function(result) {
					if(result.isSucces == "true"){
						var rowId = "#row" + result.pk_id;
						getDoopCount();
						$(rowId).fadeOut("slow", function(){$(rowId).remove();} );
					}
					else
						alert (schachtNaam + " is niet verwijderd.\r\nError: " + result.error);
				}
		});
	}
	else
		alert (schachtNaam + " is niet verwijderd.");
}

/*
 * Ledenweekend ajax functions
 */
function getWeekendCount() {
	$.ajax({
			url: "http://phtclub.be/admin/php/ajax_actions.php",
			type: "post",
			data: {
				ajax_action: "count",
				table_name: "ledenweekend"
			},
			dataType: "json",
			success: function(result) {
				if(result.isSucces == "true"){
					$("#weekendAantal").empty().html(result.weekendAantal);
				}
				else
					alert ("Probleem met het verversen van de lijst.");
			}
	});
}

function getCarsCount() {	
	$.ajax({
		url: "http://phtclub.be/admin/php/ajax_actions.php",
		type: "post",
		data: {
			ajax_action: "countCars",
			table_name: "ledenweekend"
		},
		dataType: "json",
		success: function(result) {
			if(result.isSucces == "true"){
				$("#weekendAantalAutos").empty().html(result.autosAantal);
			}
			else
				alert ("Probleem met het verversen van de lijst.");
		}
	});
}

function doWeekendFindAll() {
	$.ajax({
			url: "http://phtclub.be/admin/php/ajax_actions.php",
			type: "post",
			data: {
				ajax_action: "findAll",
				table_name: "ledenweekend"
			},
			dataType: "html",
			success: function(result) {
				if(result.length  > 7)
					$("#weekendLijst").html(result);
				else
					alert ("Probleem met het verversen van de lijst.");
			}
	});
}

function doWeekendById(phtId) {	
	$.ajax({
		url: "http://phtclub.be/admin/php/ajax_actions.php",
		type: "post",
		data: {
			ajax_action: "findById",
			table_name: "ledenweekend",
			pk_id: phtId
		},
		dataType: "html",
		success: function(result) {
			if(result.length  > 7) {
				$("#weekendViewRecord").html(result);
				$("#weekendViewRecord").dialog('open');
			}
			else
				alert ("Probleem met het ophalen van details van een inschrijving.");
		}
	});
}

function doEditWeekend(phtId) {
	$.ajax({
		url: "http://phtclub.be/admin/php/ajax_actions.php",
		type: "post",
		data: {
			ajax_action: "edit",
			table_name: "ledenweekend",
			pk_id: phtId
		},
		dataType: "html",
		success: function(result) {
			if(result.length  > 7) {
				$("#weekendEditRecord").html(result);
				$("#weekendEditRecord").dialog('open');
			}
			else
				alert ("Probleem met het bewerken van een inschrijving.");
		}
	});
}

function doSaveWeekend(phtId) {
	heeftAuto = ($("#chkHeeftAuto").prop("checked") ? 'Y' : 'N');
	voorschotBetaald = ($("#chkVoorschotBetaald").prop("checked") ? 'Y' : 'N');
	volledigBetaald = ($("#chkVolledigBetaald").prop("checked") ? 'Y' : 'N');
	
	params = {heeftAuto: heeftAuto, voorschotBetaald: voorschotBetaald, volledigBetaald: volledigBetaald};
	
	$.ajax({
		url: "http://phtclub.be/admin/php/ajax_actions.php",
		type: "post",
		data: {
			ajax_action: "update",
			table_name: "ledenweekend",
			pk_id: phtId,
			params: JSON.stringify(params)
		},
		dataType: "json",
		success: function(result) {
			if(result.isSucces == "false"){ //TODO: show OK msg? - VALIDATION
				alert ("De inschrijving is niet geupdate.\r\nError: " + result.error);
			}
			getWeekendCount();
			getCarsCount();
			doWeekendFindAll();
		}
	});
}

function doDeleteWeekend(phtId) {
	rowId = "#row" + phtId;
	var lidNaam = $(rowId).children('.naamColumn').text() + " " + $(rowId).children('.voornaamColumn').text();
	
	if(confirm("Ben je zeker dat je " + lidNaam + " wil verwijderen?")) {
		// Do Ajax call
		$.ajax({
				url: "http://phtclub.be/admin/php/ajax_actions.php",
				type: "post",
				data: {
					ajax_action: "delete",
					table_name: "ledenweekend",
					pk_id: phtId
				},
				dataType: "json",
				success: function(result) {
					if(result.isSucces == "true"){
						var rowId = "#row" + result.pk_id;
						getWeekendCount();
						$(rowId).fadeOut("slow", function(){$(rowId).remove();} );
					}
					else
						alert (lidNaam + " is niet verwijderd.\r\nError: " + result.error);
				}
		});
	}
	else
		alert (lidNaam + " is niet verwijderd.");
}

/*
 * Misc. functions
 */
function trim (str) {
    str = str.replace(/^\s+/, '');
    for (var i = str.length - 1; i >= 0; i--) {
        if (/\S/.test(str.charAt(i))) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    return str;
}
