$(function() {
	$.fn.toggleForm = function() {
		$('input, textarea', this).not("[type='hidden']").each(function() {
			$this = $(this);
			if ($this.attr('disabled') != null) $this.removeAttr('disabled', 'disabled');
			else $this.attr('disabled', 'disabled');
		});
		return this;
	};

	var toggleH1 = function() {
		if (!$('#stationInfo h1').hasClass('dontchange')) {
			if (arguments[0]) {
				var $h1 = $('<h1 class="_removeme">' + arguments[0] + '</h1>');
				$('#stationInfo h1').hide().after($h1);
			}
			else {
				$('#stationInfo h1._removeme').remove();
				$('#stationInfo h1').show();
			}
		}
	};
	
	var toggleMessage = function() {
		if (arguments[0]) {
			$msg = $('.stationSub._removeme');
			if ($msg.length == 0) {
				$msg = $('<div class="stationSub _removeme">' + arguments[0] + '</div>').hide();
				$('.stationSub:last').addClass('slidedown').slideUp(300, function() {
					$(this).after($msg);
					$msg.slideDown(300);
				});
			}
		}
		else {
			$('.stationSub._removeme').slideUp(300, function() {
				$(this).remove();
			});
		}
	}
	
	$("a[href='#add-friend']").click(function() {
		$this = $(this);
		var $list = $('#friendslist');
		var friendsCount = $('#friendslist li').length;
		var $li = $('<li></li>');
		$li.append('<fieldset><label>Όνομα φίλου</label><input type="text" name="f' + friendsCount + '_name" /></fieldset>')
			.append('<fieldset><label>Email φίλου</label><input type="text" name="f' + friendsCount + '_email" /></fieldset>');
		
		$this.parents('li').before($li);
		
		if (friendsCount == 6) $this.remove();

		return false;  	
	});
	
	$("a[href='#send-contact-form']").click(function() {
		var serializedForm = $("form").serialize();
		
		$btn = $(this);
		$('form').toggleForm();

		$('#stationInfo .actions').addClass('slideme').hide().after('<p class="removeme actions">Γίνεται η αποστολή...</p>');

		var resetForm = function() {
			console.log('reseting form');
			$('form').toggleForm();
			toggleMessage();
			toggleH1();
		};

		//$msg = $('<div class="stationSub removeme"></div>').hide();


		$.ajax({
			type: 'POST',
			url: live24_contact_url,
			data: serializedForm + '&resp_type=json&nocache=' + Math.random(),
			dataType: 'json',
			success: function(data, status) {
				if (data.e == 'true') {
					toggleH1('Πρόβλημα!');
					t = setTimeout(resetForm, 3000);
				}
				else if (data.e == 'none'){
					toggleH1('Επιτυχία');
				}
				
				toggleMessage(data.m);
			},
			error: function (XMLHttpRequest, status, err) {
				toggleH1('Πρόβλημα!');
				t = setTimeout(resetForm, 3000);
				
				toggleMessage('Υπήρξε κάποιο πρόβλημα κατά την επικοινωνία με τον διακομιστή');
			}
		});
		
		return false;
	});
});
