/**
 * The file contains javascript methods for performing operations specific
 * to Biovista Nutrition.
 *
 * @author Anuj Sharma
 */

/**
 * holds the name of the entity selected by the user. the value of this
 * variable must be flushed everytime the user selects a different question
 * type or the clicks on 'Clear Question' button (link).
 */
var selectedEntities = "";
/**
 * holds the type of question asked by the user.
 */
var questionType = -1; 
/**
 * holds reference to the supplement clicked on when on the
 * conditions questiosn side.
 */
var selectedEntity = null;
/**
 * holds the reports parse direction.
 */
var reportMarked = 'Report is now marked for printing';
var parseType = -1;
var retreivingReports = false;
var loggedOut = false, gettingSuggestion = false, sp, repDispLabel, _productIndex, _productName, _supplementName, _conditionName, _serverType;
var isRestricted = false;
var restrictedListSize = 10;
var ei;
var restrictedAccessPopUp;

var y = 240;
var t;
/**
 * constans
 */
var __CONDITION = 0, __PRODUCT = 1, __SUPPLEMENT = 2;
var fields = new Array('titleText','journalText','yearText','summaryText','pubmedText','additionalMessages','marked_for_printing');
var clearFields = new Array('titleText','jointData','summaryText','additionalMessages','marked_for_printing');

var wellness_cat_text1 = "Show Wellness Categories";
var wellness_cat_text2 = "Hide Wellness Categories";

/*******************************************************************************
 ***************************** METHODS START HERE ******************************
 ******************************************************************************/
function clearserverping(){
    loggedOut = true;   
    clearInterval(sp);
}
/**
 * setting a tab as the selected tab entails two parts:
 * - set the appropriate tab selector image highlighted
 * - show the contents of that tab.
 */
function setSelectedTab(index){
    showTab('dhtmlgoodies_tabView1',index);
}
/**
 * set the question type.
 */
function setQuestionType(v){
    questionType = ( _serverType == 'BN_SHAKLEE' )? v : ( v == __CONDITION ) ? v : __SUPPLEMENT;
}    
/**
 * get the question type.
 */
function getQuestionType(){
    return questionType;
}
/**
 * sets the value of the selectedEntity global variable to point to
 * the selectedObject passed to it as a parameter. if the selectedEntity
 * was not null the font style of the object is changed to normal and the
 * font style of the new object is set to bold.
 */
function setSelected( selectedObject ){
    selectedEntity = selectedObject;
}
function getSelected(){
    return selectedEntity;
}
/**
 *set the selected tab index image white and the rest normal
 */
function setTabHighlight(index){       
}
var startQCallBack;
function startQuestion( callBackMethod ){
    /**
     * clear all higher tabs.
     */
    removeTab("Your Question");
    removeTab("Product Supplements");
    removeTab("Product Conditions");
    removeTab("Shaklee Products");
    removeTab("Conditions");
    removeTab("Supplements");
    removeTab("Reports")
    startQCallBack = callBackMethod;
    
    /**
     * create the question tab.
     */
    addTab('Your Question','pages/questionFrame.jsp',customiseQuestion,false);
    
    /**
     * make selected entity reference null.
     */
    selectedEntity = null;
    

}

function clearQuestionText(){
    selectedEntities = '';
    document.getElementById('suggestionsList').innerHTML = '';
    document.getElementById('activeChoices').innerHTML = '';
    document.getElementById('search_entity_tf').value = '';
    document.getElementById('pick_from_list_text').style.visibility = 'hidden';
    document.getElementById('suggestionsListImageBox').style.visibility = 'hidden';
    document.getElementById('questionAddButton').style.visibility = 'hidden';
    document.getElementById('searchEntity').style.visibility = 'hidden';
    document.getElementById('questionGraphic1').style.visibility = 'hidden';
    document.getElementById('questionGraphic2').style.visibility = 'hidden';
    document.getElementById('questionGraphic3').style.visibility = 'hidden';
    document.getElementById('clearQuestionLinkImage').style.visibility = 'hidden'
    document.getElementById('clearQuestionLink').style.visibility = 'hidden'
    /**
     * place focus on the search entity field
     */
     document.getElementById('search_entity_tf').focus();
     document.getElementById('questionText').innerHTML = 'Enter a condition or drug name';
}

function customizeHomeTab(){
    document.getElementById( 'path2' ).innerHTML = ( _serverType == 'BN_SHAKLEE') ? "Start with a product" : "Start with a nutritional supplement";
    fadeInQuestions();
}

/**
 * Things to do when the questions frame is called based on question type:
 *  1. change question text
 *  2. change the visibility of the ADD button by removing it
 *  3. change the visibility of the clear question button
 *  4. change the visibility of the question text
 */
function customiseQuestion(){
    /**
     * make question text empty string.
     */
    clearQuestionText();
    setSelectedTab(1);
    var q = getQuestionType();
    if( __CONDITION == q ){//CONDITION
        document.getElementById('questionText').innerHTML = 'Enter a condition or drug name';
        document.getElementById('collectionQuestionText').innerHTML = ( _serverType == 'BN_SHAKLEE') ? "Find Shaklee products related to:" : "Find Nutritional Supplements related to:";
    }else if( __PRODUCT == q || __SUPPLEMENT == q ){//SUPPLEMENT or PRODUCT
        document.getElementById('questionText').innerHTML = ( _serverType == 'BN_SHAKLEE') ? "Enter a product and click search" : "Enter a nutritional supplement and click search";
    }
    document.getElementById('clearQuestionLink').style.visibility = "hidden";
    document.getElementById('clearQuestionLinkImage').style.visibility = "hidden";
    document.getElementById('questionGraphic1').style.visibility = "hidden";
    document.getElementById('questionGraphic3').style.visibility = "hidden";
    document.getElementById('questionGraphic2').style.visibility = "hidden";
    if( startQCallBack != null && startQCallBack != '' )
        startQCallBack();
}
/**
 * the method is called on keyUp in the text field when the user is typing.
 * it causes an asynchronus call to be made to the server in order to
 * retrieve suggested terms list from the server.
 */
function getSuggestion( pattern ){
    if( !gettingSuggestion ){
        gettingSuggestion = true;
        var tabContentUrl = "GetSuggestions.do?pattern=" + pattern +
                            "&termType=" + getQuestionType();
        makeAjaxCall( tabContentUrl, gotSuggestedTerms );
    }
}

function gotSuggestedTerms( theXMLObject ){
    var response = theXMLObject.documentElement;
    var x = response.getElementsByTagName("option");
    var val;
    var concat = "<span class='suggestions'>";
    
    document.getElementById('suggestionsList').innerHTML = '';
    
    for(var i = 0;i < x.length; i++){
        val = x[i].getElementsByTagName("val")[0].firstChild.data;
        concat += "<a href=\"javascript:entityClicked('" + val.replace(/'/g, "\\\'") +  "');\">" +  val +"</a><br>";
    }
    concat += '</span>';
    
    document.getElementById('suggestionsList').innerHTML = concat;
    if( x.length > 0 ){
        document.getElementById('pick_from_list_text').style.visibility = 'visible';
        document.getElementById('suggestionsListImageBox').style.visibility = 'visible';
        document.getElementById('questionAddButton').style.visibility = 'visible';
    }else{
        document.getElementById('pick_from_list_text').style.visibility = 'hidden';
        document.getElementById('suggestionsListImageBox').style.visibility = 'hidden';
        document.getElementById('questionAddButton').style.visibility = 'hidden';
    }
    gettingSuggestion = false;
}

/**
 * when user clicks on a term from the suggestions list this method is called.
 * the term clicked is set in the activeChoices element. if the element already
 * has a term in it the terms are seperated by an 'and'.
 */
function entityClicked( term ){
    hideTooltip();
    if( term == "" || term == null || term.length == 0 )return;

    if( getQuestionType() == __CONDITION ){
        var activeChoiceText = document.getElementById('activeChoices').innerHTML;
        if( trim(activeChoiceText) == '' ){
            document.getElementById('questionText').innerHTML = 'Enter another condition or drug name or press <b>START THE SEARCH</b>';
            document.getElementById('searchEntity').style.visibility = "visible";
            document.getElementById('clearQuestionLink').style.visibility = "visible";
            document.getElementById('clearQuestionLinkImage').style.visibility = "visible";
            document.getElementById('questionGraphic1').style.visibility = "visible";
            document.getElementById('questionGraphic3').style.visibility = "visible";
            document.getElementById('questionGraphic2').style.visibility = "visible";
            document.getElementById('activeChoices').innerHTML = term;
        }else{
            document.getElementById('activeChoices').innerHTML = activeChoiceText + ' and ' + term;
        }
        document.getElementById('suggestionsListImageBox').style.visibility = 'hidden';
        document.getElementById('questionAddButton').style.visibility = 'hidden';
        selectedEntities += term + '<marker>';
        document.getElementById('search_entity_tf').value = '';
    }else{
        if( _serverType == 'BN_SHAKLEE' ){
            _productName = term;
        }else{
            _supplementName = term;
        }
        selectedEntities = term;       
        document.getElementById('search_entity_tf').value = term;
        remove_tabs('dhtmlgoodies_tabView1', 2, -1);
        processQuestion();
    }  
    document.getElementById('suggestionsList').innerHTML = '';
    document.getElementById('pick_from_list_text').style.visibility = 'hidden';
    document.getElementById('search_entity_tf').focus();
}

function processQuestion(){
    removeTab('Shakle Products');
    removeTab('Supplements');
    removeTab('Conditions');
        
    if( selectedEntities == "" || selectedEntities == null || selectedEntities.length == 0 )return;
    if( getQuestionType() == __CONDITION ){//CONDITION
        addTab(( _serverType == 'BN_SHAKLEE') ? 'Shaklee Products' : 'Supplements','pages/resultsFrame.jsp',getResultsData,false);
    }else{//SUPPLEMENT or PRODUCT
        addTab('Conditions',( _serverType == 'BN_SHAKLEE') ? 'pages/resultsFrame.jsp' : 'pages/listSupplementsFrame.jsp',getResultsData,false);
    }
}

function toggleProcessIndicator( show ){
    if( show ){
        document.getElementById('processIndicator').innerHTML = '<div><img src=\"img/indicator_arrows.gif\" width=\"16\" height=\"16\"/></div>';
    }else{
        document.getElementById('processIndicator').innerHTML = '';
    }
}

function getResultsData(){
    toggleProcessIndicator(true);
    removeTab('Your Reports');    
    setSelectedTab(2);
    var tabContentUrl = "EntitySearch?searchType="+ getQuestionType() + "&entities="+selectedEntities +"&serverType="+_serverType;
    makeAjaxCall( tabContentUrl, gotCombinatorial );
}

function gotCombinatorial( theXMLObject ){
    toggleProcessIndicator(false);    
    var response = theXMLObject.documentElement;
    var x = response.getElementsByTagName("option");
    var val;
    for(var i = 0;i < x.length; i++){
        val = x[i].getElementsByTagName("val")[0].firstChild.data;
        if( val != "success" ){
            alert( "Process Failed" );
        }else{
            if( getQuestionType() == __CONDITION ){//CONDITION
                getCombinatorialNamesList();
            }else {//NUTRIENT or PRODUCT
                getConditionsList();
            }
        }
    }
}

function getCombinatorialNamesList(){
    toggleProcessIndicator(true);
    var tabContentUrl = "ListCombinatorials";
    makeAjaxCall( tabContentUrl, gotCombinatorialNamesList );
}

function gotCombinatorialNamesList( theXMLObject ){
    toggleProcessIndicator(false);
    var response = theXMLObject.documentElement;
    var x = response.getElementsByTagName("option");
    var val, html = '<select id=\"combinatorialOptions\" onchange=\"combinatorialChange(this);\" >';
    for(var i = 0;i < x.length; i++){
        val = x[i].getElementsByTagName("val")[0].firstChild.data;
        html += '<option value='+i+'>'+val+'</option>';
    }
    html += '</select>';
    document.getElementById('combinatorial').innerHTML = html;
    toggleProcessIndicator(true);
    getSortedSupplementsList( 0, 0 );
}

function combinatorialChange( selectBox ){
    var selectedIndex = selectBox.selectedIndex;
    var selectedCombinatorial = selectBox.options[ selectedIndex ].value;
    toggleProcessIndicator(true);
    if( _serverType == 'BN_SHAKLEE' ){
        var tabContentUrl = "ParseCombinatorial?index="+selectedCombinatorial;
        makeAjaxCall( tabContentUrl, showCombinatorial );
    }else{
        getSortedSupplementsList( 0,  selectedCombinatorial );
    }
}

function parseCombinatorial(forward){
    toggleProcessIndicator(true);
    document.getElementById('entityList').innerHTML = '';
    var tabContentUrl = "ParseCombinatorial?forward="+forward;
    makeAjaxCall( tabContentUrl, showCombinatorial );
}

function showCombinatorial( theXMLObject ){
    toggleProcessIndicator(false);
    var response = theXMLObject.documentElement;
    var x = response.getElementsByTagName("option");
    var val,val2,val3;
    val = x[0].getElementsByTagName("count")[0].firstChild.data;
    val = x[1].getElementsByTagName("count")[0].firstChild.data;
    
    //unload the products list
    var ihtml = "<span class='products'>";
    var firstProduct = firstProductName = '';
    if( x.length > 2 ){
        firstProduct = x[2].getElementsByTagName("id")[0].firstChild.data;
        firstProductName = x[2].getElementsByTagName("name")[0].firstChild.data;
    }else{
        document.getElementById('resultsListTitle').innerHTML = "No Shaklee products found";
        return;
    }
    ihtml += "<table>";
    for(var i = 2;i < x.length; i++){
        val = x[i].getElementsByTagName("name")[0].firstChild.data;
        val3 = x[i].getElementsByTagName("id")[0].firstChild.data;
        val2 = x[i].getElementsByTagName("url")[0].firstChild.data;
        //to avoid long names causing the horizontal scroll to appear
        ihtml += "<tr><td >"+foldString(val,40)+"</td>"+
                 "<td ><a href=\"javascript:getNutrientsForProduct('"+val3+"','"+val+"');\">Show Supplements</a></td>"+
                 "<td width=\"5\">&nbsp;</td></tr>";
    }
    ihtml +="</table>";
    if( x.length - 2 > 1 )
        document.getElementById('resultsListTitle').innerHTML = "Found " + ( x.length - 2 )+ " Shaklee products";
    else
        document.getElementById('resultsListTitle').innerHTML = "Found " + ( x.length - 2 )+ " Shaklee product";

    document.getElementById('resultsList').innerHTML = ihtml + "</span>";
}

function showHideSortOption( show ){
    document.getElementById('psort').style.visibility = show;
    document.getElementById('nsort').style.visibility = show;
    document.getElementById('ysort').style.visibility = show;
    document.getElementById('fsort').style.visibility = show;
}

function startSupplements(callbackFunction){
    /**
     * clear all higher tabs.
     */
    removeTab('Product Supplements');
    removeTab('Condition Supplements');
    /**
     * create the supplements tab.
     */
     if( getQuestionType() == 0 ) // condition
        addTab('Product Supplements','pages/listSuppplemntsFrame.jsp',callbackFunction,false);
     else // product
        addTab('Condition Supplements','pages/listSupplementsFrame.jsp',callbackFunction,false);
    /**
     * make selected entity reference null.
     */
    selectedEntity = null;
}

function getNutrientsForProduct(productId,productName){
    _productIndex = productId;
    _productName = productName;
    startSupplements(queryNutrients);
}

function getSupplementsNamesList(){
    getSortedSupplementsList( 0 );
}


function queryNutrients(){
    setSelectedTab( 3 );
    toggleProcessIndicator( true );
    var tabContentUrl = "NutrientsForProduct?product=" + _productIndex;
    makeAjaxCall( tabContentUrl, showNutrientsList );
}
function showAmazonStuff(){
    if(_serverType != 'BN_SHAKLEE' ) {
        var ratShow_div = document.getElementById('ratingShowLinkBox');
        ratShow_div.innerHTML = "";
        var products_div = "<div class=\"amazon_product_image_div\">"+
        "<span class=\"amaprodtitle\">Products for "+_supplementName+"</span>"+
        "<iframe style=\"width:360px;height:350px;border:0px;\"id=\"amaprodframe\" "+
        "scrolling=\"no\" src=\"\"></iframe>"+
        "</div>";
        document.getElementById('ratingsDisplayColumn').innerHTML = products_div;      
        loadAmazonResults(_supplementName,1,'salesrank');
    }
}
function showNutrientsList( theXMLObject ){
    toggleProcessIndicator( false );
    var response = theXMLObject.documentElement;
    var startingEntity;
    var listSize;
    if( getQuestionType() == 0 ){//condition
        startingEntity = _productName;
    }else{//supplement or product
        startingEntity = ( _serverType == 'BN_SHAKLEE' ) ? _conditionName : _supplementName;
    }
    var x = response.getElementsByTagName("option");
    var val = id = '', ihtml = '<span class=\"supplements\"><table width=\"458\" border=\"0\" cellspacing=\"2\" cellpadding=\"0\">';
    listSize = x.length - 1;
    //(_serverType != 'BN_SHAKLEE' && (!isRestricted || x.length < restrictedListSize) ) ? restrictedListSize : x.length - 1;
    for(var i = 0;i <= listSize; i++){
        val = x[i].getElementsByTagName("name")[0].firstChild.data;
        ihtml +="<tr><td width=\"60%\" align=\"left\">"+foldString(val,40)+"</td>"+
                 "<td width=\"2\">&nbsp;</td>";
        if( getQuestionType() != 0 ){
            if( _serverType == 'BN_SHAKLEE' )
                ihtml +="<td align=\"left\">"+
            "<a href=\"#\" onclick=\"javascript:showTooltip(event,'List');startReportsTabProduct(0,'" + val + "');\"" +
                                            "class=\"olive_link_small_bold\">Show Reports</a></td>";
            else
                  ihtml +="<td align=\"right\"><a href=\"#\" onclick=\"javascript:preShowRepTabCond(0,'" + val + "');\"" +
                                            "class=\"olive_link_small_bold\">Show Reports</a></td>";              
        }

        ihtml +="<td width=\"5\">&nbsp;</td></tr>";
    }
    ihtml += '</table></span>';
    document.getElementById('supplementsList').innerHTML += ihtml;
    if( getQuestionType() ==  0) // conditions
        document.getElementById('supplementsTitle').innerHTML = 'Nutritional Supplements found in <b>' + startingEntity + '</b>';
    else
        document.getElementById('supplementsTitle').innerHTML = 
        (_serverType == 'BN_SHAKLEE' ) ? 'Nutritional Supplements found in <b>' + _productName + '</b> related to <b> ' + _conditionName + '</b>'
                                        : 'Conditions realted to <b>' + _supplementName + '</b>';
    if( x.length - 1 == 0 )
        document.getElementById('supplementsListTitle').innerHTML = (_serverType == 'BN_SHAKLEE' ) ? 'No nutritional supplement found' : 'No conditions found';
    else if( x.length - 1 == 1 )
        document.getElementById('supplementsListTitle').innerHTML = (_serverType == 'BN_SHAKLEE' ) ? '1 supplement found' : '1 condition found';
    else
        document.getElementById('supplementsListTitle').innerHTML = (_serverType == 'BN_SHAKLEE' ) ? ( x.length - 1 ) + ' supplements found' : ( x.length - 1 ) + ' conditions found';//(listSize==x.length-1)?( x.length - 1 ) + ' conditions found' : listSize + ' conditions of ' + (x.length-1) + " found <a style=\"padding-left:5px;color:white;font-size:11px;\" href=\"javascript:createRestrictedPopup();\">(more info)</a>";
    if(_serverType != 'BN_SHAKLEE' ) {
        var ratShow_div = document.getElementById('ratingShowLinkBox');
        ratShow_div.innerHTML = "";
        var products_div = "<div class=\"amazon_product_image_div\">"+
        "<span class=\"amaprodtitle\">Products for "+_supplementName+"</span>"+
        "<iframe style=\"width:360px;height:350px;border:0px;\"id=\"amaprodframe\" "+
        "scrolling=\"no\" src=\"\"></iframe>"+
        "</div>";
        document.getElementById('ratingsDisplayColumn').innerHTML = products_div;      
        loadAmazonResults(_supplementName,1,'salesrank');
    }
}
var preRepV;
var preRepName;
function preShowRepTabCond(v,name){
    preRepV = v;
    preRepName = name;
    getPairsRating(name);
}
function getAllNutrients(){
    toggleProcessIndicator( true );
    if( document.getElementById('positiveSortRb').checked == true ){
        getSortedSupplementsList( 0 );  
    }else if( document.getElementById('nameSortRb').checked == true ){
        getSortedSupplementsList( 1 );  
    }else if( document.getElementById('yearSortRb').checked == true ){
        getSortedSupplementsList( 2 );  
    }else if( document.getElementById('frequencySortRb').checked == true ){
        getSortedSupplementsList( 3 );  
    }
}


function gotAllNutrientsList( theXMLObject ){
    var response = theXMLObject.documentElement;
    var x = response.getElementsByTagName("option");
                                
    var val;
    var concat = "<span class='entities'>";
    sho
    document.getElementById('entityList').innerHTML = '';
    
    if( x.length == 1 ){
        alert( 'No nutritional supplements found.' );
    }
    for(var i = 1;i < x.length; i++){
        val = x[i].getElementsByTagName("name")[0].firstChild.data;
        concat += "<a href=\"#\" onclick=\"setSelected(this);\" class=\"olive_link\">" + val + "</a><br>";
    }
    concat += '</span>';
    
    document.getElementById('entityList').innerHTML = concat;
    toggleProcessIndicator( false );
}

function getNutrientProductList(){
    var tabContentUrl = "ProductsForSearch";
    makeAjaxCall( tabContentUrl, showProductsList );
}
function showProductsList( theXMLObject ){
    document.getElementById('combinatorial').innerHTML = "<strong>" + 
    selectedEntities + "</strong>";
    var response = theXMLObject.documentElement;
    var x = response.getElementsByTagName("option");
    var val,val2,val3;
    var ihtml = "<span class='products'>";
    if( x.length <= 1 ){
        alert( 'No products found for the nutritional supplement.' );
    }
    for(var i = 0;i < x.length; i++){
        val = x[i].getElementsByTagName("name")[0].firstChild.data;
        val3 = x[i].getElementsByTagName("id")[0].firstChild.data;
        val2 = x[i].getElementsByTagName("url")[0].firstChild.data;
        ihtml += "<a href=\"#\">" +  val + "startReportsTabCombiantorial</a><br>";
    }
    document.getElementById('productList').innerHTML = ihtml + "</span>";
    if( x.length <= 1 ){
        document.getElementById('productList').innerHTML = 
        "No associated products found.";
    }
    getConditionsList();
}
function getConditionsList(){
    toggleProcessIndicator( true );
    getSortedConditionsList( 1 );
}
function showConditionsList( theXMLObject ){
    toggleProcessIndicator( false );//indicates the direction of the parse.
    var response = theXMLObject.documentElement;
    var x = response.getElementsByTagName("option");
    var val,val2;
    var concat = "<span class='products'>";
    
    document.getElementById('resultsList').innerHTML = '';

    if( x.length == 1 ){
        document.getElementById('resultsListTitle').innerHTML = "No conditions found";
        return;
    }
    concat += "<table width=\"460\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\">";
    for(var i = 0;i < x.length; i++){
        val = x[i].getElementsByTagName("name")[0].firstChild.data;
        //to avoid long names causing the horizontal bar to appear
        concat += "<tr><td>" + foldString(val,40) + "</td>"+
                  "<td><a href=\"javascript:getSupplements('" + val + "');\">Show Supplements</a></td>"+
                  "<td>&nbsp;</td></tr>";
    }
    concat += '</table></span>';
    
    if( x.length - 1 > 1 )
        document.getElementById('resultsListTitle').innerHTML = "Found " + ( x.length - 1 )+ " conditions";
    else
        document.getElementById('resultsListTitle').innerHTML = "Found " + ( x.length - 1 )+ " condition";

    document.getElementById('resultsList').innerHTML = concat;
    document.getElementById('combinatorial').innerHTML = selectedEntities;
    document.getElementById('resultsMessageText').innerHTML = 'Conditions related with the Shaklee product';
    loadAmazonResults(_supplementName,1,'salesrank');
}
/*******************
 * nutrients for condition
 *******************/
function getSupplements( cName ){
    _conditionName = cName;
    toggleProcessIndicator( true );
    startSupplements( nutrientsForCondition );
}
function nutrientsForCondition(){
    var tabContentUrl = "NutrientsForCondition?condition=" + _conditionName;
    makeAjaxCall( tabContentUrl, showNutrientsList );
}
function gotNutrientsForCondition(){
    alert('done calling');
}
/*******************
 * RATINGS METHODS *
 *******************/
function getPairsRating( ename ){
    toggleProcessIndicator( true );
    var qtype = getQuestionType();
    ( _serverType == 'BN_SHAKLEE'  ) ? _supplementName = ename : ( qtype != __CONDITION ) ? _conditionName = ename : _supplementName = ename;
    setSelected( ename );
    var tabContentUrl = "GetPairsRating?type="+ qtype + "&ename="+ename + "&serverType=" + _serverType;
    makeAjaxCall( tabContentUrl, gotPairRatings );
}
function gotPairRatings( theXMLObject ){
    showPairRatings( arrayFromXML( theXMLObject, "option", "val" ), arrayFromXML( theXMLObject, "option", "text") );
}
var ratingsValues;
function showPairRatings(ratings,names){
    toggleProcessIndicator( false );
    ratingsValues = ratings;
    var txt = "";//"<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">";
    
    for(var ratingVal = 0; ratingVal < ratings.length; ratingVal++ ){
        txt += "<td width='5'>  | </td><td>Relevance:  </td><td align=\"center\" style=\"font-weight:bold;color:#D1D0CE\">";
        
        if( ratings[ratingVal] == 1 )
                txt += "<img src=\"img/greenThumbsup.PNG\"\><img src=\"img/offThumbsup.PNG\"\><img src=\"img/offThumbsup.PNG\"\>";
        else if( ratings[ratingVal] == 2 )
                txt += "<img src=\"img/greenThumbsup.PNG\"\><img src=\"img/greenThumbsup.PNG\"\><img src=\"img/offThumbsup.PNG\"\>";
        else if( ratings[ratingVal] == 3 )
                txt += "<img src=\"img/greenThumbsup.PNG\"\><img src=\"img/greenThumbsup.PNG\"\><img src=\"img/greenThumbsup.PNG\"\>";
        else
                txt += "Inconclusive";
    }    
    ratingsText = txt + "</td>";
    startReportsTabCondition(preRepV,preRepName);
}

function showRatingsBox(){
    document.getElementById('amaprodframe').style.visibility = 'hidden';
    var ratShow_div = document.getElementById('ratingShowLinkBox');
    ratShow_div.innerHTML = "<a style='margin-left:10px;' href='javascript:hideRatingsBox();'>Hide ratings</a>";
    createDIV("ratingsPopup","ratingShowLinkBox","appFrame",5,30);
    document.getElementById('ratingsPopup').innerHTML = ratingsText;
}
function hideRatingsBox(){
    document.getElementById('amaprodframe').style.visibility = 'visible';
    var ratShow_div = document.getElementById('ratingShowLinkBox');
    ratShow_div.innerHTML = "<a style='margin-left:10px;' href='javascript:showRatingsBox();'>Show ratings</a>";
    document.body.removeChild( document.getElementById('ratingsPopup') );
}


function loadAmazonResults(supName,page,stype){
    document.getElementById('amaprodframe').src='amazonProducts.jsp?prodName='+supName+'&pageIndex='+page+'&stype='+stype;
}

function show_amazon_products( theXMLObject ){
    var dataArr = arrayFromXML( theXMLObject, "option", "val" );
    var dataBox = document.getElementById("prodbox");
    for( var i = 0; i < dataArr.length; i++ ){
        dataBox.innerHTML = dataBox.innerHTML + "<br>" + dataArr[i];
    }
    toggleProcessIndicator( false );
}
/*****************
 * RATINGS METHODS
 *****************/
/******************
 * SORTING METHODS
 ******************/
function relevanceSort(){
    if( getQuestionType() == 1 ){//condition list
        getSortedConditionsList( 0 );
    }else{//supplement list
        getSortedSupplementsList( 0 );
    }
}
function nameSort( type ){
    if( getQuestionType() == 1 ){//condition list
        getSortedConditionsList( 1 );
    }else{//supplement list
        getSortedSupplementsList( 1 );
    }
}
function yearSort( type ){
    if( getQuestionType() == 1 ){//condition list
        getSortedConditionsList( 2 );
    }else{//supplement list
        getSortedSupplementsList( 2 );
    }
}
function frequencySort( type ){
    if( getQuestionType() == 1 ){//condition list
        getSortedConditionsList( 3 );
    }else{//supplement list
        getSortedSupplementsList( 3 );
    }
}
function getSortedConditionsList( sorder ){
    var tabContentUrl = "ConditionsForSearch?sortedAs="+sorder+"&serverType="+_serverType;
    makeAjaxCall( tabContentUrl, (_serverType == 'BN_SHAKLEE') ? showConditionsList : showNutrientsList );
}
function getSortedSupplementsList( sorder, index ){
    var tabContentUrl = "NutrientsForCombinatorial?sortedAs="+sorder+"&index="+index;
    makeAjaxCall( tabContentUrl, showNutrientsListForCombinatorial );
}
function showNutrientsListForCombinatorial( theXMLObject ){
    toggleProcessIndicator( false );
    var response = theXMLObject.documentElement;
    var x = response.getElementsByTagName("option");
    var val;
    var ihtml = "<span class='products'><table border=\"0\" cellspacing=\"2\" cellpadding=\"0\">";
    var listSize, firstSupp;
    
    listSize = (!isRestricted || x.length < restrictedListSize ) ? x.length - 1: restrictedListSize;
    firstSupp = x[0].getElementsByTagName("name")[0].firstChild.data;
    for(var i = 0;i <= listSize; i++){
        val = x[i].getElementsByTagName("name")[0].firstChild.data;
        ihtml +="<tr><td width=\"60%\" align=\"left\">"+
            foldString(val,40)+"</td>"+
            "<td align=\"right\"><a href=\"#\" onclick=\"javascript:showReportsSelectorPopup(event,'"+val+"');\"class=\"olive_link_small_bold\">Show Reports</a></td>" +
            "<td width=\"5\" align='center' style='font-weight: bold;'>|</td>"+
            "<td align=\"left\"><a href=\"#\" onclick=\"javascript:_supplementName='"+val+
            "';showAmazonStuff( );\"class=\"product_link_small_bold\"style='color:#FE5C24;'>Find Products</a></td>"+
            "<td width=\"5\">&nbsp;</td></tr>";
    }
    document.getElementById('resultsList').innerHTML = ihtml + "</table></span>";
    
    if( x.length <= 1 ){
        document.getElementById('resultsListTitle').innerHTML =  "No associated supplements found.";
    }else{
        document.getElementById('resultsListTitle').innerHTML =  (listSize==x.length-1) ? ( x.length - 1 )+ " supplements found" : ( listSize ) + " supplements of " + (x.length - 1)+" found <a style=\"padding-left:5px;color:white;font-size:11px;\" href=\"javascript:createRestrictedPopup();\">(more info)</a>";
    }
    document.getElementById('resultsMessageText').innerHTML = 'Nutritional Supplements related to: ';
    _supplementName= firstSupp;
    showAmazonStuff( );
}
/**
 * Show reports pop-up related methods
 */
var reportSelectorEvent = null;
var rsClientX, rsClientY;
var ratingsText;
function showReportsSelectorPopup( event, selectedNutrient ){
    reportSelectorEvent = event;
    rsClientX = event.clientX;
    rsClientY = event.clientY;
    genRating( selectedNutrient );
}
function genRating( ename ){
    toggleProcessIndicator( true );
    var qtype = getQuestionType();
    ( _serverType == 'BN_SHAKLEE'  ) ? _supplementName = ename : ( qtype != __CONDITION ) ? _conditionName = ename : _supplementName = ename;
    setSelected( ename );
    var tabContentUrl = "GetPairsRating?type="+ qtype + "&ename="+ename + "&serverType=" + _serverType;
    makeAjaxCall( tabContentUrl, gotRatings );
}
function gotRatings( theXMLObject ){
    reportSelector( arrayFromXML( theXMLObject, "option", "val" ), arrayFromXML( theXMLObject, "option", "text") );
}
var ratingsValue;
function reportSelector(ratings,names){
    toggleProcessIndicator( false );
    ratingsValue = ratings;
    var txt = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">";
    if( ratings.length == 1 ){
        preReportsTab(0,names[0],ratings[0]);
        return;
    }
    for(var ratingVal = 0; ratingVal < ratings.length; ratingVal++ ){
        txt += "<tr><td align='center' width='20px'>-</td><td height='12px' width=\"100\" style=\"font-weight:bold;\">" + 
               "<a class=\"reportLink\" href=\"javascript:preReportsTab(0,'" + 
               names[ratingVal] + "',"+ratings[ratingVal]+");\"> "+
               foldString(names[ratingVal],30)+"</a></td></tr>";
    }
    
    txt = "<table width=100%s> <tr><td height='20px'>Show reports of <b>" + _supplementName + "</b> with: </td>" + 
            "<td><a class='closeLink' href='javascript:closeSelector();'>X</a></td></tr>" +
            "<tr><td>" + txt + "</table></td></tr></table>";
   
    showSelector(reportSelectorEvent,txt,rsClientX,rsClientY);
}
function preReportsTab(v,name,rating){
    var txt = '';
    txt = "<td width='5'>  | </td><td>Relevance: </td><td align=\"center\" style=\"font-weight:bold;color:#D1D0CE\">";

    if( rating == 1 )
            txt += "<img src=\"img/greenThumbsup.PNG\"\><img src=\"img/offThumbsup.PNG\"\><img src=\"img/offThumbsup.PNG\"\>";
    else if( rating == 2 )
            txt += "<img src=\"img/greenThumbsup.PNG\"\><img src=\"img/greenThumbsup.PNG\"\><img src=\"img/offThumbsup.PNG\"\>";
    else if( rating == 3 )
            txt += "<img src=\"img/greenThumbsup.PNG\"\><img src=\"img/greenThumbsup.PNG\"\><img src=\"img/greenThumbsup.PNG\"\>";
    else
            txt += "Inconclusive";
   
    ratingsText = txt + "</td>";
    
    startReportsTabCondition(v,name);
}
function closeSelector(){
    hideTooltip();
}
/******************
 * SORTING METHODS
 ******************/
/***********************
 * PARSE REPORTS METHODS
 ***********************/
function getParseType(){
    setSelectedTab(4);
    return parseType;
}
function setParseType( p ){
    parseType = p;
}
function parseReports(){
    if( parseType == 1 && isRestricted )//going forward
        {
            if( ei >= 9 )
                {
                    createRestrictedPopup();
                    return;
                }
        }
    if( !retreivingReports ){
        toggleProcessIndicator( true );
        retreivingReports = true;
        document.getElementById('paper_reference_1').innerHTML = '&nbsp;';
        document.getElementById('paper_reference_2').innerHTML = '&nbsp;';
        document.getElementById('paper_reference_3').innerHTML = '&nbsp;';
        document.getElementById('paper_reference_4').innerHTML = '&nbsp;';
        document.getElementById('paper_reference_5').innerHTML = '&nbsp;';
        document.getElementById('paper_reference_6').innerHTML = '&nbsp;';
        document.getElementById('paper_reference_7').innerHTML = '&nbsp;';
        document.getElementById('paper_reference_8').innerHTML = '&nbsp;';
        document.getElementById('paper_reference_9').innerHTML = '&nbsp;';
        flushReportDetails();
        var tabContentUrl = 'ParseReports?parse='+getParseType()+
        '&ename='+selectedEntity+
        '&qtype='+getQuestionType()+'&serverType='+_serverType;
        makeAjaxCall( tabContentUrl, parseReportsResults );
    }
}
function flushReportDetails(){
    for(var i = 0; i < clearFields.length - 1; i++){
        document.getElementById(clearFields[i]).innerHTML = '&nbsp;';
    }
    document.getElementById('additionalMessagesHolder').style.visibility = 'hidden';
    document.getElementById(clearFields[clearFields.length-1]).visibility = 'hidden';
}
function parseReportsResults( theXMLObject ){
    retreivingReports = false;
    toggleProcessIndicator( false );
    var response = theXMLObject.documentElement;
    var x = response.getElementsByTagName("option");
    
    var si = x[0].getElementsByTagName("sindex")[0].firstChild.data;
    ei = x[1].getElementsByTagName("eindex")[0].firstChild.data;
    var tc = x[2].getElementsByTagName("tcount")[0].firstChild.data;
    
    document.getElementById('report_index_label').innerHTML = 
    "Viewing reports " + si + " to " + ei + " of " + tc;
    
    var title = '', ename = '';
    for(var i = 3; i < x.length; i++){
        title = x[i].getElementsByTagName("title")[0].firstChild.data;
        if( title.length > 145 ){
            title = title.substr(0,142) + ' ...';
        }
        if( i >= 3 )
            document.getElementById('paper_reference_'+(i-2)).innerHTML = 
            "<a class='reportLink' href='javascript:reportDetails("+(i-3)+");'>"+(parseInt(si)+(i-3))+". "+title+"</a>";
    }
    if( si == '0' && ei == '0' && tc == '0' ){
        if( getQuestionType() == 0 ){//CONDITIONS
            alert( 'No common reports found for the condition(s) and nutritional supplement.' );
        }else{//SUPPLEMENTS
            alert( 'No common reports found.' );
        }        
    }
}

function reportDetails( pageDetailIndex ){
    toggleProcessIndicator( true );
    var tabContentUrl = 'ParseReports?parse=3'+
    '&index='+pageDetailIndex+'&serverType='+_serverType;
    makeAjaxCall( tabContentUrl, gotReportDetails);
}
function showThePage(){
    document.getElementById('detailsTable').style.zIndex = 1000;
    document.getElementById('detailsTable').style.visibility = 'visible';
}
function hideDetails(){
    document.getElementById('detailsTable').style.zIndex = 1;
    document.getElementById('detailsTable').style.visibility = 'hidden';
    document.getElementById('marked_for_printing').style.visibility = 'hidden';
    document.getElementById('markedMessage').innerHTML = '&nbsp;';
    document.getElementById('additionalMessagesHolder').style.visibility = 'hidden';
}
function gotReportDetails( theXMLObject ){
    toggleProcessIndicator( false );
    var response = theXMLObject.documentElement;
    var x = response.getElementsByTagName("option");
    var tags = new Array("title","journal","pubyear","abstract","pubmed","annotation","marked");
    var dispTags = new Array("title","Journal","Year","abstract","PubMed ID","annotation","marked");
    var lastPos = tags.length-1;
    
    var tag = '';
    var j, count, d;
    var linkT = 'http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?cmd=Retrieve&db=pubmed&dopt=Abstract&list_uids=';
    var jointData = '<table><tr>';
    for(var i = 0; i < x.length; i++){
        tag = x[i].getElementsByTagName("tag")[0].firstChild.data;
        d = x[i].getElementsByTagName("value")[0].firstChild.data;
        for( var j = 0; j < tags.length; j++ ){
            if( tag == tags[lastPos] ){//marked
                document.getElementById(fields[lastPos]).style.visibility = (d=='true')?'visible':'hidden';
                document.getElementById('markedMessage').innerHTML = (d=='true')?reportMarked:'&nbsp;';
            }else if( tag == tags[1] || tag == tags[2] || tag == tags[4] )
                continue;
            else if( tags[j] == tag )
                document.getElementById(fields[j]).innerHTML = d;
        } 
        if( tag == tags[1] || tag == tags[2] || tag == tags[4] ){
            var disp = dispTags[1];
            if( tags[2] == tag )disp=dispTags[2];
            else if( tags[4] == tag){
                disp=dispTags[4];
                d = '<a target=\"blank\" class=\"pubmedLink\" href=\"' + linkT + d + '\">' + d + '</a>'; 
            }
            jointData += '<td>' + disp + ': ' + d + ' |</td>';
        }
    }
    jointData = jointData.substring(0,jointData.length-6);
    jointData += '</tr></table>';
    document.getElementById('jointData').innerHTML = jointData;
    
    if( document.getElementById('additionalMessages').innerHTML != 'N/A' ){
        document.getElementById('additionalMessagesHolder').style.visibility = 'visible';
    }else{
        document.getElementById('additionalMessagesHolder').style.visibility = 'hidden';
    }
    
    document.getElementById('detailsTable').style.zIndex = 1000;
    document.getElementById('detailsTable').style.visibility = 'visible';
}
function toggleMark(){
    if( document.getElementById('titleText').value == '&nbsp;' ){
        alert('Please select a report to mark.');
        return;
    }
    var tabContentUrl = 'MarkPrint?type=mark';
    makeAjaxCall( tabContentUrl, markToggled );
}
function markToggled( theXMLObject ){
    var i, v, n_elems, elems = theXMLObject.documentElement.getElementsByTagName("option");
    var perform = false;
    n_elems = elems.length;
    v = elems[0].getElementsByTagName("val")[0].firstChild.data;
    if( v == 'fail' ){
        perform = false;
    }else{
        perform = true;
    }
              
    var el = document.getElementById('marked_for_printing');
    if( perform ){//If the process of marking succeded on the server do GUI update
        if(el.style.visibility == 'hidden'){
            el.style.visibility = 'visible';
            document.getElementById('markedMessage').innerHTML = reportMarked;
        }else{
            el.style.visibility = 'hidden';
            document.getElementById('markedMessage').innerHTML = '&nbsp;';
        }   
    }
}
/***********************
 * PARSE REPORTS METHODS
 ***********************/
/***********************
 *ONLOAD OPERATIONS
 ***********************/
function onStart(){
    set_panel(document.getElementById('dhtmlgoodies_leftPanel'));
    makeAjaxCall( 'GetVersion', setServerType );
    sp = window.setInterval( serverPing, 120000 );//2 minutes    
    serverPing();
}
function serverPing(){
    var loc = window.location + '';
    if( loc.indexOf ('exit.do') == -1 ){
        makeAjaxCall( 'ReportActive', pingResponseHandler );
    }else{
        clearInterval( sp );
    }
}
function pingResponseHandler(){
}    
function setLoggedOut(){
    loggedOut = true;
    setTimeout(clearSp,1000);
}
function clearSp(){
    clearInterval( sp );
}
var auto_init_ename;
function setServerType( theXMLObject ){
    var response = theXMLObject.documentElement;
    var x = response.getElementsByTagName("option");
    _serverType = x[0].getElementsByTagName("val")[0].firstChild.data;
    //getUserProfile();
    // auto init operation check
    var loc = window.location + '';
    if( loc.indexOf('autoinit') != -1 ){
        makeAjaxCall( 'autoinitdrequest.do', gotAutoInitData );
     }
}
function getUserProfile(){
    makeAjaxCall( 'GetUserProfile', gotUserProfile );
}
function gotUserProfile( theXMLObject ){
    var response = theXMLObject.documentElement;
    var x = response.getElementsByTagName("option");
    var val = x[0].getElementsByTagName("val")[0].firstChild.data;
    isRestricted = ( val == 0 ) ? false : true;
    // auto init operation check
    var loc = window.location + '';
    if( loc.indexOf('autoinit') != -1 ){
        makeAjaxCall( 'autoinitdrequest.do', gotAutoInitData );
    }
}
function gotAutoInitData( theXMLObject ){
    var response = theXMLObject.documentElement;
    var x = response.getElementsByTagName("option");
    var etype = x[0].getElementsByTagName("val")[0].firstChild.data;
    var ename = x[1].getElementsByTagName("val")[0].firstChild.data;
    auto_init_ename = ename;
    autoLoadQuestionTab( (etype == 'cond') ? __CONDITION : __SUPPLEMENT );
}
function autoLoadQuestionTab( type ){    
    setQuestionType(type);
    startQuestion( questionTabLoaded );
}
function questionTabLoaded(){
    if( getQuestionType() != __CONDITION ){
            _supplementName = auto_init_ename;
    }else{
        document.getElementById('searchEntity').style.visibility = "visible";
        document.getElementById('clearQuestionLink').style.visibility = "visible";
        document.getElementById('clearQuestionLinkImage').style.visibility = "visible";
        document.getElementById('questionGraphic1').style.visibility = "visible";
        document.getElementById('questionGraphic3').style.visibility = "visible";
        document.getElementById('questionGraphic2').style.visibility = "visible";
        document.getElementById('activeChoices').innerHTML = auto_init_ename;    
    }
    selectedEntities = auto_init_ename;
    processQuestion();
}
function getAutoInitResults(){
    processQuestion();
}
/***********************
 *ONLOAD OPERATIONS
 ***********************/
/***********************
 *PRINT REOPORTS METHODS
 ***********************/
function doPrint(){
    setLeftPanelContent('pages/reportPrintOptions.html');
}
/***********************
 *PRINT REOPORTS METHODS
 ***********************/
/*********************
 *SHOW REPORTS METHODS
 *********************/
function showReports(){
    setVersionType
    var q = getQuestionType();
    if( 0 == q ){//CONDITION
        makeAjaxCall( 'ReportOptions?type=build&ename='+selectedEntity.innerHTML,buildOptions);
    }else if( 1 == q ){//SUPPLEMENT
        startReportsTab(0);
    }
}
function buildOptions(){
    setLeftPanelContent('pages/showReportsOptions.html');
}
function startReportsTab(parseType){
    setParseType(parseType);
    removeTab('Reports');
    if( isie() ){
        addTab('Reports','pages/reportsFrame.jsp',parseReports,false);
    }else{
        addTab('Reports','pages/reportsFrame.jsp',parseReports,false);
    }
}
var conditionName;
function startReportsTabProduct(parseType,selectedEntityName){
    _supplementName = selectedEntityName;
    setSelected(selectedEntityName);
    setParseType(parseType);
    removeTab('Reports');
    addTab('Reports','pages/reportsFrame.jsp',parseReportsCombinatorial,false);
}
function startReportsTabCombiantorial(parseType,selectedEntityName){
    setSelected(selectedEntityName);
    setParseType(parseType);
    removeTab('Reports');
    addTab('Reports','pages/reportsFrame.jsp',parseReportsCombinatorial,false);
}
function startReportsTabCondition(parseType,condition){
    conditionName=condition;
    setParseType(parseType);
    removeTab('Reports');
    addTab('Reports','pages/reportsFrame.jsp',parseReportsCondition,false);
}
function parseReportsCombinatorial(){
    if( !retreivingReports ){
        document.getElementById('report_for_text').innerHTML = '<table><tr height=\'20px\'><td>Reports for <b>' + _conditionName + '</b> and <b>' + _supplementName + '</b></td>' + ratingsText + '</tr></table>';
        toggleProcessIndicator( true );
        retreivingReports = true;
        document.getElementById('paper_reference_1').innerHTML = '&nbsp;';
        document.getElementById('paper_reference_2').innerHTML = '&nbsp;';
        document.getElementById('paper_reference_3').innerHTML = '&nbsp;';
        document.getElementById('paper_reference_4').innerHTML = '&nbsp;';
        document.getElementById('paper_reference_5').innerHTML = '&nbsp;';
        document.getElementById('paper_reference_6').innerHTML = '&nbsp;';
        document.getElementById('paper_reference_7').innerHTML = '&nbsp;';
        document.getElementById('paper_reference_8').innerHTML = '&nbsp;';
        document.getElementById('paper_reference_9').innerHTML = '&nbsp;';        
        var tabContentUrl = '';
        tabContentUrl = 'ParseReports?parse='+getParseType()+ '&ename='+getSelected()+ '&qtype='+getQuestionType()+'&serverType='+_serverType;
        makeAjaxCall( tabContentUrl, parseReportsResults );
    }
}
function parseReportsCondition(){
    if( !retreivingReports ){
        toggleProcessIndicator( true );
        document.getElementById('report_for_text').innerHTML = '<table><tr height=\'20px\'><td>Reports for <b>' + conditionName + '</b> and <b>' + _supplementName + '</b></td> ' + ratingsText + '</tr></table>';
        retreivingReports = true;
        document.getElementById('paper_reference_1').innerHTML = '&nbsp;';
        document.getElementById('paper_reference_2').innerHTML = '&nbsp;';
        document.getElementById('paper_reference_3').innerHTML = '&nbsp;';
        document.getElementById('paper_reference_4').innerHTML = '&nbsp;';
        document.getElementById('paper_reference_5').innerHTML = '&nbsp;';
        document.getElementById('paper_reference_6').innerHTML = '&nbsp;';
        document.getElementById('paper_reference_7').innerHTML = '&nbsp;';
        document.getElementById('paper_reference_8').innerHTML = '&nbsp;';
        document.getElementById('paper_reference_9').innerHTML = '&nbsp;';                var tabContentUrl = '';
        tabContentUrl = 'ParseReports?parse='+getParseType()+ '&ename='+_supplementName+ '&qtype=2'+ '&enameCondition='+conditionName+'&serverType='+_serverType;
        makeAjaxCall( tabContentUrl, parseReportsResults );
    }
}
/*********************
 *SHOW REPORTS METHODS
 *********************/
function reportsDispLabel(dispText){
    repDispLabel = "Reports for " + dispText + " (" + ratingsText + ")" ;
}
function doNothing(){
    ;
}
function change_font_size(type){
    var summary_field = document.getElementById('summaryText');
    var summary_text = summary_field.innerHTML;
    var font_size = document.getElementById('summaryFontSize').innerHTML;
    if( type == 1 ){
        font_size++;
    }else{
        font_size--;
    }
    document.getElementById('summaryFontSize').innerHTML = font_size;
    summary_field.style.fontSize = font_size + 'pt';
    document.getElementById('summaryText').innerHTML = summary_text;
}

function enable_disable_tooltips(){
    var current_text = trim(document.getElementById('tooltip_toggle').innerHTML);
    var change_to_text = "";
    if( current_text == 'Disable Tooltips'){
        change_to_text = 'Enable Tooltips';
        set_show_tool_tips(false);
    }else{
        change_to_text = 'Disable Tooltips';
        set_show_tool_tips(true);
    }
    document.getElementById( 'tooltip_toggle' ).innerHTML = change_to_text;
}
function doExit(){
    var ajaxObject = new sack();
    ajaxObject.requestFile = 'LogOut';    
    ajaxObject.runAJAXSimple();
}

function createPrinterPopup( url ){
    var coordinates = findPos( document.getElementById( 'mainTable' ) );
    var mObj = document.createElement('DIV');
    mObj.id = 'printerPopup';
    mObj.style.width = '800px';
    mObj.style.height = '600px';
    mObj.style.position = 'absolute';
    mObj.style.left = (coordinates[0] + 50 ) + 'px';//centered on the main table
    mObj.style.top = (coordinates[1] ) + 'px';//top of the main table
    mObj.style.border = '1px solid #886e36';
    document.body.appendChild(mObj);
    mObj.innerHTML = "<table><tr><td align='right'>"+
    "<div style='width:45px;border:1px solid #886e36;margin:0px;padding:2px;' >"+
    "<a class='closeLink' href='javascript:removePrinterPopup();'>Close X</a>"+
    "</div></td></tr>"+
    "<tr><td align='center'><iframe style='width:795px;height:571px;border:0px;' id='printerPopupFrame' "+
        "src=" + url +"></iframe></td></tr></table>";
}

function removePrinterPopup(){
    document.body.removeChild( document.getElementById('printerPopup') );
}

// ************************************
// Restricted Access Message Popup Code
// ************************************
function createRestrictedPopup()
{
    //get position of main table
    var coordinates = findPos( document.getElementById( 'mainTable' ) );
    //create parent div
    var mObj = document.createElement('DIV');
    mObj.id = 'restrictedPopup';
    mObj.style.width = '555px';
    mObj.style.height = '220px';
    mObj.style.position = 'absolute';
    mObj.style.left = (coordinates[0] + 420 / 2 ) + 'px';//centered on the main table
    mObj.style.top = (coordinates[1] +140 / 2 ) + 'px';//top of the main table
    mObj.style.border = '0px';
    mObj.style.visibility = 'hidden';
    document.body.appendChild(mObj);
    //create & execute ajax access element
    restrictedAccessPopUp = new sack();
    restrictedAccessPopUp.requestFile = 'pages/RestrictedAccessPopup.html';	
    restrictedAccessPopUp.onCompletion = function(){ showPopupContent('restrictedPopup'); };	
    restrictedAccessPopUp.runAJAX();
}

function showPopupContent(parentId)
{
    var obj = document.getElementById( parentId );
    obj.innerHTML = restrictedAccessPopUp.response;		
    makeDivRounded( 'mainDIV' );
    obj.style.visibility = 'visible';
    y = 240;
}

function removePopup()
{
    document.body.removeChild( document.getElementById('restrictedPopup') );
    document.body.removeChild(document.getElementById('mainDIV_canvas'));
    document.body.removeChild(document.getElementById('mainDIV_content'));
}

function showSubscriptionOptions()
{
    changeHeight1();
}

function showSubFrame()
{
    var obj = document.createElement('IFRAME');
    obj.style.border = '0px';
    obj.style.padding = '0px';
    obj.style.margin = '0px';
    obj.scrolling = 'no';
    obj.style.position = 'relative';
    obj.style.top = '2px';
    obj.style.left = '10px';
    obj.style.height = '270px';
    obj.style.width = '534px';
    obj.src = 'http://www.biovistanutrition.com/content.php?page=How much does it cost';
    document.getElementById('mainDIV_content').appendChild(obj);
    obj.style.visibility = 'visible';  
}

function changeheight(){
    if(y>545){showSubFrame();return;}
    y=y+10;
    e=document.getElementById("mainDIV_content");
    e.style.height = y + 'px';      
    t=setTimeout("changeheight();",0);
}

function changeHeight1()
{
    document.body.removeChild(document.getElementById('mainDIV_canvas'));
    document.body.removeChild(document.getElementById('mainDIV_content')); 
    
    //create & execute ajax access element
    restrictedAccessPopUp = new sack();
    restrictedAccessPopUp.requestFile = 'pages/RestrictedAccessPopup.html';	
    restrictedAccessPopUp.onCompletion = function(){ showPopupContent1('restrictedPopup'); };	
    restrictedAccessPopUp.runAJAX();       
}

function showPopupContent1(parentId)
{
    var obj = document.getElementById( parentId );
    obj.innerHTML = restrictedAccessPopUp.response;		
    document.getElementById("mainDIV").style.height = '370px';
    makeDivRounded( 'mainDIV' );
    obj.style.visibility = 'visible';
    document.getElementById('mainDIV_content').removeChild( document.getElementById('optionsLinkDiv') ); 
    showSubFrame(); 
}

function fadeInQuestions(){
    opacity('q1Table',0,100,3600);
    opacity('q2Table',0,100,3600);
}