
//set a cookie
function setCookie(cookiename){		
	$.cookie(cookiename, "true", { path: '/', expires: 365});
}



$(document).ready(function() {
	
		
	//if submit button is clicked
	$(".simplesurvey_form .survey_submit .submitbutton").click(function () {		
		//alert('click!');
		var portlet_id = $(this).parents(".simplesurvey").attr("id");
		
		var form_id = $(this).parent().parent().attr("id");		
		//log.debug('portlet_id = '+portlet_id);
		
		var selectorName = '#' + portlet_id + ' .simplesurvey_form input';
		//log.debug('selectorName = '+selectorName);
		
		//Collect input data
		var data = "";
		var atleastone = false;
		$(selectorName).each(function(){
			var name = $(this).attr("name");
			var type = $(this).attr("type");
			var checked = $(this).attr("checked");	
			//log.debug('name = '+name);
			if(type == 'radio' || type == 'checkbox'){
				if(checked){
					data+=(name+'='+$(this).val())+'&';
					atleastone = true;
				}
			}
			if(type == 'hidden'){
				data+=(name+'='+$(this).val())+'&';
			}
		});
		
		//Check that there is, at least, one selected answer
		if(!atleastone){
			alert(getAtLeastOneAnswerSelectedText());
			return false;
		}
		
		data+="reqId="+ Math.floor(Math.random()*101);		
		//log.debug(data);
		
		//hide form		
		$("#form_"+portlet_id).hide();
		
		//show loading
		//alert('show loading');
		$("#loading_div_"+portlet_id).show();
		
		//start the ajax
		//alert('start ajax');
		$.ajax({
			//this is the php file that processes the data and send mail
			url: getSimpleSurveyPostURL(),	
			
			//GET method is used
			type: "GET",

			//pass the data			
			data: data,		
			
			//Do not cache the page
			cache: false,
			
			//success
			success: function (html) {				
				treatAJAXResponse(html,form_id,portlet_id);		
			},	
		
			//error
			error: function(html,errormessage){
				//hide loading
				$("#loading_div_"+portlet_id).hide();
				
				//show form
				$("#"+form_id).show();	
				
				//display error message
				alert(getTransmissionErrorMessageText()+'\nError message : '+errormessage);				
			}
		});
		//alert('end ajax');
		
		//cancel the submit button default behaviours
		return false;
	});	
});	

function treatAJAXResponse(html, formId, portletID){
	//log.info('RETURN : '+html);
	//log.debug('formId = '+formId);
	//log.debug('portletID = '+portletID);
	//hide loading
	$("#"+formId).hide();		
	
	//set html in answer div
	$("#report_div_"+portletID).html(html);
	
	//show the answer div
	$("#report_div_"+portletID).show();
	
	//set the cookie
	var cookieName = $("#cookie_name_input_"+portletID).val();
	//log.debug('cookieName = '+cookieName);
	setCookie(cookieName);
}


