window.document.pollModules = new Array();

$(document).ready(function(){
	//poll FORM
	$('.polling').ajaxForm({ beforeSubmit: submit_poll, success: showResponse_poll, dataType: 'json', error: raiseError }); 

});

function SubmitPollForm(f,box,id,answer) {
	if (CheckPollForm(f.answer)) {
		v_answer = SelectPollForm(f.answer);
		$.ajax({
			url: "/enquesta/result.php",
			data: { int_box: box, int_PK: id, answer: v_answer },
			dataType: 'json',
			error: raiseError,
			success:function(data){
					showPollResult(data,box);
				}
		 });
	} else alert("S'ha de seleccionar una resposta");
}

function submit_poll(formData, jqForm, options) {
	var f = jqForm[0];
	if (!CheckPollForm(f.answer)) {
		alert("S'ha de seleccionar una resposta"); 
		return false;
	}
	return true;
}

function CheckPollForm(option) {
	for(i=0; i<option.length; i++){
		if (option[i].checked){
			return true;
		}
	}
	return false;
}

function SelectPollForm(option) {
	for(i=0; i<option.length; i++){
		if (option[i].checked)return option[i].value;
	}
	return 0;
}

function showResponse_poll(data, statusText, jqForm)  { 
	
	var f = jqForm[0];
	showPollResult(data,data.box);
}

function raiseError() {
	alert("Error: no és possible votar ");
}

function raiseError2() {
	alert("Error: no és possible carregar els resultats");
}

function showPollResult(data,box) {
	if (data.status==0) {
		alert(data.message);		
	} else {
		$("#pollVotes"+box).html(data.totalvotes);
		$("#txt_pollVotes"+box).html((data.totalvotes==1)? 'Vot':'Vots');
		$("#pollOpinions"+box).html(data.totalopinions);
		$("#txt_pollOpinions"+box).html((data.totalopinions==1)? 'Opinió':'Opinions');
		
		window.document.pollModules[box] = $("#poll"+box).html();
		$("#poll"+box).html(data.html);

	}
}

function backToPoll(box) {
	$("#poll"+box).html(window.document.pollModules[box]);
}

function viewPollresults(box,id) {
	$.ajax({
		url: "/enquesta/result.php",
		data: { int_box: box, int_PK: id },
		dataType: 'json',
		error: raiseError2,
		success:function(data){
				showPollResult(data,box);
			}
	 });
}

var newOpiPollwindow = '';
function viewPollOpinions(id,tId) {
    	var url = "/opinions/list.php?id="+id+"&tId="+tId;
        if (!newOpiPollwindow.closed && newOpiPollwindow.location) {
        	newOpiPollwindow.location.href = url;
        } else {
    	    var w = '800';
        	var h = '600';
    	    LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
        	TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
        	settings ='height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',toolbar=0,location=0,status=0,menubar=0,scrollbars=1,toolbar=0,resizable=0';
        	newOpiPollwindow = window.open(url,"Opinions",settings);
        }
        if (window.focus) newOpiPollwindow.focus();
}
