// Checks if form has required fields & if they have content 
$('form').submit(function(){
    
    // Define return state
    var state    = true;
    var position = 0;
    
    // Iterate all input fields
    $('form fieldset').each(function(){
        if(!$(this).find('input[@type=radio]:checked').size()){            
            if(state){
                position = ($(this).position().top-20);
            }            
            state = false;
            $(this).addClass('missing');
            $(this).find('input[@type=radio]').click(function(){
                $(this).parent().parent().parent().removeClass('missing');
            });            
        }        
    });
    
    // Return & show error message
    if(!state)$.scrollTo(position, 0, {onAfter:function(){alert('Var god och välj ett alternativ per fråga.');}});    
    return state;
});

// Add done look
$('form').find('input[@type=radio]').click(function(){
    $(this).parent().parent().parent().addClass('done');
});

// Remove links from result-table
$('body#results td a').each(function(){
    var text = $(this).text();
    $(this).parent().append(text);
    $(this).remove();
});

// Table link handlers
$('body#results tbody tr').mouseover(function(){$(this).addClass('hover')});
$('body#results tbody tr').mouseout(function(){$(this).removeClass('hover')});

// Show candidate in thickbox
$('body#results tbody tr').click(function(){
    if(!$(this).parent().hasClass('rest')){    
        var sUrl    = '/valmaskin/'+$(this).attr('rel');
        var sName   = $(this).find('td[rel="name"]').text();
        var sParty  = $(this).find('td[rel="party"]').text(); 
        tb_show(sName+' - '+sParty,sUrl+'?keepThis=true&TB_iframe=true&height=600&width=870');
    }
    return;    
});
// Show rest of candidates
$('body#results thead.rest tr').click(function(){
    $(this).parent().removeClass('rest');
    $(this).parent().addClass('visible');
    $(this).parent().next().removeClass('rest');
    $(this).parent().next().addClass('visible');    
    return false;
});

// Statistics popup
$('body#statistics tr.answer-text').addClass('thickbox-hidden');
$('body#statistics tr.answer').mouseover(function(){$(this).addClass('hover')});
$('body#statistics tr.answer').mouseout(function(){$(this).removeClass('hover')});
$('body#statistics tr.answer').click(function(){
    var sName   = $(this).find('td.question strong').text();
    var sId     = $(this).next().attr('id');
    tb_show(sName,'#TB_inline?inlineId='+sId+'&height=600&width=870');
});

// External links
$('a').click(function(){
    if($(this).attr('rel') == 'external'){
        window.open(this.href);
        return false;
    }else{
        return true;
    }
});
