/**
 * @author Adam Mielko
 * @copyright 4e, 2009
 * @version $Id$
 */
var e4PollPlugin = {
    submit: function($target){
        $.ajax({
            type: 'POST',
            url: $target.attr('action'),
            data: $target.serialize(),
            success: function(msg){
                $target.parent().parent().parent().html(msg);
            },
            beforeSend: function(){
                $target.parent().parent().parent().append('<div class="ajax-loader">  </div>');
                $target.parent().parent().parent().children('.ajax-loader').css('opacity', .4).css('height');
            }
        });
    },
    
    result: function(id){
        $this = $('#' + 'plugin-poll-container-' + id);
        $.ajax({
            type: 'POST',
            url: 'poll/plugin/build',
            dataType: 'html',
            data: 'poll_id=' + id + '&show_results=1',
            success: function(msg){
                $this.children('.plugin-poll-form-container').hide();
                $this.children('.ajax-loader').hide();
                $this.append(msg);
            },
            beforeSend: function(){
                $this.append('<div class="ajax-loader">  </div>');
                $this.children('.ajax-loader').css('opacity', .4);
            }
        });
    },
    
    build: function($this){
        $.ajax({
            type: 'POST',
            url: 'poll/plugin/build',
            dataType: 'html',
            data: 'poll_id=' + $this.attr('id').substr($this.attr('id').lastIndexOf('-') + 1),
            success: function(msg){
                $this.html(msg);
            },
            beforeSend: function(){
                $this.html('<div class="ajax-loader">  </div>');
                $this.children('.ajax-loader').css('opacity', .4);
            }
        });
    }
};

$(function(){
    $('.plugin-poll-container').listen('click', 'a.poll-results', function(e){
        e.preventDefault();
        var $this = $(this).parent().parent();
        if ($this.children('.poll-plugin-results').length) {
            $this.children('.poll-plugin-results').show();
            $this.children('.plugin-poll-form-container').hide();
        }
        else {
            var id = $(this).attr('href').substr($(this).attr('href').lastIndexOf('/') + 1);
            e4PollPlugin.result(id);
        }
    });
    
    $.listen('click', 'a.poll-vote', function(e){
        e.preventDefault();
        var $this = $(this).parent().parent();
        $this.children('.poll-plugin-results').hide();
        $this.children('.plugin-poll-form-container').show();
    });
});

