
$(function(){
	
	var surveymodal = false;
	
	function modalOpen(dialog) {
		dialog.overlay.fadeIn('slow', function() {
			dialog.container.fadeIn('slow', function() {
				dialog.data.hide().slideDown('slow');	 
			});
		});
		$('#start').bind('click', function() {
			startSurvey();
			return false;
		})
	}
	
	function resizeModal(w,h){
		var ww = $(window).width();
		var wh = $(window).height();
		var t = ((wh - h) / 2);
		var l = ((ww - w) / 2);
		$('#simplemodal-container').animate({
			width:w,
			height:h,
			top:t,
			left:l
		});
	}	
	
	function loadModalContent(url, target) {
		target = (typeof target == 'undefined' ? '#surveyinner' : target);
		url = (typeof url == 'undefined' ? '' : url);
		$.ajax({
			url: url,
			data: '',
			success: function(text) {
				$(target).html(text);
				bindSurveyForm();
				bindSurveyClose();
			},
			error: function() {
				alert('Unable to start survey.');
			}
		});
	}
	
	function bindSurveyForm(target) {
		target = (typeof target == 'undefined' ? '#surveyinner' : target);
		$('form.survey').ajaxForm({
			url: '/survey/',
			dataType: 'text',
			success: function(text) {
				$(target).html(text);
				bindSurveyForm();
				bindSurveyClose();
			},
			error: function() {
				alert('Sorry, we were unable to save your answers.');
			},
			global: false,
			timeout: 300000
		});
		if ($('p.error').html()) {
			alert($('p.error').html());
		}
	}
	
	function bindSurveyClose() {
		$('.simplemodal-close').bind('click', function() {
			surveymodal.close();
		});
	}
	
	function startSurvey() {
		loadModalContent('/survey/');
		resizeModal(660,400);
	}
	
	$("#survey").ajaxStart(function () {
		$('#surveyinner', '#survey').fadeOut();
	});
	
	$("#survey").ajaxStop(function () {
		$('#surveyinner', '#survey').fadeIn();
	});	
	
	setTimeout(
		function() {
			surveymodal = $('#survey').modal({
				overlayClose:true,
				onOpen:modalOpen
			});
		}, 
		2000
	);

});
