/* Работа опросов и голосований за материалы */

function getCachedVoteList(form) {
    var cookie_var_name = form.find('input[name=cookie_name]').val();
    var list_serialized = $.cookie(cookie_var_name);
    if (list_serialized) {
	return list_serialized.replace(/^\"(.*?)\"$/,'$1').split(',');
    }
    return [];
}

function surveySubmitCompleteHandler(targetSurveyForm) {
    return function submitSurveyComplete(data) {
	targetSurveyForm.replaceWith(data);
    }
}

function submitSurvey(el) {
    var btn = $(el);
    var form = btn.parents('form').eq(0);
    var caseVal = form.find('input:radio:checked').val();
    if (caseVal == undefined) {
	alert('Укажите, за какой вариант вы голосуете.');
    } else {
	jQuery.post(form.attr('action'), {'case':caseVal}, surveySubmitCompleteHandler(form));
    }
}

function showVoteResults(selector, get_affix) {
    get_affix = get_affix ? get_affix : ''
    $(selector).each(function() {
        var form = $(this);
	var obj_id = form.find('input[name=object_id]').val();
	var vote_list = getCachedVoteList(form);
	var has_been_voted = false;
	for (var i=0; i<vote_list.length; i++) {
	    if (obj_id == vote_list[i]) {
		jQuery.get(form.attr('action') + get_affix, {}, surveySubmitCompleteHandler(form));
		has_been_voted = true;
		break;
	    }
	}
	if (!has_been_voted) {
	    form.show();
	}
    });
}

function showSurveyResults(selector, get_affix) {
    get_affix = get_affix ? get_affix : ''
    $(selector).each(function() {
        var form = $(this);
	var obj_id = form.find('input[name=object_id]').val();
	var vote_list = getCachedVoteList(form);
	var has_been_voted = false;
	for (var i=0; i<vote_list.length; i++) {
	    if (obj_id == vote_list[i]) {
		has_been_voted = true;
		break;
	    }
	}
    if (has_been_voted) {
        form.find('#vote_button').css('display', 'none');
        form.find('#vote_message').show();
    }
    });
}

function submitMaterialVote(el, verdict) {
    var btn = $(el);
    var form = btn.parents('form').eq(0);
    jQuery.post(form.attr('action'), verdict ? {'yes':1} : {'no':1}, surveySubmitCompleteHandler(form));
}

function showSurveyBlogCode(survey_url) {
    jQuery.post(survey_url, function(result) {
        $('#blog_code').find('textarea').val(result);
    });
    $('#blog_code').show(100);
}

function getClosedPolls(page) {
    jQuery.post("/get_closed_polls/", {page: page}, function(result) {
        $('#closed-polls').html(result);
    });
}

function submitSurveySubscription(el) {
    var btn = $(el);
    var form = btn.parents('form').eq(0);
    var checkbox = form.find('input:checkbox:checked');
    if (checkbox.val()!=null) {
        form.submit();
    }
}

$(document).ready(function() {
   //showVoteResults('div.survey form');
   showVoteResults('div.opinion form');
   showSurveyResults('div.g2-poll-block form');
   showSurveyResults('div.g2-block-polls-variants form');
   showSurveyResults('div.g2-single-poll-block form');
});
