var slide = new Array(3);
var question_title_cache;
var bar_colour_type = 'gradient'; // default  
var colours = ['#007EC3', '#87C2E3']; // defaults
var current = '';
var previous = ''; 
 

function toggleOptions(id)
{
    if($(id+'_container') != null && $(id+'_legend') != null) { 
        if($(id+'_container').parentNode.getStyle('height') == "0px") {
            slide[id].slideIn();
            $(id+'_img').src = 'graphics/SmallButtons_ArrowUp.gif';        
        }
        else {
            slide[id].slideOut();
            $(id+'_img').src = 'graphics/SmallButtons_ArrowDown.gif';        
        }
    }    
}

function setLoading()
{
    if($('chart_div') != null && $('chartloading') != null) {
        var loadingimg = $('loadingimage');
        loadingimg.src = 'graphics/chartloading.gif'; 
        $('chartloading').removeClass('loaded');
        $('loadingmessage').innerHTML = 'Chart Loading';
        loadingslide.show();
    }
}
function setLoaded()
{
    if($('chart_div') != null && $('chartloading') != null) { 
        var loadingimg = $('loadingimage');
        loadingimg.src = 'graphics/LoadedTick.gif';
        $('chartloading').addClass('loaded');
        $('loadingmessage').innerHTML = 'Chart Loaded!';  
        loadingslide.show();
    }
}
function hideLoading()
{    
    if($('chart_div') != null && $('chartloading') != null) {
        loadingslide.hide();
    }
}    

function showOverlay(id)
{                                         
    // hide any select boxes
    hideSelects();

    var currentwidth = $(id).getStyle('width');
    currentwidth = currentwidth.replace(/px/, '');  
    var left = (window.getWidth()/2)- (currentwidth/2);
    $('overlay').setStyle('opacity', 0.8);
    $('overlay').setStyle('display', 'block');
    $(id).setStyle('left', left+'px');
    $(id).setStyle('display', 'block');
    return false;
}

function hideOverlay(id)
{    
    // check at least one checkbox is checked
    var checked = 0;
    var num = 0;
    var onenotchecked = false;                                      
    var onechecked = false;
    $ES('input', id).each(function(el){
        if(el.checked == true) {
            onechecked = true;
            checked++
        }
        num++;
    });
    
    if(checked == num-1) onenotchecked = true;
    
    // hide the form and update the chart if one is checked
    if((id != 'opinion_exclude_options_overlay' && onechecked) || (id == 'opinion_exclude_options_overlay' && !onenotchecked) || id == 'exclude_statements_overlay') {
        $(id).setStyle('display', 'none'); 
        $('overlay').setStyle('display', 'none');
        $('overlay').setStyle('opacity', 0);
        refreshChart();
        
        // show any select boxes
        showSelects();
    }
    else if(id == 'opinion_exclude_options_overlay' && onenotchecked) {
        alert('At least one option must be included');
    }
    else {
        alert('At least one option must be checked');
    }                                        
    return false;
}
    
window.addEvent('domready', function() { 
    
    if($$('.Tips') != null) {
        var Tips4 = new Tips($$('.Tips'), {
                initialize:function(){
            this.fx = new Fx.Style(this.toolTip, 'opacity', {duration: 500, wait: false}).set(0);
        },
        onShow: function(toolTip) {
            this.fx.start(1);
        },
        onHide: function(toolTip) {
            this.fx.start(0);
        },
        className: 'charttooltip'
                });
    }
    
    if($('chart_div') != null && $('chartloading') != null) {
        loadingslide = new Fx.Slide($('chartloading'));
    }
    
    if($('basicoptions_container') != null && $('basicoptions_legend') != null) {  
        slide['basicoptions'] = new Fx.Slide($('basicoptions_container'));  
        $('basicoptions_legend').addEvent('click', function(e){
            e = new Event(e);                                               
            toggleOptions('basicoptions');
            e.stop(); 
        });   
    }
    
    if($('advancedoptions_container') != null && $('advancedoptions_legend') != null) {  
        slide['advancedoptions'] = new Fx.Slide($('advancedoptions_container'));  
        $('advancedoptions_legend').addEvent('click', function(e){
            e = new Event(e);                                               
            toggleOptions('advancedoptions');
            e.stop(); 
        });   
    }
    
    if($('saveoptions_container') != null && $('saveoptions_legend') != null) {  
        slide['saveoptions'] = new Fx.Slide($('saveoptions_container'));  
        $('saveoptions_legend').addEvent('click', function(e){
            e = new Event(e);                                               
            toggleOptions('saveoptions');
            e.stop(); 
        });   
    }
    
    var picker = new MooRainbow('colourpicker', { 

        id: 'cp',         
        startColor: [58, 142, 246],
        imgPath: 'charts/images/', 
        onComplete: function(color) {  
            colours[$('select_colour').value-1] = color.hex; 
            $('chosen_colour').value = color.hex;
            $('chosen_colour').setStyle('background-color', color.hex);
            refreshChart();
        } 
    });   
      
    toggleOptions('advancedoptions');
    if($('chart_div') != null && $('chartloading') != null) {
        loadingslide.hide(); 
    }
    
    if($('qid') != null) {
        if($('qid').value == 'dummy') {
            getChartShowOptions();
        }
    }   
     
}); 

/* retrieves the URL by observing the various comboboxes */
function getURL() {
    var url = 'charts/chart.php?';
    var query_string = $('chart_form').toQueryString();
    var colours_query_string = '';
    if($('bar_colour_type').value == 'solid' || $('opinion_rating_colours_div').getStyle('display') == 'none' && ($('requested_chart_type').value == 'SR_line' || $('requested_chart_type').value == 'SR_pie' || $('mr_requested_chart_type').value == 'MR_line'))
    {
        var hex = $('chosen_colour').value;
        colours_query_string += '&options[solidcolour_hex]=' + hex.replace(/#/, '');
    }
    else if($('bar_colour_type').value == 'gradient')
    {
        var hex1 = colours[0];
        var hex2 = colours[1];
        colours_query_string += '&options[gradientcolour1_hex]=' + hex1.replace(/#/, '');
        colours_query_string += '&options[gradientcolour2_hex]=' + hex2.replace(/#/, '');
    }
    if($('filter') != null)
    {
        query_string += '&filter=' + $('filter').value;
    }
    //var thumbnailurl = 'charts/thumb.php?width=250&filename=';
    //return thumbnailurl;   
    return url + query_string + colours_query_string; 
} 

/* replaces the chart image with new one with given url */
function getChart(url, setloadedbool) { 
    if(setloadedbool == null) {
        setloadedbool = true;
    }
    if($('chart_image') == null) {
        var img = document.createElement('img');
        img.src = url;
        img.id = 'chart_image';
        img.onload = function(evt) {
            var div = $('chart_div');
            div.appendChild(img);
            if(setloadedbool) {
                setLoaded(); 
            }
            else {
                hideLoading();
            }
        }
    }
    else {
        var img = $('chart_image');
        img.src = url;
        img.onload = function(evt) {
            if(setloadedbool) {
                setLoaded();
            }
            else {
                hideLoading();
            }
        }
    }                                         
    return false;   
}

function getChartShowOptions() {
    // show the possible chart options 
    setLoading();
    getChartType();   
    return false;
}

function refreshChart() { 
    setLoading();
    getChart(getURL());
    return false;
}

function downloadChart() {
    var url = getURL();
    url += '&options[download]=true';
    window.location.href=url;
    return false;
}
function saveChart() {
    showOverlayLoaded();
    var url = getURL();  
    url += '&options[save]=true';                      
    var myAjax = new Ajax(url, {
        method: 'get',
        onComplete: setOverlayLoaded          
    }).request();            
    return false;
}

function setOverlayLoaded() {
    $('savingoverlayimage').src= 'graphics/LoadedTick.gif';
    $('savingoverlayimage').alt='Loaded';
    $('savingoverlaymessage').innerHTML = 'Your chart has been saved and is viewable in the Custom Charts tab.';
    $('savingoverlaybutton').setStyle('display', 'inline');
}

function showOverlayLoaded() {
    // hide any select boxes
    hideSelects();
    var currentwidth = $('savingoverlay').getStyle('width');
    currentwidth = currentwidth.replace(/px/, '');  
    var left = (window.getWidth()/2)- (currentwidth/2);
    $('savingoverlay').setStyle('left', left+'px');
    $('overlay').setStyle('display', 'block');
    $('overlay').setStyle('opacity', 0.8);  
    $('savingoverlayimage').src= 'graphics/chartloading.gif';
    $('savingoverlayimage').alt='Saving';
    $('savingoverlaymessage').innerHTML = 'Please wait while your chart is saved.';
    $('savingoverlaybutton').setStyle('display', 'none');
    $('savingoverlay').setStyle('display', 'block');
}

function hideOverlayLoaded() {
    $('overlay').setStyle('display', 'none');
    $('overlay').setStyle('opacity', 0);
    $('savingoverlay').setStyle('display', 'none');
    // show any select boxes
    showSelects();
}

function showHelpOverlay() {
    // hide any select boxes
    hideSelects();
    var currentwidth = $('helpoverlay').getStyle('width');
    currentwidth = currentwidth.replace(/px/, '');  
    var left = (window.getWidth()/2)- (currentwidth/2);
    $('helpoverlay').setStyle('left', left+'px');
    $('overlay').setStyle('display', 'block');
    $('overlay').setStyle('opacity', 0.8);
    $('helpoverlay').setStyle('display', 'block');
}

function hideHelpOverlay() {
    $('overlay').setStyle('display', 'none');
    $('overlay').setStyle('opacity', 0);
    $('helpoverlay').setStyle('display', 'none');
    // show any select boxes
    showSelects();
}

function showNoDataOverlay() {
    hideSelects();
    var currentwidth = $('nodataoverlay').getStyle('width');
    currentwidth = currentwidth.replace(/px/, '');  
    var left = (window.getWidth()/2)- (currentwidth/2);
    $('nodataoverlay').setStyle('left', left+'px');
    $('overlay').setStyle('display', 'block');
    $('overlay').setStyle('opacity', 0.8);
    $('nodataoverlay').setStyle('display', 'block');
}

function hideNoDataOverlay() {
    window.location = 'manage.php';
}

function generateDefaultCharts() {

    // hide any select boxes
    hideSelects();
    
    var currentwidth = $('generateoverlay').getStyle('width');
    currentwidth = currentwidth.replace(/px/, '');  
    var left = (window.getWidth()/2)- (currentwidth/2);
    
    $('generateoverlay').setStyle('left', left+'px');
    
    
    $('overlay').setStyle('display', 'block');
    $('overlay').setStyle('opacity', 0.8);
      
    $('generateoverlay').setStyle('display', 'block');
    $('generateoverlaybutton').setStyle('display', 'none');
    
    var url = "charts/get_questions.php?";
    var query_string = $('chart_form').toQueryString();
    var myAjax = new Ajax(url + query_string, {
        method: 'get',
        onComplete: generateCallBack
    }).request();

    
    return false;
}

function generateCallBack(responseText, responseXML)
{
    var numquestions = responseXML.getElementsByTagName('questions')[0].firstChild.data;
    generateChart(0, numquestions);
}

function redirectToDefault()
{
    var sid = $('sid').value;
    window.location = "chart.php?sid="+sid+"&chart_section=standard";
    return false;
}

function doGenerateChart(responseText, responseXML)
{
    var id = responseXML.getElementsByTagName('id')[0].firstChild.data;
    var maxid = responseXML.getElementsByTagName('maxid')[0].firstChild.data;
    id = parseInt(id);
    generateChart(id+1, maxid);
}

function generateChart(id, maxid) {
    
    if(id > maxid) {
        // set overlay to loaded
        $('generateoverlayimage').src= 'graphics/LoadedTick.gif';
        $('generateoverlayimage').alt='Loaded';
        $('generateoverlaymessage').innerHTML = 'Your charts have been saved and are viewable in the Standard Charts tab.';
        $('generateoverlaybutton').setStyle('display', 'inline');
    }
    else {
        // set progress in overlay
        var progress = (parseInt(id)+1)+'/'+(parseInt(maxid)+1);
        
        var percentage = Math.round(((parseInt(id)+1) / (parseInt(maxid)+1))*100) * 2;
        var progresspercentage = percentage + 'px';
        $('progressinner').setStyle('width', progresspercentage);
        $('generateoverlaymessage').innerHTML = 'Please wait while your charts are generated ('+progress+')...';
        // save chart
        var url = getURL();  
        url += '&options[savedefault]=true';                      
        var myAjax = new Ajax(url+'&q_title='+id, {
            method: 'get',
            onComplete: doGenerateChart          
        }).request(); 
    }
}

function changeColourType(activate) {
    if(activate == null) {
        activate = false;
    }
    var type = $('bar_colour_type').value;
    if(type == 'solid') {
        showField('colour');
        $('select_colour').setProperty('disabled', 'true');
        $('select_colour').setStyle('display', 'none'); 
        showField('chosen_colour');
    }
    else if(type == 'gradient') {
        if($('opinion_rating_colours_div').getStyle('display') != 'none' && $('qid') == null)
        {
            showField('colour');
            $('select_colour').setProperty('disabled', 'true');
            $('select_colour').setStyle('display', 'none'); 
            showField('chosen_colour');
        }
        else
        {         
            showField('colour');
            $('select_colour').removeProperty('disabled');
            $('select_colour').setStyle('display', 'inline');
            showField('chosen_colour');
        }
    } 
    if(activate) {
        refreshChart();
    }         
    return false;
}

function changeColour()
{        
    colours[$('select_colour').value-1] = $('colour').value;
    setField('colour', 'chosen_colour');                                                    
    $('chosen_colour').setStyle('background-color', $('colour').value);  
    return refreshChart(); 
}

function changeSelectColour()
{                                                            
    $('chosen_colour').value = colours[$('select_colour').value-1];
    $('chosen_colour').setStyle('background-color', colours[$('select_colour').value-1]);
    return refreshChart();
}

function setTitle(title) {
    if($('custom_title') != null) {
        $('custom_title').value = title;
    }
} 
function resetTitle() {
    if($('custom_title') != null) {
        $('custom_title').value = question_title_cache;
    }
    refreshChart();
    return false;
}

/* get the height the div should be by observing how many unhidden divs are children of it */
function setHeight(id) {
    var hidden = $(id).getElements('div.hidden'); // retrieve all the divs which are hidden
    var all = $(id).getElements('div'); // retrieve all the divs
    var height = ((all.length-hidden.length)*25); // calculate the height that the id should be
    if(!($(id).parentNode.getStyle('height') == '0px')) { // if the dropdown is not hidden
        $(id).parentNode.setStyle('height', height+'px'); // change the height to the appropriate height
    }
}

function showOptions(response) {

    var type = response.getElementsByTagName('chart_type')[0].firstChild.data;
    var question_title = response.getElementsByTagName('question_title')[0].firstChild.data; 
    var num_statements = response.getElementsByTagName('num_statements')[0].firstChild.data;
    question_title_cache = question_title;
    
    previous = current;
    current = type;
    
    if(type == 'dummy') {
        changeColourType();
        changeSelectColour();
    }
    else if(type == 'SR') {
                  
        /* POPULATE THE EXCLUDE STATEMENTS OVERLAY */
        var html = '';                                 
        var statements = response.getElementsByTagName('statement');
        for(i=0; i<statements.length; i++) {
            html += '<label>' + statements[i].getElementsByTagName('label')[0].firstChild.data + '<input type="checkbox" name="exclude_statements[' + statements[i].getElementsByTagName('n')[0].firstChild.data + ']" value="true"/></label><br/>';
        }        
        $('exclude_statements_overlay_options').innerHTML = html;
        
        // hide the information messages
        hideField('information');   
        hideField('advanced_information');
        hideField('saveoptions_information');
        
        // show the allowed fields for SR type questions
        showField('requested_chart_type');   
        if(num_statements > 4) {
            if(current != previous)
            {
                $('requested_chart_type').selectedIndex = 1;
            }
        }
        showField('value_type');
        showField('decimal_places');
        showField('order');            
        showField('custom_title');        
        showField('base');
        hideField('top');
        hideField('showposneg');
        setTitle(question_title);
        hideField('mr_requested_chart_type');
        hideField('ps_requested_chart_type');
        
        if($('requested_chart_type').value == 'SR_col' || $('requested_chart_type').value == 'SR_bar') {  
            showField('bar_colour_type');
            showField('colour');
            showField('chosen_colour');
            changeColourType();
            changeSelectColour();            
        }
        else if($('requested_chart_type').value == 'SR_line' || $('requested_chart_type').value == 'SR_pie') {
            hideField('bar_colour_type');
            showField('colour');
            $('select_colour').setProperty('disabled', 'true');
            $('select_colour').setStyle('display', 'none'); 
            showField('chosen_colour'); 
        }
        else {
            hideField('bar_colour_type'); 
            hideField('colour');
            hideField('chosen_colour');  
        } 
        hideField('opinion_order_toggle_overlay');
        hideField('opinion_exclude_options_toggle_overlay');
        showField('exclude_statements_toggle_overlay');
        hideField('opinion_rating_colours');
        showField('download');
        showField('refresh');
        showField('save');
                                                
        // correct the heights of the dropdowns
        setHeight('basicoptions_container'); 
        setHeight('advancedoptions_container');
        setHeight('saveoptions_container');       
    }
    
    else if(type == "MR") {
    
        /* POPULATE THE EXCLUDE STATEMENTS OVERLAY */
        var html = '';
        var statements = response.getElementsByTagName('statement');
        for(i=0; i<statements.length; i++) {
            html += '<label>' + statements[i].getElementsByTagName('label')[0].firstChild.data + '<input type="checkbox" name="exclude_statements[' + statements[i].getElementsByTagName('n')[0].firstChild.data + ']" value="true"/></label><br/>';
        }        
        $('exclude_statements_overlay_options').innerHTML = html;
        
        // hide the information messages
        hideField('information');
        hideField('advanced_information');
        hideField('saveoptions_information');
        
        // show the allowed fields for MR type questions   
        showField('decimal_places'); 
        showField('order');          
        hideField('value_type');  
        showField('mr_requested_chart_type');
        hideField('ps_requested_chart_type');
        
        if(num_statements > 4) {
            if(current != previous)
            {
                $('mr_requested_chart_type').selectedIndex = 1;
            }
        }
        
        if($('mr_requested_chart_type').value == 'MR_col' || $('mr_requested_chart_type').value == 'MR_bar') {
            showField('bar_colour_type');
            showField('colour');
            showField('chosen_colour');
            changeColourType();
            changeSelectColour();
        }
        else if($('mr_requested_chart_type').value == 'MR_line') {
            hideField('bar_colour_type');
            showField('colour');
            $('select_colour').setProperty('disabled', 'true');
            $('select_colour').setStyle('display', 'none'); 
            showField('chosen_colour'); 
        }
        else {
            hideField('bar_colour_type'); 
            hideField('colour');
            hideField('chosen_colour');
        }
        showField('custom_title');              
        showField('base');
        hideField('top');
        hideField('showposneg');
        hideField('opinion_order_toggle_overlay');
        hideField('opinion_exclude_options_toggle_overlay');   
        showField('exclude_statements_toggle_overlay');
        hideField('opinion_rating_colours');
        setTitle(question_title);
        
        // hide the disallowed fields for SROX type questions
        hideField('requested_chart_type');
        showField('download');
        showField('refresh'); 
        showField('save');       
        
        // correct the heights of the dropdowns 
        setHeight('basicoptions_container'); 
        setHeight('advancedoptions_container');
        setHeight('saveoptions_container');
        
    }
    
    else if(type == "SROX") {
    
        /* POPULATE THE OPINIONS ORDER OVERLAY */
        var html = '';
        var opinions = response.getElementsByTagName('opinion');
        for(i=0; i<opinions.length; i++) {
            html += '<label>' + opinions[i].getElementsByTagName('label')[0].firstChild.data + '<input type="checkbox" name="opinion_order[' + opinions[i].getElementsByTagName('n')[0].firstChild.data + ']" value="true"';
            if(opinions[i].getElementsByTagName('checked')[0].firstChild.data == 'true')
            {
                html += ' checked';
            }
            html += '/></label><br/>';
        }          
        $('opinion_order_overlay_options').innerHTML = html;
        
        /* POPULATE THE OPINIONS EXCLUDE OPTIONS OVERLAY */
        var html = '';
        var opinions = response.getElementsByTagName('opinion');
        for(i=0; i<opinions.length; i++) {
            html += '<label>' + opinions[i].getElementsByTagName('label')[0].firstChild.data + '<input type="checkbox" name="opinion_exclude_options[' + opinions[i].getElementsByTagName('n')[0].firstChild.data + ']" value="true"';
            if(opinions[i].getElementsByTagName('ignore')[0].firstChild.data == 'true')
            {
                html += ' checked';
            }
            html += '/></label><br/>';
        }        
        $('opinion_exclude_options_overlay_options').innerHTML = html;
        
        /* POPULATE THE EXCLUDE STATEMENTS OVERLAY */
        var html = '';
        var statements = response.getElementsByTagName('statement');
        for(i=0; i<statements.length; i++) {
            html += '<label>' + statements[i].getElementsByTagName('label')[0].firstChild.data + '<input type="checkbox" name="exclude_statements[' + statements[i].getElementsByTagName('n')[0].firstChild.data + ']" value="true"/></label><br/>';
        }        
        $('exclude_statements_overlay_options').innerHTML = html;
        
        /* SHOW/HIDE OPTIONS AND INFORMATION MESSAGES */
        /* BASIC */                      
        hideField('information'); // information message               
        hideField('requested_chart_type');
        hideField('mr_requested_chart_type');
        hideField('ps_requested_chart_type');
        showField('opinion_order_toggle_overlay');
        showField('opinion_exclude_options_toggle_overlay');   
        showField('exclude_statements_toggle_overlay');
        showField('bar_colour_type'); 
        hideField('colour');
        hideField('chosen_colour');
        showField('opinion_rating_colours');
        changeOpinionColour();
        changeSelectColour();
        /* ADVANCED */
        hideField('advanced_information'); // information message
        hideField('value_type'); 
        showField('decimal_places');     
        hideField('order');             
        showField('custom_title');        
        showField('base');
        hideField('top');
        hideField('showposneg');
        /* SAVE */
        showField('download');
        showField('refresh');
        showField('save');
        hideField('saveoptions_information');
        
        /* SET THE TITLE TO THE NEW QUESTION */
        setTitle(question_title);
        
        /* CORRECT HEIGHT OF DROPDOWNS */
        setHeight('basicoptions_container'); 
        setHeight('advancedoptions_container');
        setHeight('saveoptions_container');   
    }
    else if(type == "PS") {
        /* SHOW/HIDE OPTIONS AND INFORMATION MESSAGES */
        /* BASIC */                      
        hideField('information'); // information message               
        hideField('requested_chart_type');
        hideField('mr_requested_chart_type');
        showField('ps_requested_chart_type');
        hideField('opinion_order_toggle_overlay');
        hideField('opinion_exclude_options_toggle_overlay');      
        hideField('exclude_statements_toggle_overlay');
        showField('bar_colour_type'); 
        showField('colour');
        showField('chosen_colour');
        hideField('opinion_rating_colours'); 
        changeColourType();
        changeSelectColour();
        /* ADVANCED */
        hideField('advanced_information'); // information message
        hideField('value_type'); 
        if($('ps_requested_chart_type').value == 'PS_bipolar') {
            showField('decimal_places');
            showField('showposneg');
            hideField('top');
        }
        else {                          
            hideField('decimal_places');
            hideField('showposneg');
            showField('top');
        }                               
        hideField('order');         
        showField('custom_title');         
        showField('base');     
        var tophtml = '<option value="all">All</option>';
        for(i=1; i<parseInt(num_statements)+1; i++) {
            tophtml += '<option value="'+i+'">Top '+i+'</option>';
        }                         
        $('top').innerHTML = tophtml;
        /* SAVE */
        showField('download');
        showField('refresh');
        showField('save');
        hideField('saveoptions_information');     
        
        /* SET THE TITLE TO THE NEW QUESTION */
        setTitle(question_title);
        
        /* CORRECT HEIGHT OF DROPDOWNS */
        setHeight('basicoptions_container'); 
        setHeight('advancedoptions_container');
        setHeight('saveoptions_container');          
    }
    else if(type == "none") {       
        /* SHOW/HIDE OPTIONS AND INFORMATION MESSAGES */
        /* BASIC */                      
        showField('information'); // information message               
        hideField('requested_chart_type');
        hideField('mr_requested_chart_type');
        hideField('ps_requested_chart_type');
        hideField('opinion_order_toggle_overlay');            
        hideField('exclude_statements_toggle_overlay');
        hideField('bar_colour_type'); 
        hideField('colour');
        hideField('chosen_colour');
        hideField('opinion_rating_colours'); 
        /* ADVANCED */
        showField('advanced_information'); // information message
        hideField('value_type'); 
        hideField('decimal_places');     
        hideField('order');
        hideField('opinionorder');
        hideField('custom_title');       
        hideField('base');
        hideField('top');
        hideField('showposneg');
        /* SAVE */
        hideField('download');
        hideField('refresh');
        hideField('save');
        showField('saveoptions_information');
        
        /* SET THE TITLE TO THE NEW QUESTION */
        setTitle(question_title);
        
        /* CORRECT HEIGHT OF DROPDOWNS */
        setHeight('basicoptions_container'); 
        setHeight('advancedoptions_container');
        setHeight('saveoptions_container');                      
    }
    
    // show the chart
    if(type != "none") {   
        getChart(getURL());          
    }   
    else {
        getChart('graphics/Please-select-a-question.gif', false);
    }                   
}

function hideField(id) {   
    /* disable the element, then hide it */
    if($(id) != null) {
        $(id).setProperty('disabled', 'true'); 
    }
    if($(id+'_div') != null) {
        $(id+'_div').addClass('hidden');
    }  
}

function showField(id) { 
    /* enable the elementm then show it */
    if($(id) != null) {
        $(id).removeProperty('disabled');
    }
    if($(id+'_div') != null) {
        $(id+'_div').removeClass('hidden');     
    }
}

function setField(from, to) {
    if($(from) != null && $(to) != null) {
        $(to).value = $(from).value;
    }
    return refreshChart();
}

function getChartType() {                             
    var url = "charts/get_options.php?";
    var query_string = $('chart_form').toQueryString();
    var myAjax = new Ajax(url + query_string, {
        method: 'get',
        onComplete: ajaxCallback
    }).request();
}

function ajaxCallback(responseText, responseXML)
{                    
    showOptions(responseXML);
}

function hideSelects()
{
    // hide any select boxes
    $ES('select', 'chartwindow').each(function(el){
        el.setStyle('display', 'none');
    });
    return false;
}

function showSelects()
{
    // show any select boxes
    $ES('select', 'chartwindow').each(function(el){
        el.setStyle('display', 'inline');
    });
    return false
}

function redirectToCustomNewFilter()
{
    window.location = 'chart.php?sid=' + $('sid').value + '&chart_section=custom&filter=' + $('filter').value;
}

function changeOpinionColour()
{    
    if($('opinion_rating_colours').value == 'multi')
    {
        // hide colour selection
        hideField('colour');
        $('select_colour').setProperty('disabled', 'true');
        $('select_colour').setStyle('display', 'none'); 
        hideField('chosen_colour');
    }
    else if($('opinion_rating_colours').value == 'shades')
    {
        // show colour selection
        showField('colour');
        $('select_colour').setProperty('disabled', 'true');
        $('select_colour').setStyle('display', 'none'); 
        showField('chosen_colour');
    }
    
    // re-generate chart 
    setHeight('basicoptions_container');
    refreshChart(); 
}