/**
 * Page load actions.
 */

$(document).ready(function() {
	// Toggle help
	$('#help-button').click(function() {
		$('#help-container').toggle();
		return false;
	});

	$('#gtc-label a').click(function() {
		$('#help-button').trigger('click');
		return false;
	});

	// Close help
	$('#close-help-button').click(function() {
		$('#help-container').hide();
		return false;
	});

	// Close proposals
	$('#close-proposals-button').click(function() {
                $('#text-proposals').toggle();
		return false;
	});

	// Validate signon form
	$('#signonform').submit(function() {
		return validateForm('signonform');
	});
	$('#signonform-link').click(function() {
		if (validateForm('signonform')) {
			document.signonform.submit();
		}
		return false;
	});

	// Validate patron form
	$('#patronform').submit(function() {
		return validateForm('patronform');
	});
	$('#patronform-link').click(function() {
		if (validateForm('patronform')) {
			document.patronform.submit();
		}
		return false;
	});

	// Validate donation form
	$('#donateform').submit(function() {
		return validateForm('donateform');
	});
	$('#donateform-link').click(function() {
		if (validateForm('donateform')) {
			document.donateform.submit();
		}
		return false;
	});

	// Validate patron edit form
	$('#edit-patronform').submit(function() {
		return validateForm('edit-patronform');
	});
	$('#edit-patronform-link').click(function() {
		if (validateForm('edit-patronform')) {
			document['edit-patronform'].submit();
		}
		return false;
	});

	// Product select
	if ($('#product-select').length > 0) {
		// on page load
		if ($('#product-select option:selected').length == 1) {
			var optionValue = $('#product-select option:selected').val();
			if (optionValue) {
				var productId = optionValue.replace('product', 'product-content');
				showProduct(productId);
			}
		}

		// on change
		$('#product-select').change(function(event) {
			document.productform.submit();
			//var productId = this.value.replace('product', 'product-content');
			//showProduct(productId);
		});
	}
	
	// Deactive boxes with overlays
	$('.inactive-overlay').each(function() {
		var target = $('#' + $(this).attr('rel'));
		$(this).css('height', target.height() + 'px').css('width', target.width() + 'px').css('opacity', '.7');
	});

	// Donation confirmation
 	if ($('#donation-overlay').length > 0) {
		$('#donation-info-box a').click(function() {
			$('#donation-overlay').fadeOut(500);
			$('#donation-info-box').fadeOut(500);
			return false;
		});
	}

	// Show text proposals
	$('#text-proposal-link').click(function() {
		$('#text-proposals').toggle();
		return false;
	});

	// Select text propsals
	$(".text-proposal").each(function() {
		$(this).click(function() {
			var activePropsal = $(this).attr('id');
			// Uncheck all proposals
			$(".text-proposal").each(function() {
				$(this).removeAttr('rel');
				if ($(this).attr('id') != activePropsal) {
					$(this).find('img.checked').hide();
					$(this).find('img.unchecked').show();
				}
			});
			// Toggle active propsal
			$(this).find('img.checked').toggle();
			$(this).find('img.unchecked').toggle();
			// Set active propsal
			if ($(this).find('img.checked').css('display') != 'none') {
				$(this).attr('rel', 'checked');
			}
		});
	});

	// Copy text propsal
	$('#copy-text-proposal').click(function() {
		$('#text-patron').val($(".text-proposal[rel='checked'] .text-proposal-content").text());
		$('#text-proposals').toggle();
		return false;
	});

	// Toggle donator list
	$('.toggle-donatorlist').click(function() {
		$('#donatorlist').toggle();
		return false;
	});

	// Donation bar
	var barFullHeight = 330;
	var donatedMoney =  parseInt($('#donated-money-int').text());
	var missingMoney =  parseInt($('#missing-money-int').text());
	var barHeight = 330 / (donatedMoney + missingMoney) * donatedMoney;
	if (barHeight > barFullHeight) {
		barHeight = barFullHeight;
	}
	$('#donation-bar').css('height', '0px');
	
	$('#donation-bar').animate({
		height: barHeight + 'px'
	}, 1000, "linear");

	var barPercent = 100 / (donatedMoney + missingMoney) * donatedMoney;
	if (barPercent > 100) {
		barPercent = 100;
	}
	if (isNumber(barPercent.toFixed(0))) {
		$('#donation-box-container').attr('title', barPercent.toFixed(0) + '%');
	}

	// Show info messages
	$('.infoMessage').each(function() {
		var container = $(this).attr('rel');
		$('#' + container).contents().css("opacity",".1");
		
		setTimeout(function() {
			$('#' + container).contents().css("opacity","1");
		}, 1500); 

		$(this).fadeOut(2000);
	});

	// Patron email editor
	$('.email-patron-row .button-edit').live('click', function() {

		var $this = $(this);
		var index = $this.parent().parent().find('.email-patron-row').index($this.parent());

		//var diff = $this.parent().outerHeight();

		if (index > 0) {
			// remove
			$this.parent().remove();

			//diff *= -1;
		}
		else {
			// add
			var $row = $('<div class="email-patron-row"><input type="text" name="email-patron" class="mandatory-set email-patron" \/><span class="button-edit"><\/span><\/div>');
			$(this).parent().before($row);
		}

		$this.parent().parent().find('.email-patron-row .button-edit').html('&ndash;').eq(0).html('+');
	});

	// Show patron list edit controls
	$('.show-donationlist-edit').click(function() {
		$('.edit-buttons').toggle()
		return false;
	});

	// Add patron
	$('.patron-add').click(function() {
		$('#edit-patron-box #firstname').val('');
		$('#edit-patron-box #lastname').val('');
		$('#edit-patron-box #email').val('');
		$('#edit-patron-box #amount').val('');
		$('#edit-patron-box #anonymous').removeAttr('checked');
		$('#edit-patron-box #donationUuid').val('');
		$('#edit-patron-box #action').val('add');

		// Show title and form
		$('#edit-patron-title').hide();
		$('#add-patron-title').show();
		$('#edit-patron-box').show();
		return false;
	});

	// Edit patron
	$('.patron-edit').click(function() {
		var uuid = $(this).attr('rel');
		var firstname = $('#' + uuid + ' .firstname').text();
		var lastname = $('#' + uuid + ' .lastname').text();
		var email = $('#' + uuid + ' .email').text();
		var amount = $('#' + uuid + ' .amount').text();
		var anonymous = $('#' + uuid + ' .anonymous').text();
		$('#edit-patron-box #firstname').val(firstname);
		$('#edit-patron-box #lastname').val(lastname);
		$('#edit-patron-box #email').val(email);
		$('#edit-patron-box #amount').val(amount);
		if (anonymous == 'true') {
			$('#edit-patron-box #anonymous').attr('checked', 'checked');
		}
		else {
			$('#edit-patron-box #anonymous').removeAttr('checked');
		}
		$('#edit-patron-box #donationUuid').val(uuid);
		$('#edit-patron-box #action').val('edit');

		// Show title and form
		$('#edit-patron-title').show();
		$('#add-patron-title').hide();
		$('#edit-patron-box').show();
		return false;
	});

	// Delete patron
	$('.patron-delete').click(function() {
		var uuid = $(this).attr('rel');
		var firstname = $('#' + uuid + ' .firstname').text();
		var lastname = $('#' + uuid + ' .lastname').text();
		var confirmationMessage = $('#deleteDonatorConfirmation1').text() + ' "' + firstname + ' ' + lastname + '" ' + $('#deleteDonatorConfirmation2').text(); 
		$('#edit-patron-box #donationUuid').val(uuid);
		$('#edit-patron-box #action').val('delete');

		// Confirmation message
		if (confirm(confirmationMessage)) {
			document['edit-patronform'].submit();
		}
		return false;
	});

	// Cancel edit
	$('#edit-patronform-cancel').click(function() {
		$('#edit-patron-box').hide();
		return false;
	});

	/**
	 * Organisations
	 */

	// Validate registration form
	 $('#registrationform').submit(function() {
		return validateForm('registrationform');
	});

	// Validate voting form
	 $('#votingform').submit(function() {
		return validateForm('votingform');
	});

	// Select all
	$('textarea.select-all').click(function() {
		$(this).focus();
		$(this).select();
	});

	// Show agb overlay
	$('#gtc-label a').click(function() {
		$('#help-container').toggle();
		return false;
	});

});

/**
 * Show product
 */

function showProduct(productId) {
	var image = $('#' + productId + ' .image').text();
	var link = $('#' + productId + ' .link').text();
	var description = $('#' + productId + ' .description').html();
	// Show image
	$('#product-image-container').empty();
	$('#product-image-container').append('<a href="' + link + '" target="_blank"><img src="' + image + '" /></a>');
	// Show description
	$('#product-description-container').empty();
	$('#product-description-container').append(description);
	// Show save button
	$('#product-box .continue-link').show();
}

/**
 * Form validation
 */

function validateForm(formName) {
	var proceed = true;

	var $set = $('#' + formName + ' :input.mandatory-set');
	if ($set.length > 0) {
		var _valid = false;
		$set.each(function() {
			if ($(this).val() != '') {
				_valid = true;
			}
		});

		$set.removeClass('error');
		if (!_valid) {
			$set.eq(0).addClass('error');
			proceed = false;
		}
	}	


	// input, textarea, select
	$('#' + formName + ' :input.mandatory').each(function() {
		if ($(this).val() == '') {
			$(this).addClass('error');
			proceed = false;
		}
		else {
			$(this).removeClass('error');
		}
	});

	// input type checkbox
	$('#' + formName + ' :checkbox.mandatory').each(function() {
		if (! $(this).is(':checked')) {
			$('#' + this.id + '-label').addClass('error');
			proceed = false;
		}
		else {
			$('#' + this.id + '-label').removeClass('error');
		}
	});

	// email
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	$('#' + formName + ' :text.validate-email').each(function() {
		if (! reg.test($(this).val())) {
			$(this).addClass('error');
			proceed = false;
		}
		else {
			$(this).removeClass('error');
		}
	});

	// number
	$('#' + formName + ' :text.validate-number').each(function() {
		if (! isFloat($(this).val())) {
			$(this).addClass('error');
			proceed = false;
		}
		else {
			$(this).removeClass('error');
		}
	});

	return proceed;
}

/**
 * Check for a numeric value
 */

function isNumber(value) {
	if (! value.toString().match(/^\d*$/)) {
		return false;
	}
	else {
		return true;
	}
}

function isFloat(value) {
	if (! value.toString().match(/^[-]?\d*\.?,?\d*$/)) {
		return false;
	}
	else {
		return true;
	}
}




