var indexNews;
var requiredFields = [
    'LastName',
    'FirstName',
    'Town',
    'BirthdayDD',
    'BirthdayMM',
    'BirthdayYYYY',
    'Team'
];

function bindIndexEvents(){
	$('.clearFields').unbind().click(clearFields);
	$('#sendMessageTeam').unbind().click(sendMail);
}

function sendMail(){
	var content = $('.contentAktiv:first');
	var active = $(content).attr('id');
	var data = new Object();
	data.AJAXType = active == 'probetraining' ? 1 : (active == 'aslkdjl' ? 2 : 3);
	
	$(content).find(':text,textarea,select').each(function(){
		data[$(this).attr('id')] = formatiereURI($(this).val());
	});
	
	if(checkFields()){
		//AJAX-Request senden
		$.ajax({
			async: "async",
			url: "PHP/index.ajax.php",
			type: "POST",
			dataType: "json",
			data: data,							//Daten suchen
			success: function(dataP, status){
				if(dataP && dataP.ok){
					clearFields();
					alert('Nachricht wurde erfolgreich verschickt!');
				}
			},
			error: function(xmlhttp, statzs, error){
				alert('Fehler bei der Kommunikation. Bitte wenden Sie sich an Ihren Administrator!');
			}
		});
	}
}

function checkFields(){
	var ok = true;
	var phone = $('#Phone').val();
	var mobile = $('#Mobile').val();
	var mail = $('#Mail').val();
	$('.failField').removeClass('failField');
	
	for(var i in requiredFields){
		var field = requiredFields[i];
		
		if(!($('#' + field).val() != '')){
			$('#' + field).addClass('failField');
			ok = false;
		}
	}
	
	if(phone != '' || mobile != '' || mail != ''){
		if(mail != ''){
			if(!checkMail(mail)){
				$('#Mail').addClass('failField');
				ok = false;
			}
		}
	}
	else{
		$('#Phone,#Mobile,#Mail').addClass('failField');
		ok = false;
	}
	
	return ok;
}

function clearFields(){
	var active = $('.contentAktiv:first');
	$(active).find(':text,textarea').val('');
	$(active).find('select').each(function(){
		if($(this).attr('id') != 'BirthdayYYYY'){
			$(this).find('option:first').attr('selected', true);
		}
		else{
			$(this).find('option:last').attr('selected', true);
		}
	});
}

function berechneAbstandContainer(){
	var newsContainerHeight = $('#topNews').height() + (2 * $('.newsReihe').height()) + $('#subnaviLeiste').height() + 4 + 10 + 10; //4 Pixel Border oben und unten + 10 Pixel Margin-Top + 10 Pixel Abstand zum unteren Rand
	var leerRaum = ($('#contentBereich').height() - newsContainerHeight) / 3;
	$('#topNews').css('margin-top', leerRaum - 10);
	$('.newsReihe').css('margin-top', leerRaum);
	$('#topNews').focus();
}

function initialize(){
	//Lädt die News und ruft die jeweilge Callback auf.
	indexNews = new News(SITEID, function(){
		$('#news').empty().append(this.newsHTML);
		berechneAbstandContainer();
	}, true, true);
	
	bindIndexEvents();
}

$(window).load(function(){
	initialize();
});
