////////////////////////////////////////////////////////////////////////////////
//
// Javascript file planit common functions
//
////////////////////////////////////////////////////////////////////////////////

var currentPlanitTab = 1;

//if you think you need more tabs than this, you're probably insane. admittedly 
//it's not a particularly extensible design, but it shouldn't cause too many problems :)
var MAX_PLANIT_TABS = 99; 
var disabledPlanitTabs = new Array(MAX_PLANIT_TABS + 1); 

//initialise the array
for (i=0; i<MAX_PLANIT_TABS+1; i++)
{
    disabledPlanitTabs[i] = 0;
}

function updateCombinationTitle(obj)
{
    // base title details
    var title_tag        = document.getElementById("title");

    var base_description = ""; 

    // for each override field, build string which contains the selected values    

    var select_tags = document.getElementsByTagName("select");
    
    var previous = "";
    var previous_index = 0;
    var current  = "";
    
    var range_field = false;
    var update_count     = 0;
    
    for (i = 0; i < select_tags.length;++i)
    {
        var tag = select_tags[i];
        
        var current = tag.name;

        if ((previous.length > 0) && (current == previous) && (previous_index > 0))
        {
            range_field = true;        
        }        
        
        if (range_field)
        {
            if (tag.selectedIndex > 0)
            {
                base_description += " to ";
                base_description += tag.options[tag.selectedIndex].innerHTML;
                range_field = false;
            }
        }
        else
        {
            if (tag.selectedIndex > 0)
            {
                // do not include a '&' directly after title (title is first description to add).
                if (update_count == 1)
                {
                    base_description += " ";
                }
                else if (update_count > 1)
                {
                    base_description += " & ";
                }
            
                base_description += tag.options[tag.selectedIndex].innerHTML;        
                update_count++;
            }    
        }
    
        previous       = current;
        previous_index = tag.selectedIndex;
    }
    
    base_description = base_description.replace("&amp;", "&"); 
    title_tag.value = base_description;
}

function setPlanitButtonStatus(maxTab, enableFinishAt)
{
    var prev = document.getElementById("prev_button");
    var next = document.getElementById("next_button");
    var finish = document.getElementById("finish_button");

    if (currentPlanitTab == 1)
    {
        prev.disabled = true;
    }
    else
    {
        prev.disabled = false;
    }
}

function disablePlanitTab(tab, disableAllControls)
{   
    //make disableControls behave as though it has a default argument
    if (arguments.length <= 1)
        disableAllControls = true;
    
    if (tab > MAX_PLANIT_TABS || tab < 0)
    {
        return;
    }
    
    disabledPlanitTabs[tab]++;

    var directLink = document.getElementById("div_tab" + tab);
    if (directLink) //just in case we're not using direct links
    {
        directLink.className = "planit_tab_disabled";
    }

    //get all the input elements within this tab-page and disable them...
    var tabPage = document.getElementById("panel"+tab);
    if (tabPage && disableAllControls)
    {
        var formElements = tabPage.getElementsByTagName("input");
        for(i=0; i<formElements.length; i++)
        {
            formElements[i].disabled = true;
        }
    }

}

function enablePlanitTab(tab, force, enableAllControls)
{
    if (arguments.length < 3)
        enableAllControls = true;
    
    if (tab > MAX_PLANIT_TABS || tab < 0)
    {
        return;
    }

    if (force)
    {
        disabledPlanitTabs[tab] = 0;
    }
    else
    {
        disabledPlanitTabs[tab]--;    
        if (disabledPlanitTabs[tab] < 0)
        {
            disabledPlanitTabs[tab] = 0;
        }
    }
    
    if (enableAllControls && !disabledPlanitTabs[tab])
    {    
        var directLink = document.getElementById("div_tab" + tab);
        if (directLink) //just in case we're not using direct links
        {
            directLink.className = "planit_tab";
        }
        
        //get all the input elements within this tab-page and enable  them...
        var tabPage = document.getElementById("panel"+tab);
        if (tabPage)
        {
            var formElements = tabPage.getElementsByTagName("input");
            for(i=0; i<formElements.length; i++)
            {
                formElements[i].disabled = false;
            }
        }
    }
}

function nextPlanitTab(maxTab, enableFinishAt)
{
    if (currentPlanitTab == maxTab)
    {
        displayPlanitFinishTab(maxTab);
        return;
    }
    else
    {
        if (disabledPlanitTabs[++currentPlanitTab])
        {
            nextPlanitTab(maxTab, enableFinishAt);
            return;
        }
       
        selectPlanitTab(currentPlanitTab, maxTab);
        setPlanitButtonStatus(maxTab, enableFinishAt);
    }        
}

function previousPlanitTab(maxTab, enableFinishAt)
{
    if (disabledPlanitTabs[--currentPlanitTab])
    {
        previousPlanitTab(maxTab, enableFinishAt);
        return;
    }

    selectPlanitTab(currentPlanitTab, maxTab);
    setPlanitButtonStatus(maxTab, enableFinishAt);
}

function displayPlanitFinishTab(maxTab)
{
    for (i=1; i<=maxTab; i++)
    {
        disablePlanitTab(i, false, false);
    }
    
    var currentPlanitTabBackup = currentPlanitTab;
    selectPlanitTab(5, maxTab+1); //+1 to take account of the (usually irrelevant) finish tab
    currentPlanitTab = currentPlanitTabBackup;
    var wizardButtons = document.getElementById("wizard_buttons");
    wizardButtons.style.display = "none";

    var wizardButtonsFinal = document.getElementById("wizard_buttons_final");
    wizardButtonsFinal.style.display = "";

    // hide second finish button - used only in advanced mode
    var finish_button = document.getElementById("select_finish_button");
    finish_button.style.display="none";
}

function cancelPlanitFinishTab(maxTab)
{
    for (i=1; i<=maxTab; i++)
    {
        enablePlanitTab(i, false, false);
    }
    
    selectPlanitTab(currentPlanitTab, maxTab+1);  //+1 to take account of the (usually irrelevant) finish tab
    var wizardButtons = document.getElementById("wizard_buttons");
    wizardButtons.style.display = "";

    var wizardButtonsFinal = document.getElementById("wizard_buttons_final");
    wizardButtonsFinal.style.display = "none";
}

function showPlanitTab(section)
{
   document.getElementById(section).style.className = 'tab';
   document.getElementById(section).style.display = 'inline';
}

function hidePlanitTab(section)
{
   document.getElementById(section).style.className = 'tab';
   document.getElementById(section).style.display = 'none';
}

function displayPlanitTabs(selectbox)
{
   var i=1;
   while (i<selectbox.length)
   {
      if(selectbox[i].selected)
      {
         showPlanitTab(selectbox.options[i].value);
      }
      else
      {
         hidePlanitTab(selectbox.options[i].value)
      }
      i++;
   }
   reflow('reflow_div');
}


function finishAnalysing()
{
    var frm = document.forms["planit_form"];
    var planit_type = frm.planit_type;

    var download = document.getElementById("download_type");
    var download_type = download.options[download.selectedIndex].value;

    if (download_type == "vib") //"view in browser"
    {
        if (planit_type.value == "C")
        {
            // crosstab / graph mode
            graphDisplayFullSize();
        }
        else if (planit_type.value == "S" || planit_type.value == "R")
        {
            // schedule mode
            submitHtml();
        }
        else
        {
            // invalid mode
        }
    }
    else
    {
        submitForm(download_type);
    }
}


function waitForSearchToFinish()
{
    var button = document.getElementById('select_finish_button');
    if (button)
    {
        enableSubmitButton(button, false);
        var url = '/search/queue/finished/last';
        var args;
        var request = new AsynchRequest(url,
            // function on success
            function(response_text)
            {
                var response_components = response_text.split('\#\#');
                if (response_components[1] == 'SUCCESS')
                {
                    var number_results = parseInt(response_components[2], 10);
                    if (number_results > 0)
                    {
                        enableSubmitButton(button, true);
                        showWaitingMessage(false, null);
                    }
                    else
                    {
                        enableSubmitButton(button, false);
                        showWaitingMessage(true, 'Unable to submit a PlanIT report; your initial search didn\'t contain any results!');
                    }
                }
                else
                {
                    enableSubmitButton(button, false);
                    showWaitingMessage(true, 'Unable to submit a PlanIT report; your initial search did not complete successfully!');
                }

                // Expect response to begin with the delimiter
                if (response_components[0] != '' || 'SUCCESS' != response_components[1])
                {
                    var log_args = 'response='+encodeURIComponent(response_text);
                    var log_request = new AsynchRequest('/test/log_search_finished_error',
                        // success
                        function(log_result) {},
                        // start log_load
                        function() {},
                        // error
                        function() {},
                        "POST",
                        log_args
                        );
                    log_request.send();
                }
            },
            // function on start of load
            function()
            {
                enableSubmitButton(button, false);
                showWaitingMessage(true, null);
            },
            function()
            {
                enableSubmitButton(button, false);
                showWaitingMessage(true, 'An error occurred while finalizing data; unable to submit a PlanIT report!');
            },
            "GET",
            args
        );
        request.send();
    }
}

function enableSubmitButton(button, enable)
{
    if (enable)
    {
        button.disabled = false;
        button.style.opacity = '';
        button.style.filter = '';
    }
    else
    {
        button.disabled = true;
        button.style.opacity = '0.5';
        button.style.filter = 'alpha(opacity=50)';
    }
}

function showWaitingMessage(show, message_text)
{
    var td = document.getElementById('planit_waiting_message');
    if (td)
    {
        var tr = td.parentNode;
        if (tr)
        {
            if (show)
            {
                if (message_text)
                {
                    // if no message text is specified, use default message and color
                    td.innerHTML = '<img src="/images/compere/famfamfam_icons/error.png" style="border:none; padding:0; margin:0"/> ' + message_text;
                    td.style.color = 'red';
                }
                tr.style.display = '';
            }
            else
            {
                tr.style.display = 'none';
            }
        }
    }
}

function switchReportingMethod(obj, submit_url)
{
   var mode = obj.options[obj.selectedIndex].value;   
   document.location.href=submit_url + "&reporting_interface=" + mode;
}

function selectReportingMethod(method)
{
	var select = document.planit_form.reporting_interface;
	
	for (x=0;x<select.length;++x)
	{
		if (select.options[x].value==method)
		{
			select.options[x].selected=true;
		}
	}	
}

function selectAll(selectbox)
{
   var i=1;
   while (i<selectbox.length)
   {
      selectbox[i].selected = true;
      i++;
   }
   displayPlanitTabs(selectbox);
}

function selectPlanitTab(number, tab_count)
{
   currentPlanitTab = number;

   //if the selected tab is disabled, return now.
   if (disabledPlanitTabs[currentPlanitTab])
   {
       return;
   }
   
   var i=1;        
   while (i <= tab_count)
   {
      var panelId = "panel"+i;
      var tabId = "tab" + i;
      if (i == number)
      {  
         var tabLabel = document.getElementById("div_" + tabId)
         //tabLabel may not exist (final pane on planit-wizard, for example)
         if (tabLabel)
         {
             tabLabel.className = "planit_tab_active";
         }
         
         showPlanitTab(panelId);
      }
      else
      {
         if (disabledPlanitTabs[i])
         {
            var tabLabel = document.getElementById("div_" + tabId)
            //tabLabel may not exist (final pane on planit-wizard, for example)
            if (tabLabel)
            {
               tabLabel.className = "planit_tab_disabled";
            }
         }
         else
         {
            var tabLabel = document.getElementById("div_" + tabId)
            //tabLabel may not exist (final pane on planit-wizard, for example)
            if (tabLabel)
            {
                tabLabel.className = "planit_tab";
            }
         }
         hidePlanitTab(panelId);
      }
      i++;
   }
}


function showHideTag(id, tag, display)
{
    tags = document.getElementsByTagName(tag);
    for (var i = 0; i < tags.length; ++i)
    {
        if (tags[i].id == id)
        {
            if (display != null && display)
            {
                tags[i].style.display = '';
            }
            else if (display != null)
            {
                tags[i].style.display = 'none';
            }
            else
            {
                tags[i].style.display = (tags[i].style.display == '' ? 'none' : '');
            }
        }
    }
}

function displayWizard(type)
{
    // append fieldname
    var url = "/sinatra/compere/planit/" + type;
  
    var params = "width=500,height=250,menubar=no,top=150,left=150," +
                 "resizable=yes,toolbar=no,scrollbars=no";

    var wizard_window = window.open("", "wizard", params);

      var frm = document.forms["planit_form"];
    frm.command.value = "wizard";
    frm.action = url;
    frm.target = "wizard";
    frm.submit();
    frm.command.value="";
    return true;
}

function submitPlanitSearchTemplate()
{
    var frm             = document.forms["planit_form"];
    var template_select = frm.template_id;
    var chart_type      = frm.chart_type;
    
    if (template_select.selectedIndex > 0)
    {        
      //frm.template_id.value = template_select.options[template_select.selectedIndex].value;
      //frm.chart_type.value  = chart_type.options[chart_type.selectedIndex].value; 
      planit_form.submit();
    }
    else
    {
      alert("Please select a planit template to run");    
    }
}

function setupPlanitPenetration()
{
    // wizard form
    var wizard_frm = document.forms["planit_wizard"];
    
    // get grouping 0
    var grouping_0 = wizard_frm.grouping_0.options[wizard_frm.grouping_0.selectedIndex].value;
    
    // get grouping 1
    var grouping_1 = wizard_frm.grouping_1.options[wizard_frm.grouping_1.selectedIndex].value;
    
    // now get a reference to the opener
    
    var planit_form = window.opener.document.forms["planit_form"];
    
    if (planit_form)
    {
        if (grouping_0)
        {
                    
            // set grouping0 field
            var main_grouping0  = planit_form["grouping_0"];
            for (i = 0;i < main_grouping0.length;i++)
            {
                if (main_grouping0.options[i].value == grouping_0)
                {
                    main_grouping0.options[i].selected = true;
                }             
            }            
        }
        if (grouping_1)
        {
            // set grouping0 field
            var main_grouping1  = planit_form["grouping_1"];
            for (i = 0;i < main_grouping1.length;i++)
            {
                if (main_grouping1.options[i].value == grouping_1)
                {
                    main_grouping1.options[i].selected = true;
                }             
            } 
        }       
        
        // setup percentage type        
        var percentage_options = planit_form["percent_options"];
        for (i = 0;i < percentage_options.length;i++)
        {
            if (percentage_options.options[i].value == "column")
            {
                percentage_options.options[i].selected = true;
            }             
        } 

        var percent_type = planit_form.percentage_type;
        var percent_level = planit_form.percentage_level;
        // percent per column
        percent_type.value="penetration";
        percent_level.value="1";
    }    
    
    window.close();
}

function planit_goback()
{
    var frm = document.forms["planit_form"];
    var submit = frm.submit_url.value;
    frm.action = submit;
    frm.command.value = "";
    frm.submit();
    return true;
}

function submitForm(value)
{
    var frm = document.forms["planit_form"];
    if (checkForm(frm)==false)
    {
        return;
    }
    var crosstab_mode = '';
    var cmode_input = document.getElementById('crosstab_mode');
    if (cmode_input)
    {
        crosstab_mode = '&crosstab_mode=' + cmode_input.options[cmode_input.selectedIndex].value;
    }
    frm.action = frm.submit_url.value + crosstab_mode + '&planit.' + value;
    frm.format.value = value;
    frm.target="";
    frm.command.value = "submit";

    frm.submit();

    return true;
}

function change(command, type)
{
    var frm = document.forms["planit_form"];
    frm.command.value = command;

    var old_action = frm.action;
    frm.action = frm.base_url.value + "/" + type; 
    frm.submit();
    frm.action = old_action
}

function viewList(level)
{
    var frm = document.forms["planit_form"];
    frm.command.value = "view_list";

    var old_level = frm.drill_level.value;

    if (typeof(level) != "undefined")
    {
        frm.drill_level.value = level;
    }

    frm.submit();

    frm.drill_level.value = old_level;

    return true;
}


function animateDots()
{
    if (document.getElementById("creating").style.display != "none")
    {
        if (document.getElementById("dots").innerHTML.length >= 4)
            document.getElementById("dots").innerHTML = "";
        else
            document.getElementById("dots").innerHTML += ".";
        setTimeout("animateDots()", 500);
    }
}


function checkForm()
{
    var retval = true;
    var frm    = document.forms["planit_form"];
    var x_axis = frm["grouping_0"];
    var planit_type = frm.planit_type.value;

    if (planit_type == "C")
    {
        if (x_axis.value == "-")
        {
            retval = false;
        } 	
    }

    return retval;
}

function update()    
{
    // planit form
    var frm    = document.planit_form;    
    
    if (checkForm())
    {
        // submit the form
        frm.action = frm.submit_url.value + '&planit.html';    
        frm.format.value = "html";
        frm.command.value = "submit";

        // submit the form
        frm.submit();
        return true;
    }        
}

//function checkForm()  { return true; }
function submitRtf()  { submitForm("rtf"); }
function submitXls()  { submitForm("xls"); }
function submitCsv()  { submitForm("csv"); }
function submitHtml() { submitForm("html"); }


function handleEnter(field, event)
{
    var keyCode = (event.keyCode
                   ? event.keyCode
                   : (event.which
                      ? event.which
                      : event.charCode));

    if (keyCode == 13)
    {
        return saveTemplate();
    }
    else
    {
        return true;
    }
}


function getPercentOptions()
{
    var form = document.forms["planit_form"];
    var percent_type = form.percentage_type;
    var percent_level = form.percentage_level;
    var percent_options = form.percent_options;

    percent_options.selectedIndex=0;
    if (percent_type.value=="penetration")
    {
        if (percent_level.value=="0")
        {
            // percent per table
            percent_options.selectedIndex=1;
        }
        else if (percent_level.value=="1")
        {
            // percent per column
            percent_options.selectedIndex=2;
        }
    }
}

function setCheckBox(formname, checkbox)
{
    var form = document.forms[formname];
    if (form)
    {
        var checkbox = form[checkbox];
        if (checkbox)
        {
            checkbox.checked = !checkbox.checked;
        }
    }
}

function setImageFieldValue(name, value)
{
    //first reset all the images to have no border
    var field_container = document.getElementById(name + "_field");
    var field_elements = field_container.getElementsByTagName("img");
    for (i=0; i<field_elements.length; i++)
    {
        field_elements[i].style.border="4px solid white";
    }
    var field_name = "document.forms[\"planit_form\"]." + name;
    var field = eval(field_name);
    field.value = value;
    
    var img = document.getElementById(name+"_"+value);
    if (img)
    {
        img.style.border="4px solid #0000a0";
    }
}

