/**
 * company /retail interactive functions
 */

function showHierarchy(id,company)
{
    window.open("/sinatra/oxygen/retail_rankings/?screen=company_info&file=hierarchy.html&id="+id+"&company="+company,new Date().getTime(),'screenX=10,screenY=10,top=10,left=10,height=480,width=800,resizable=1,status=0,scrollbars=1');
}

function showRetailNetwork(id,company)
{
    window.open("/sinatra/oxygen/retail_rankings/?screen=company_info&file=network.html&id="+id+"&company="+company,new Date().getTime(),'screenX=10,screenY=10,top=10,left=10,height=480,width=800,resizable=1,status=0,scrollbars=1');
}

function showLogo(id,company)
{
    window.open("/sinatra/oxygen/retail_rankings/?screen=company_info&file=photo.html&id="+id+"&company="+company,new Date().getTime(),'screenX=10,screenY=10,top=10,left=10,height=580,width=680,resizable=1,status=0,scrollbars=1');
}

function showCompany(company)
{
    window.open("/sinatra/oxygen/retail_rankings/?screen=company_info&file=bottom.html&id=",company,new Date().getTime(),'screenX=10,screenY=10,top=10,left=10,height=480,width=800,resizable=1,status=0,scrollbars=1');
}

/**
 * standard site functions
 */

function refresh(anchor)
{
    // does not refresh page if location the same.
    // will need to modify url to use this.
    /***
    var url = window.location.href;
    var pos = url.indexOf('#');

    if (pos != -1)
        url = url.substring(0,pos);

    url += '#' + anchor;
    location.replace(url);
    **/

    // Javascript 1.2 only
    location.reload(false);
}


function selectAllCheckboxes(form_name)
{
    var inputs = document.forms[form_name].elements.length;

    for (var x=0; x<inputs; x++)
    {
        var input = document.forms[form_name].elements[x];
        if (input.type == 'checkbox' && !input.disabled)
        {
            input.checked = true;
        }
    }
}

function deselectAllCheckboxes(form_name)
{
    var inputs = document.forms[form_name].elements.length;

    for (var x=0; x<inputs; x++)
    {
        var input = document.forms[form_name].elements[x];
        if (input.type == 'checkbox' && !input.disabled)
        {
            input.checked = false;
        }
    }
}


function selectAllCheckboxesOnPage()
{
    var num_forms = document.forms.length;
    var num_inputs;

    for (var x=0; x<num_forms; x++)
    {
        num_inputs = document.forms[x].elements.length;

        for (var i=0; i<num_inputs; i++)
        {
            if (document.forms[x].elements[i].type == 'checkbox')
                document.forms[x].elements[i].checked = true;
        }
    }
}


function deselectAllCheckboxesOnPage()
{
    var num_forms = document.forms.length;
    var num_inputs;

    for (var x=0; x<num_forms; x++)
    {
        num_inputs = document.forms[x].elements.length;

        for (var i=0; i<num_inputs; i++)
        {
            if (document.forms[x].elements[i].type == 'checkbox')
                document.forms[x].elements[i].checked = false;
        }
    }
}


function selectCheckboxesWithHits()
{
    var num_forms = document.forms.length;
    var num_inputs;

    for (var x=0; x<num_forms; x++)
    {
        num_inputs = document.forms[x].elements.length;

        for (var i=0; i<num_inputs; i++)
        {
            if ((document.forms[x].elements[i].type  == 'checkbox') &&
                (document.forms[x].elements[i].value == 'hit') )
            {
                document.forms[x].elements[i].checked = true;
            }
        }
    }
}


function getNumSelectedCheckboxes(form)
{
    var num_selected = 0;
    for (var i=0; i<form.elements.length; i++)
    {
        var input = form[i];
        if(input.type == 'checkbox' && !input.disabled && input.checked == true)
        {
            num_selected++;
        }
    }
    return num_selected;
}


// Gets text selected by user, does not work on Opera and Konqueror
function getSelectedText()
{
    var txt = "";

    if (window.getSelection) txt = window.getSelection();
    else if (document.selection) txt = document.selection.createRange().text;

    return txt;
}


function removeExportItems()
{
    //could have used this syntax but netscape 4 cant handle it as usual.
    //document.forms['select_items'].elements['remove_items'].value = 'true';
    document.forms['select_items'].elements[0].value = true;
    document.forms['select_items'].submit();
}


function submitForm(form_name, action, zipped)
{
    var form  = document.forms[form_name];
    if(getNumSelectedCheckboxes(form) > 0)
    {
        var el = document.getElementById('action_performed');
        if (el)
        { 
            el.value = 'true';
        }

        var ext;
    
        if (zipped)
            ext = '.zip';
        else
            ext = '.rtf';
    
        // note this relies on the form having a hidden value named 'zipped'
        document.forms[form_name].elements['zipped'].value = zipped;
        document.forms[form_name].action = '/sinatra/oxygen/' + action + '/report' + ext;
        document.forms[form_name].submit();
    }
    else
    {
        alert('No items were selected.');
    }
}


function deleteSelected(form_name, action)
{
    var form = document.forms[form_name];
    if(getNumSelectedCheckboxes(form) > 0)
    {
        document.forms[form_name].zipped.value = 'false';
        document.forms[form_name].action = action;
        document.forms[form_name].submit();
    }
    else
    {
        alert('No items were selected.');
    }
}


function submitAllForms(action, zipped)
{
    var num_forms = document.forms.length;
    var num_inputs;
    var first = true;
    var url = '/sinatra/ci/' + action + '/report';
    var ext;

    if (zipped)
        url += '.zip?zipped=true&';
    else
        url += '.rtf?';

    for (var x=0; x<num_forms; x++)
    {
        num_inputs = document.forms[x].elements.length;

        for (var i=0; i<num_inputs; i++)
        {
            if ((document.forms[x].elements[i].type  == 'checkbox') &&
                (document.forms[x].elements[i].checked == true) )
            {
                if (first == true)
                    first = false;
                else
                    url += '&';

                url += document.forms[x].elements[i].name;
            }
        }
    }

    open(url, '_self');
}


function loadPageItem()
{
    var index = document.forms['page_list_form'].elements['page_list'].selectedIndex;
    var href  = document.forms['page_list_form'].elements['page_list'].options[index].value;
    open(href, '_self');
}


//these functions are form generating form input fields
function printOption(name, value, thevar)
{
    if (thevar == value)
        document.write('<option value=' + value + ' selected>' + name);
    else
        document.write('<option value=' + value + '>' + name);
}


function setEmailAlert(search_id)
{
    var list_name = 'alert' + search_id;
    var index = document.forms['searches'].elements[list_name].selectedIndex;
    var value = document.forms['searches'].elements[list_name].options[index].value;
    var url = '/sinatra/oxygen/saved_searches/?set_alert&search_id=' + search_id + '&interval=' + value + '#' + search_id;
    location = url;
}


function setPresetAlert(id)
{
    var list_name = 'preset_alert' + id;
    var index = document.forms['searches'].elements[list_name].selectedIndex;
    var value = document.forms['searches'].elements[list_name].options[index].value;
    var url = '/sinatra/oxygen/saved_searches/?set_preset_alert&index=' + id + '&interval=' + value + '#' + id;
    location = url;
}


function deleteSavedSearch(search_id)
{
    var url = '/sinatra/oxygen/saved_searches/?delete_search&search_id=' + search_id;

    if (confirm("Are you sure you want to delete this saved search?"))
    {
       location = url;
    }

    return false;
}


//creates an array of any type - given a size (n)
function List(n)
{
    this.length = n;
    for (var i=1; i<=n; i++)
    {
        this[i] = 0;
        return this;
    }
}

function printList(list, code_list, val)
{
    for (var i=0; i<list.length; i++)
    {
        if (val == code_list[i])
            document.write('<option value=' + code_list[i] + ' selected>' + list[i]);
        else
            document.write('<option value=' + code_list[i] + '>' + list[i]);
    }
}

function printListValue(list, code_list, val)
{
    for (var i=0; i<list.length; i++)
    {
        if (val == code_list[i])
        {
            document.write(list[i]);
            break;
        }
    }
}


function setAccessFilter(req_cur_url)
{
    var cur_url_loc = document.location;
    var cur_url = document.location;

    if (cur_url_loc.pathname=="/" && cur_url_loc.search=="")
    {
       cur_url = cur_url_loc.href + "index.html";
    }
    else
    {
       cur_url = cur_url_loc.href;
    }

    var index = document.forms['access_filter'].elements['set_access_filter'].selectedIndex;
    var value = document.forms['access_filter'].elements['set_access_filter'].options[index].value;
    var set   = cur_url.indexOf('set_access_filter=');

    while (set >= 0)
    {
        cur_url = cur_url.substring(0,set-1) + cur_url.substring(set+25,cur_url.length);
        set = cur_url.indexOf('set_access_filter=');
    }

    // Because some URLs are like "reports.mintel.com/.../view/blah&1234#567"
    // it's not ok to just append the & param on the end as it'll get treated as part
    // of the # anchor bit.  So need to find the last instance of a '/' in the url and insert
    // the &set_access_filter there to guarantee if gets noticed.
    if (cur_url.indexOf('#') >= 0)
    {
        var slash_index = cur_url.lastIndexOf('/');
        if (slash_index >= 0 && slash_index < cur_url.length )
        {
        var rest_of_string = cur_url.substring(slash_index+1, cur_url.length);
        if (rest_of_string.charAt(0) != '&') rest_of_string = '&' + rest_of_string;
            location = cur_url.substring(0,slash_index+1) + '&set_access_filter=' + value + rest_of_string;
        }
        else
        {
            location = cur_url + '&set_access_filter=' + value;
        }
    }
    else
    {
        location = cur_url + '&set_access_filter=' + value;
    }
}


function changeUrl(args)
{
    var index = document.forms['versions'].elements['version_list'].selectedIndex;
    var value = document.forms['versions'].elements['version_list'].options[index].value;
    var url   = './' + 'id=' + value + args.substring(args.indexOf('&'));
    location  = url;
}


/**
 * image functions
 */

function MM_swapImgRestore()
{
    var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages()
{
    var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d)
{
    var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
    if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
    for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); return x;
}

function MM_swapImage()
{
    var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
    if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}


function showTag(id)
{
    var el = document.getElementById(id);
    if (el)
        el.style.display = '';
}

function hideTag(id)
{
    var el = document.getElementById(id);
    if (el)
        el.style.display = 'none';
}

function showhideTag(id)
{
    var el = document.getElementById(id);
    if (el)
        el.style.display == '' ? el.style.display = 'none' : el.style.display = '';
}

/** Show and hide containers by class name
 */
function showhideTagByClass(classN, tag)
{
    divTags = document.getElementsByTagName(tag);

    for (var i = 0; i < divTags.length; i++)
    {
        if (divTags.item(i).className == classN)
        {
            divTags[i].style.display == '' ?
                divTags[i].style.display = 'none' : divTags[i].style.display = '';
        }
    }
}


// show/hide a layer by id alone, no need to specify tag name
function showhideUniq( id )
{
    tag = document.getElementById(id);
    if ( tag )
    {
        tag.style.display == '' ? tag.style.display = 'none' : 
                                  tag.style.display = '';
    }
}

// Show/hide a layer and its associated +/- buttons
// (which are prefixed with add_ and sub_)
// TODO: Inconsistently named, should be showhideAll (lower case 'h')
// Fix this when there's time to make sure we don't break anything!
function showHideAll( id )
{
    showhideUniq(id);
    showhideUniq('add_'+id);
    showhideUniq('sub_'+id);
}

function showhideComments( atom_id )
{
    showhideUniq( "comments_on_" + atom_id );
    showhideUniq( "comments_off_" + atom_id );
    showhideUniq( "personal" + atom_id );
    showhideUniq( "feedback" + atom_id );
    showhideUniq( "discussion" + atom_id );
    return false;
}

/** Check and disable checkboxes by id
 *  @author Matt Hall
 */

function selectenable(checkid, myid, sel)
{
    divTags = document.getElementsByTagName('input');

    for (var i = 0; i < divTags.length; i++)
    {
        // Alter disabled/checked attributes for child checkboxes

        if (divTags.item(i).title == checkid)
        {
            //divTags[i].disabled = sel;
        if (divTags[i].checked != sel)
        {
                divTags.item(i).click();
        }
        }

        // Make sure any other checkboxes of the same id match this one

        if (divTags.item(i).title == myid)
        {
            //divTags[i].checked = sel;
        }
    }
}

function openGraphWizard(item_id, figure, graph)
{
    var url = '/sinatra/oxygen/graphing/item_id=' + item_id + '&figure=' + figure;

    if (graph != "0_0")
        url += '&mode=draw&load=' + graph;

    open( url,
         'graphing'+graph,
         'toolbar=no,menu=no,status=yes,scrollbars=yes,resizable=yes,top=30,left=30,height=650,width=870');
}

function popupNewWindow(url, name)
{
   open(url, name, 'menubar=yes,toolbar=yes,scrollbars=yes');
}

// Global used to jump between hits on a page
hitID=1;

function jumpHit(jump, numHits)
{
    hitID += jump;
    
    if (jump != 0)
    {
        window.location.hash = "hit" + hitID;
    }

    if (hitID > 1)
    {
        showTag('prevbutton');
        hideTag('prevgrey');
    }
    else
    {
        hideTag('prevbutton');
        showTag('prevgrey');
    }

    if (hitID < numHits)
    {
        showTag('nextbutton');
        hideTag('nextgrey');
    }
    else
    {
        hideTag('nextbutton');
        showTag('nextgrey');
    }
}

// Function used by jump to site dropdown on each page
function jumpSite()
{
  var idx=document.forms['sites'].elements['site_list'].selectedIndex;
  var url=document.forms['sites'].elements['site_list'].options[idx].value;

  //If for some reason the user jumps to a website using the dropdown and then resets the dropdown back
  //to its initial setting (Group Websites) prevent them from being directed to [server]/Group Websites
  if (url != 'none' && url != 'Group Websites')
  {
    var winname='dogs';
    window.open(url,winname);
  }
}

function getCookie(NameOfCookie){
    if (document.cookie.length > 0) {              
    begin = document.cookie.indexOf(NameOfCookie+"=");       
    if (begin != -1) {           
      begin += NameOfCookie.length+1;       
      end = document.cookie.indexOf(";", begin);
      if (end == -1) end = document.cookie.length;
        return unescape(document.cookie.substring(begin, end));
    } 
  }
  return null;
}

function setCookie(NameOfCookie, value) {
  document.cookie = NameOfCookie + "=" + escape(value) + '; path=/sinatra/' + getServerName();
}

function getServerName() {
    var matches= /\/sinatra\/([A-Za-z0-9_]*)\//.exec(window.location);
    return (matches && matches[1]) ? matches[1] : "oxygen"; 
}

function flipHighlight()
{
    var Preference=getCookie('Highlight');
    var divTags;
    
    // If highlighting is on or we dont have a cookie,
    // turn it off
    if (Preference=='true' || Preference==null )
    {
        setCookie('Highlight', 'false');
        showTag('hloff');
        hideTag('hlon');
        
        divTags = document.getElementsByTagName('a');
        
        for (var i = 0; i < divTags.length; i++)
        {
            if (divTags[i].className == 'hit_word')
                divTags[i].className = 'hit_word_off';
        }

        divTags = document.getElementsByTagName('span');
        
        for (var i = 0; i < divTags.length; i++)
        {
            if (divTags[i].className == 'hit_word')
                divTags[i].className = 'hit_word_off';
        }
    }
    // If higlighting is off, turn it on
    else
    {
        setCookie('Highlight', 'true');
        showTag('hlon');
        hideTag('hloff');
        
        divTags = document.getElementsByTagName('a');
        
        for (var i = 0; i < divTags.length; i++)
        {
            if (divTags[i].className == 'hit_word_off')
                divTags[i].className = 'hit_word';
        }

        divTags = document.getElementsByTagName('span');
        
        for (var i = 0; i < divTags.length; i++)
        {
            if (divTags[i].className == 'hit_word_off')
                divTags[i].className = 'hit_word';
        }
    }
}

function drawPrevNext(prevdoc, nextdoc, prevtitle, nexttitle, 
                      prevsec, nextsec, prevsectitle, nextsectitle,
                      comesFromSearch, numHits, back_url)
{
   var floater= "";    
    
   if (numHits > 0)
   {
        floater= "<div class='searchcontrol'>" +
                 "<div class='tabspacer'>" +
                 "<div class='tab'>" +
                     "<a class='slider' href='#' " +
                     "  onclick='slideToolbar(); return false;'>HIDE&nbsp;" +
                     "<img src='/images/" + getServerName() + "/styled_slider.gif'></a>" +
                 "</div></div>" +
                 "<div class='tabbody'>" +
                 "<h1>Search Results</h1>";

        if (numHits > 1)
        {
            floater+= "<div style='margin: 0.5em 0.25em'>" +
                      "<table style='border: 2px outset #999999; width: 100%' cellspacing=0><tr>" +
                      "<td valign='middle' id='prevbutton' style='display:none'>" +
                         "<a href='#' title='previous match'" +
                         "  onclick='javascript:jumpHit(-1," + numHits + ");return false;'" + 
                         "><img style='display:inline' src='/images/oxygen/styled_arrow_left.gif'> prev</a></td>\n" +                         
                      "<td id='prevgrey'>" +
                         "<img src='/images/oxygen/styled_arrow_left.gif'> prev</td>\n" +
                     
                      "<td>FIND</td>" +
                        
                      "<td id=' nextbutton' style='text-align:right'>" +
                         "<a href='#' title='next match'" +
                         "  onclick='javascript:jumpHit(1," + numHits + ");return false;'" + 
                         ">next <img src='/images/oxygen/styled_arrow_right.gif'></a></td>\n"+
                      "<td id='nextgrey' style='display:none; text-align:right'>" +
                         "next <img src='/images/oxygen/styled_arrow_right.gif'></td>\n" +
                      "</span></tr></table></div>\n";                         
       }
       
        var Preference=getCookie('Highlight');
        
        var onstyle, offstyle;
        if (Preference=='true' || Preference==null)
        {    
            onstyle= "";
            offstyle= " style='display: none'";
        }
        else
        {
            onstyle= " style='display: none'";
            offstyle= "";
        }
        
        floater +=
               "<div>\n" +
                 "<div class='styled_button' id='hlon'" + onstyle + ">\n" +
                   "<a href='#' onclick='javascript:flipHighlight();return false;' " +
                       "class='hit_word'>highlight on</a>" +
                 "</div>" +
                 "<div class='styled_button' id='hloff'" + offstyle + ">" +
                   "<a href='#' onclick='javascript:flipHighlight();return false;'>" +
                     "highlight off" +
                   "</a>" +
                 "</div>" +
               "<div></div>" +
               "</div><br>";
    }

    return floater;
}

NS6=false;
IE4=(document.all);
if (!IE4) {NS6=(document.getElementById);}
NS4=(document.layers);

lastScrollHeight=0;

//TODO: remove these from the C++ code output
var floatX, floatY
var toolbarHidden=false;
var toolbarAutoHidden=false;

function adjust() {     
    var toolbarEl= document.getElementById('floatlayer');

    //don't bother moving if only by this much
    var moveThresh = 100; 
    
    if (toolbarEl) {
        var scrollHeight= window.pageYOffsset || document.documentElement.scrollTop;
        var stable= Math.abs(scrollHeight - lastScrollHeight) < 5;
        
        if (stable) {
            var viewportHeight= YAHOO.util.Dom.getViewportHeight();
            var docHeight= YAHOO.util.Dom.getDocumentHeight();
            
            var distFromTop= 100;
            var minDistFromTop= 500;
            var newY= scrollHeight + distFromTop;
            
            if (newY < minDistFromTop)
                newY= minDistFromTop;
             
            if (Math.abs(newY-YAHOO.util.Dom.getY(toolbarEl)) > moveThresh) {
                YAHOO.util.Dom.setStyle(toolbarEl, 'opacity', 0);
                YAHOO.util.Dom.setY(toolbarEl, newY);
                var a= new YAHOO.util.Anim(toolbarEl);
                a.duration= 1;
                a.attributes.opacity = { to: 1 };
                //delay checking pos again until anim is over
                a.onComplete.subscribe(function() { adjust() });
                a.animate();
            } else {
                //check periodically if we need to move
                setTimeout(function() { adjust() }, 1000);        
            }
        } else {
            //still scrolling; check later
            setTimeout(function() { adjust() }, 200);        
        }
        
        lastScrollHeight= scrollHeight;
    }
}

function define()
{
    adjust();
}

function slideToolbar(){
    var toolbarEl= document.getElementById('floatlayer');
    var slidOutX= 5;
    var slidInX= -120+18;
    
    if (toolbarEl) {                                  
        var x= YAHOO.util.Dom.getX(toolbarEl);
        YAHOO.util.Dom.setX(toolbarEl, toolbarHidden ? slidOutX : slidInX);
        toolbarHidden= !toolbarHidden;
    }
}

/* Function for switching between the different price types and deciding whether or not to show the TVA code */

function showprice( selecta )
{
    switch(selecta)
    {
        case 0:
            document.getElementById( '1ALL_UK' ).style.display = '';
            document.getElementById( '2BUS_EU' ).style.display = 'none';
            document.getElementById( '3PRI_EU' ).style.display = 'none';
            document.getElementById( '4ALL_US' ).style.display = 'none';
            document.getElementById( '5ALL_XX' ).style.display = 'none';
            document.booking.tvacode.value="Not required";
            document.booking.tvacode.disabled = true;
            break;
        case 1:
            document.getElementById( '1ALL_UK' ).style.display = 'none';
            document.getElementById( '2BUS_EU' ).style.display = '';
            document.getElementById( '3PRI_EU' ).style.display = 'none';
            document.getElementById( '4ALL_US' ).style.display = 'none';
            document.getElementById( '5ALL_XX' ).style.display = 'none';
            document.booking.tvacode.value="";
            document.booking.tvacode.disabled = false;
            break;
        case 2:
            document.getElementById( '1ALL_UK' ).style.display = 'none';
            document.getElementById( '2BUS_EU' ).style.display = 'none';
            document.getElementById( '3PRI_EU' ).style.display = '';
            document.getElementById( '4ALL_US' ).style.display = 'none';
            document.getElementById( '5ALL_XX' ).style.display = 'none';
            document.booking.tvacode.value="Not required";
            document.booking.tvacode.disabled = true;
            break;
        case 3:
            document.getElementById( '1ALL_UK' ).style.display = 'none';
            document.getElementById( '2BUS_EU' ).style.display = 'none';
            document.getElementById( '3PRI_EU' ).style.display = 'none';
            document.getElementById( '4ALL_US' ).style.display = '';
            document.getElementById( '5ALL_XX' ).style.display = 'none';
            document.booking.tvacode.value="Not required";
            document.booking.tvacode.disabled = true;
        case 4:
            document.getElementById( '1ALL_UK' ).style.display = 'none';
            document.getElementById( '2BUS_EU' ).style.display = 'none';
            document.getElementById( '3PRI_EU' ).style.display = 'none';
            document.getElementById( '4ALL_US' ).style.display = 'none';
            document.getElementById( '5ALL_XX' ).style.display = '';
            document.booking.tvacode.value="Not required";
            document.booking.tvacode.disabled = true;
            break;
    }
}


var std_window_attributes = 'resizable=yes,copyhistory=no,menubar=no,directories=no,toolbar=no,location=no,scrollbars=yes,statusbar=yes'
var new_ann_window_attributes = std_window_attributes + ',left=100,top=50,width=800,height=650'
var ann_window_attributes = std_window_attributes + ',left=100,top=50,width=400,height=600'
var del_window_attributes = std_window_attributes + ',left=0,top=0,width=1,height=1'
var print_window_attributes = std_window_attributes + ',left=50,top=50,width=800,height=600,menu=yes,menubar=yes,scrollbars=yes,resizable=yes'
var link_window_attributes = std_window_attributes + ',left=50,top=50,width=1000,height=600'

var changed = false;
function closeConfirm( )
{
    if ( !changed || window.confirm( "Really close this window, abandoning changes?" ) )
    {
        window.close();
    }
}

function delConfirm( )
{
    if ( window.confirm( 'Delete this comment?' ) )
    {
        document.comment_form.comment_text.value='';
        document.comment_form.submit();
    }
}


function newComment( item_id, atom_id, parent_id, def_prof, scope, subject_type )
{
    if ( def_prof == 'false' )
    {
        self.name = 'mintel_reports.main';
        window.open( '/sinatra/oxygen/annotate/comment/edit?' + 
                        'item_id=' + item_id + 
                        '&atom_id=' + atom_id + 
                        '&parent_id=' + parent_id + 
                        (scope ? ('&scope=' + scope) : '') +
                        (subject_type ? ('&subject_type=' + subject_type) : ''),
                     'annotations',
                     ((parent_id && (scope!='group') && subject_type != 2) || scope=='mintel') ? ann_window_attributes : new_ann_window_attributes );

        return false;
    }
    return true;
}


function editComment( item_id, atom_id, comment_id, parent_id, last_comment_id, scope, subject_type )
{
    self.name = 'mintel_reports.main';
    window.open( '/sinatra/oxygen/annotate/comment/edit?' +
            'item_id=' + item_id +
            '&atom_id=' + atom_id +
            '&comment_id=' + comment_id +
            '&parent_id=' + parent_id +
            (last_comment_id ? ('&last_comment_id=' + last_comment_id) : '') +
            '&scope=' + scope +
            (subject_type ? ('&subject_type=' + subject_type) : ''),
                 'annotations', 
                 (scope=='group' ? new_ann_window_attributes : ann_window_attributes) );
    return false;
}


function editUserList( item_id, atom_id, comment_id, scope )
{
    self.name = 'mintel_reports.main';
    window.open( '/sinatra/oxygen/annotate/comment/edit_user?item_id=' + item_id + '&atom_id=' + atom_id + '&comment_id=' + comment_id + '&scope=' + scope,
                 'annotations', ann_window_attributes );
    return false;
}


function deleteComment( item_id, atom_id, comment_id, last_comment_id, scope, subject_type )
{
    self.name = 'mintel_reports.main';
    if ( window.confirm( 'Delete this comment?') )
    {
        window.open( '/sinatra/oxygen/annotate/comment/delete?' +
                'item_id=' + item_id +
                '&atom_id=' + atom_id +
                '&comment_id=' + comment_id +
                (last_comment_id ? ('&last_comment_id=' + last_comment_id) : '') +
                '&scope=' + scope +
                (subject_type ? ('&subject_type=' + subject_type) : ''),
                'del_comment', del_window_attributes );
        return false;
    }
    return false;
}

function printWindow( item_id )
{
    self.name='mintel_reports_main';
    window.open( '/sinatra/oxygen/print/id=' + item_id, 
                 'print_item', print_window_attributes );
    return false;
}

function printTables( item_id )
{
    self.name='mintel_reports_main';
    window.open( '/sinatra/oxygen/displaytables/target=printer&id=' + item_id,
                 'print_item', print_window_attributes );
    return false;
}

function linkEditor( item_id, atom_id )
{
    self.name='mintel_reports_main';
    var selected_text = getSelectedText();
    window.open( '/sinatra/oxygen/link_editing/item_id=' + item_id + '&atom_id=' + atom_id + '&mode=edit&selected_text=' + encodeURIComponent(selected_text), 
                 'edit_links', link_window_attributes );
    return false;
}

function showHideThreading( discussion_id )
{
    var layer = document.getElementById( 'discuss' + discussion_id );
    if ( layer )
    {
        if ( layer.className == "discussion" )
            layer.className="discussion threaded"
        else
            layer.className="discussion"
    }
    return false;
}

var last_child_id=0;
var last_parent_id=0;
function highlightParent( child_id, parent_id )
{
    var child = document.getElementById( 'comment' + child_id );
    var parent = document.getElementById( 'comment' + parent_id );
    if ( parent && child )
    {
        if ( child_id != last_child_id )
        {
            // Unhighlight the last comment pair we highlighted
            var last_p = document.getElementById( 'comment' + last_parent_id );
            if ( last_p )
            {
                last_p.className = "user";
                last_p.title = "comment";
            }

            var last_c = document.getElementById( 'comment' + last_child_id );
            if ( last_c )
            {
                last_c.className = "user";
                last_c.title = "comment";
            }

            // Highlight the desired comment pair
            parent.className = child.className = "user highlighted";
            parent.title = "Highlighted parent comment";
            child.title = "Highlighted child comment";

            // Remember which comments are currently highlighted
            last_child_id = child_id;
            last_parent_id = parent_id;
            return true;
        }
        else
        {
            parent.title = child.title = "comment";
            parent.className = child.className = "user";
            last_child_id = last_parent_id = 0;
            return false;
        }
    }
}

// Enable element 'id' if element 'if_checked' is checked: otherwise, disable it.
function enableIfChecked( id, if_checked )
{
    var layer = document.getElementById( id )
    var check = document.getElementById( if_checked )
    if ( layer && check )
    {
        layer.disabled = !check.checked;

        if ( layer.className.search("(disabled|enabled)") == -1 )
        {
            layer.className += (check.checked ? " enabled" : " disabled");
        }
        else
        {
            if ( check.checked )
                layer.className = layer.className.replace("disabled","enabled");
            else
                layer.className = layer.className.replace("enabled","disabled");
        }
    }
    return false;
}

// Focus on the given element
function setFocus( id )
{
    var layer = document.getElementById(id)
    if ( layer )
        layer.focus();
    return false;
}

function compareOptionText( a, b )
{
    return a.text!=b.text ? ( a.text < b.text ? -1 : 1 ) : 0;
}

function sortOptions(list) 
{
    var items = list.options.length;

    // create array and make copies of options in list
    var tmpArray = new Array(items);
    for ( i=0; i<items; i++ )
        tmpArray[i] = new Option(list.options[i].text,list.options[i].value);

    // sort options using given function
    tmpArray.sort(compareOptionText);

    // make copies of sorted options back to list
    for ( i=0; i<items; i++ )
        list.options[i] = new Option(tmpArray[i].text,tmpArray[i].value);
}

function setCommentAlert( where )
{
    var layer = document.getElementById('instantalert_'+where);
    if ( layer )
    {
        var frm = document.forms['filter_'+where];
        if ( layer.checked )
        {
            frm.action = 'set_alert';
        }
        else
        {
            frm.action = 'unset_alert';
        }
        
        frm.submit();
    }
        
    return false;
}


function maximizeWindow()
{
    window.moveTo(0,0);

    if (document.all)
    {
        window.resizeTo(screen.availWidth,screen.availHeight);
    }
    else if (document.layers||document.getElementById)
    {
        window.outerHeight = screen.availHeight;
    window.outerWidth = screen.availWidth;
    }
}


function toggleOutOfOffice()
{
    if (!document.edit_profile.Enable_Out_Of_Office.checked)
    {
       // Grey out select controls
       document.edit_profile.Out_Of_Office_Start_DAY.disabled=true;
       document.edit_profile.Out_Of_Office_Start_MONTH.disabled=true;
       document.edit_profile.Out_Of_Office_Start_YEAR.disabled=true;
       document.edit_profile.Out_Of_Office_End_DAY.disabled=true;
       document.edit_profile.Out_Of_Office_End_MONTH.disabled=true;
       document.edit_profile.Out_Of_Office_End_YEAR.disabled=true;
    }
    else
    {
       // Unlock select controls
       document.edit_profile.Out_Of_Office_Start_DAY.disabled=false;
       document.edit_profile.Out_Of_Office_Start_MONTH.disabled=false;
       document.edit_profile.Out_Of_Office_Start_YEAR.disabled=false;
       document.edit_profile.Out_Of_Office_End_DAY.disabled=false;
       document.edit_profile.Out_Of_Office_End_MONTH.disabled=false;
       document.edit_profile.Out_Of_Office_End_YEAR.disabled=false;
    }
}

function load_slide_image()
{
if ((obj=document.getElementById("slide_img")) && Player.currentMedia)
{
var new_url=Player.currentMedia.getItemInfo('HTMLView');
if (new_url && obj.src!=new_url) obj.src=new_url;
}
}

/**
 * Checks the xmlString input to ensure it's parsed correctly.
 * If the browser doesn't support the check methods, it will assume the xml was ok.
 */
function checkXML(xmlString)
{
    var xmlValid = true;
    // For use in IE.
    if ( window.ActiveXObject )
    {
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM")
        xmlDoc.async=false;
        xmlDoc.loadXML(xmlString);
        if ( xmlDoc.parseError.errorCode != 0 )
        {
            xmlValid=false;
        }
    }
    else
    {
        try
        {   
            /*
             * Some newer browsers support e4x scripting.  If the browser doesn't an exception
             * will be thrown and the server code will have to do the checking.
             */
            var e4xTest = new XML();
            try
            {
                var changedXML = new XML(xmlString);
            }
            catch(tagerr)
            {
                xmlValid=false;
            }
        }
        catch(e4xerr)
        {
        }
    }
    return xmlValid;
}

/*
 * Report cover functions associated with editing extracts.
 */

/**
 * Shows and highlights an extract for editing.
 */
function showInputArea(area, count)
{
    var tempelement;
    for ( var i = 1; i <= count; i++ )
    {
        tempelement = document.getElementById("inputs_" + i);
        tempelement.style.display = "none";
        tempelement = document.getElementById("show_" + i);
        tempelement.style.color = "blue"
    }
    tempelement = document.getElementById("inputs_" + area);
    tempelement.style.display = "";
    tempelement = document.getElementById("show_" + area);
    tempelement.style.color = "red";
}

/**
 * Checks the xml style input to ensure it's parsed correctly.
 */
function checkXMLInputs(count)
{
    var error_string = '';
    var error_count  = 0;
    var tempelement;
    for ( var i = 1; i <= count; i++ )
    {
        tempelement = document.getElementById("highlight_box_"+i);
        if ( !checkXML("<surround>" + tempelement.value + "</surround>"))
        {
            error_string += ' ' + i;
            error_count++;
        }
    }
    if ( error_count == 0 )
    {
        return true;
    }
    else
    {
        alert("There is a problem with the xml tags in extract"
                + ((error_count > 1) ? "s" : "")
                + error_string
                + ".  Please check and try again.");
        return false;
    }
}

/**
 * Popup the extract editor window.
 */
function popupExtractEditor(item,addNew)
{
    window.open("/sinatra/oxygen/extract_editing/item_id="+item+(addNew ? "&action=add" : ""),new Date().getTime(),'screenX=10,screenY=10,top=10,left=10,height=360,width=480,resizable=1,status=0,scrollbars=1');
}

/*
 * Report section functions associated with editing slideshows.
 */

/**
 * Popup the slideshow editor window.
 */
function popupSlideshowEditor(item_id,figure_number)
{
    window.open("/sinatra/oxygen/slideshow_editing/item_id="+item_id+"&figure="+figure_number,new Date().getTime(),'screenX=10,screenY=10,top=10,left=10,height=725,width=600,resizable=1,status=0,scrollbars=1');
}

/**
 * Checks the xml style input to ensure it's parsed correctly.
 */
function checkSlideshowXMLInputs(count)
{
    var error_string = '';
    var error_count  = 0;
    var delete_string = '';
    var delete_count = 0;
    var tempelement;
    for ( var i = 1; i <= count; i++ )
    {
        tempelement = document.getElementById("delete_"+i);
        if ( !tempelement.checked )
        {
            tempelement = document.getElementById("explanation_box_"+i);
            if ( !checkXML("<surround>" + tempelement.value + "</surround>"))
            {
                error_string += ' ' + i;
                error_count++;
            }
        }
        else
        {
            delete_string += ' ' + i;
            delete_count++;
        }
    }
    if ( delete_count > 0 )
    {
        if ( !confirm("Are you sure you wish to delete slide"
                      + ((delete_count > 1) ? "s" : "")
                      + delete_string) )
        {
            return false;
        }
    }
    if ( error_count == 0 )
    {
        return true;
    }
    else
    {
        alert("There is a problem with the xml tags in slide"
                + ((error_count > 1) ? "s" : "")
                + error_string
                + ".  Please check and try again.");
        return false;
    }
}

/**
 * Swaps two slides' positions.
 */
function swapslides(slide_one, slide_two)
{
    swapcontents(document.getElementById("title_" + slide_one),
                 document.getElementById("title_" + slide_two));
    swapcontents(document.getElementById("image_name_" + slide_one),
                 document.getElementById("image_name_" + slide_two));
    swapcontents(document.getElementById("explanation_box_" + slide_one),
                 document.getElementById("explanation_box_" + slide_two));
    var tempelement_one = document.getElementById("image_" + slide_one);
    var tempelement_two = document.getElementById("image_" + slide_two);
    var tempvalue = tempelement_one.src;
    tempelement_one.src = tempelement_two.src;
    tempelement_two.src = tempvalue;
    tempvalue = tempelement_one.alt;
    tempelement_one.alt = tempelement_two.alt;
    tempelement_two.alt = tempvalue;
    tempelement_one = document.getElementById("delete_" + slide_one);
    tempelement_two = document.getElementById("delete_" + slide_two);
    tempvalue = tempelement_one.checked;
    tempelement_one.checked = tempelement_two.checked;
    tempelement_two.checked = tempvalue;
}

function swapcontents(element_one, element_two)
{
    var tempvalue = element_one.value;
    element_one.value = element_two.value;
    element_two.value = tempvalue;
}

/**
 * Rewrites html to play a video.
 */
function playInline(holding_element, video_url)
{
    document.getElementById(holding_element).innerHTML = '<object id="Player"' +
                                     ' classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6"' +
                                     ' standby="Loading Microsoft Windows Media Player components..."' +
                                     ' type="application/x-oleobject"' +
                                     ' src="' + video_url + '"' +
                                     ' alt="">' +
                              ' <param name="URL" value="' + video_url + '" />' +
                              ' <param name="animationatStart" value="false" />' +
                              ' <param name="transparentatStart" value="true" />' +
                              ' <param name="autoStart" value="true" />' +
                              ' <param name="showControls" value="true" />' +
                              ' <!-- Embed isn\'t standard HTML but it\'s needed for Mozilla -->' +
                              ' <embed name="Player"' +
                                     ' type="application/x-mplayer2"' +
                                     ' pluginspage="http://www.microsoft.com/Windows/MediaPlayer/"' +
                                     ' src="' + video_url + '"' +
                                     ' AutoStart="1"' +
                                     ' AutoSize="0"' +
                                     ' alt="">' +
                               '</embed>' +
                               '</object>';
}

function deleteImage()
{
    var image_name = document.forms.deleteImage.image_name.value;
    var item_id = document.forms.deleteImage.item_id.value;
    YAHOO.util.Connect.asyncRequest(
                            'POST',
                            '/sinatra/oxygen/attach_item_image/',
                            {
                                success: function(o)
                                {
                                    var status_holder = document.getElementById('im_stat');
                                    if (o.responseText == "true")
                                    {
                                        status_holder.innerHTML = "Image Deleted";
                                        var image = document.getElementById('reportCoverImage');
                                        image.style.display = 'none';
                                    }
                                    else
                                    {
                                        status_holder.innerHTML = "Could not delete";
                                    }
                                }
                            },
                            'action=delete&item_id=' + item_id + '&image_name=' + image_name + '&ajax=true'
                                    );
    return false;
}

function attachImage()
{
    YAHOO.util.Connect.setForm(document.forms.attachImage, true);
    YAHOO.util.Connect.asyncRequest( 
                            'POST', 
                            '/sinatra/oxygen/attach_item_image/?ajax=true',
                            {
                                upload: function(o)
                                {
                                    var status_holder = document.getElementById('im_stat');
                                    status_holder.innerHTML = o.responseText;
                                    var date = new Date();
                                    var image = document.getElementById('reportCoverImage');
                                    image.src += "&" + date.getTime();
                                    image.style.display = 'block';
                                }
                            }
                                    );
    return false;
}

//Hide the floating toolbar when the report sections dropdown is shown (on RS pages).
function showhideReportSections(link_div)
{
    var divs= link_div.parentNode.childNodes;
    var sections_list;
    for (var i=0; i<divs.length; i++) {
        if (divs[i].className && divs[i].className.match(/\bbd\b/)) {
            sections_list= divs[i];
            break;
        }
    }
    
    if (!sections_list) {
        return;
    }
    
    var has_floatlayer = document.getElementById('floatlayer') ? true : false;
    if( sections_list.style.display=='none' )
    {   
        if (!toolbarHidden)
        {
            toolbarAutoHidden= true;
            slideToolbar();
        }
        link_div.className = 'hd down_arrow';
        sections_list.style.display='';
    }
    else
    {
        if (toolbarHidden && toolbarAutoHidden)
        {
            toolbarAutoHidden= false;
            slideToolbar();
        }        
        link_div.className = 'hd';
        sections_list.style.display='none';
    }
}

function flipExpandSymbol(id)
{
    var el = document.getElementById(id);
    if(el)
    {
        el.innerHTML = el.innerHTML == '+' ? '-' : '+';
    }
}

function showhideNavbar(symbol_id, navbar_id)
{
    flipExpandSymbol(symbol_id);
    showhideTag(navbar_id);
}


function warnIfItemsSelected(form, url)
{
    var isOpera = (navigator.userAgent.indexOf("Opera") != -1)

    if (!isOpera && getNumSelectedCheckboxes(form) > 0)
    {
        var el = document.getElementById('action_performed');
        if (el && el.value == 'false')
        {
            return confirm("You have selected items which have not been downloaded or exported, are you sure you wish to navigate away from this page?");
        }
    }
    return true;
}

function popupGlossary(type, sort, atom)
{
    var url = "/sinatra/oxygen/glossary/";
    if(type != undefined && type != '')
    {
        url += "type="+type;
    }
    if(sort != undefined && sort != '')
    {
        if(type != undefined)
        {
            url += "&";
        }
        url += "sort="+sort;
    }
    if(atom != undefined && atom != '')
    {
        url += "#"+atom;
    }
    window.open(url, "", 'screenX=10,screenY=10,top=10,left=10,height=725,width=650,resizable=1,status=0,scrollbars=1');
    return false;
}
