// Toggle visibility of layer, keeping track of all toggles in toggleHistory
var toggleHistory = new Array();
function toggleLayer(whichLayer, noHistory){
    var key = window.location.hash;
    if(noHistory != true){
        if(!toggleHistory[key]){
            toggleHistory[key] = new Array();
        }
        toggleHistory[key].push(whichLayer);
    }
    
    var elem, vis;
    elem = document.getElementById( whichLayer );
    vis = elem.style;
    // if the style.display value is blank we try to figure it out here
    if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
        vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
    vis.display = (vis.display==''||vis.display=='block')?'none':'block';
}

//Running the toggle history puts hierarchy any view back into the state that the
//user last viewed it in.  With divs expanded/collapsed appropriately.  This funciton
//is called in the getText function of the http.js library.
function runToggleHistory(){
    var key = window.location.hash;
    if(toggleHistory[key]){
        for(var i = 0; i < toggleHistory[key].length; i++){
            toggleLayer(toggleHistory[key][i], true)
        }
    }
}

function scrollToName(name){
    var elements = document.getElementsByName(name);
    if(elements.length > 0){
        elements[0].scrollIntoView();
    }
}

function deHash(anchor){ return anchor.substr(1,anchor.length); }

//Runs onload of document
function init(contents_node){
        // Make left and center "windows" the height of the window
        resize();
        // Use Ajax to populate contents
        HTTP.getText(contents_node,populateDiv,'left_content');
        // Initiate horizontal resize bar
        new Resizable('left_column', {handle:'handle', minWidth:'305', constraint:'horizontal'});
        // Search stuff
        clearSearch("iSearch", 0);
        // Start centering of search
        center_search();
        // Float columns for CRT
        testFloat();
        //detect Opera
        if(navigator.appName == "Opera"){
        }
        initHistory();
}

function initHistory(){
        /*- YBHM -*/
        var myModuleBookmarkedState = YAHOO.util.History.getBookmarkedState("webreader");
        // If there is no bookmarked state, assign the default state:
        var myModuleInitialState = deHash(window.location.hash);
        var currentState;
        function myModuleStateChangeHandler (state) {
            //We don't actually use the state for keeping track of the history.
            //We use this funciton to update the content div with whatever is
            //specified in window.location.hash.
            if(window.location.hash == ''){
                setTimeout('HTTP.getText("/welcome",populateDiv,"content");', 20);
            } else {
                setTimeout('HTTP.getText("/"+deHash(window.location.hash),populateDiv,"content");', 20);
                //Look for named anchor within the path.  Scroll to the named anchor if any exists.
                path = deHash(window.location.hash);
                fragmentPos = path.indexOf("#");
                if ( fragmentPos >= 0) {
                    setTimeout('scrollToName(path.substr(fragmentPos + 1, path.length));', 300);
                }
            }
            
            //Track Ajax Page view with google analytics
            try {
                pageTracker._trackPageview("/" + deHash(window.location.hash));
            } catch(err) {}
            
        }
        YAHOO.util.History.register("webreader", myModuleInitialState, myModuleStateChangeHandler);
        YAHOO.util.History.initialize("yui-history-field", "yui-history-iframe");

        if(window.location.hash){
                path = deHash(window.location.hash);
                HTTP.getText("/"+path,populateDiv,'content');
                //Scroll to the named anchor if any exists.
                fragmentPos = path.indexOf("#");
                if ( fragmentPos >= 0) {
                    setTimeout('scrollToName(path.substr(fragmentPos + 1, path.length));', 300);
                }
        }
    
}


// Centers search box
function center_search(){
        center("searchResults");
        center("search_wrap");
}
function center(who){
        var w = document.getElementById(who);
        var p_width = document.getElementById("search").offsetWidth;
        var w_width = w.offsetWidth;
        calc = (p_width/2)-(w_width/2);
        w.style.left = calc+"px";
}

// Resize windows
function resize(){
        // Offset for left panel
        l_off = 137 + document.getElementById("tabs").offsetHeight;
        forceHeight('left_content',l_off,null);
        forceHeight('left','137',null);
        forceHeight('handle','97',null);
        forceHeight('content','97',null);
        forceHeight('search_items',0,2);
        size_content(null);
}

// Forces height of divs to height of window
function forceHeight(id,offset,perc){
    if(typeof(window.innerHeight) == 'number'){ //Non-IE
      screenHeight = (window.innerHeight-offset);
    }else{
      screenHeight = (document.documentElement.clientHeight-offset);
    }
    if(perc != null){
        screenHeight = screenHeight/perc;
    }
    document.getElementById(id).style.height = screenHeight+"px";
}

//Force Content window's width
function size_content(offset){
     if(typeof(window.innerWidth) == 'number'){ //Non-IE
      screen_width = parseInt(window.innerWidth);
    }else{
      screen_width= parseInt(document.documentElement.clientWidth);
    }

    lefty = parseInt(document.getElementById('left').offsetWidth);
    handley = parseInt(document.getElementById('handle').offsetWidth.toString());
    content_width =  screen_width - (lefty + handley);
    document.getElementById('content').style.width = (content_width-(40+offset))+"px";
    //alert(screen_width+" - ("+lefty+" + "+handley+") = "+content_width);
    //alert(document.getElementById('content').style.width);
}


//*- Index Search -*//
function searchSel(str, maxResults) {
    //"event" is either the event object from the input box or it can be a string for explicit searches.
    
    str = str.toLowerCase();
    var sbox = document.getElementById('sbox');
    var results = document.getElementById('search_items');
    if(str != ''){
        start = fuzzyBinSearch(str, 0, items.length - 1);
        toggleSearch(1);
        if(start >= 0){
            results.innerHTML = 0;
            var found_first = false;
            for(var i=start; i < items.length; i++) {
                if(items[i].toLowerCase().startsWith(str)){
                    var option = new Option(items[i],ids[i]);
                    //option.addEventListener('click',indexLink,true); 
                    //option.attachEvent("onclick",indexLink);
                    results.options[i-start]=option;
                    maxResults--;
                    if (maxResults == 0){
                        option = new Option("See all results for '" + str + "'",0);
                        results.options[i - start + 1 ] = option;
                        break;
                    }
                }else{
                    break;
                }
            }
        }
    }else{
        results.innerHTML = "";
    }
    document.getElementById("search_items").selectedIndex = 0;
}



function fuzzyBinSearch(str, low, high){
    if(items[low].toLowerCase().startsWith(str)){ return low; }
    if(low >= high){  return -1;  }
    mid = parseInt( (low + high) / 2 );

    var item = items[mid].toLowerCase();
    if(item > str){  return fuzzyBinSearch(str, low, mid);  }
    else if(item < str){  return fuzzyBinSearch(str, mid + 1, high);  }
    else{  return mid;  }
}

//*- Dual List Search -*//
function searchSel_2(inputstr, maxResults) {
       var sbox = document.getElementById('sbox');
       var results = document.getElementById('d_searchResults')
       results.innerHTML = ''
       if(inputstr != ''){
           start = fuzzyBinSearch_2(inputstr, 0, dl_items.length - 1);
           if(start >= 0){
               for(var i=start; i < dl_items.length; i++) {
                   if(dl_items[i][0].toLowerCase().indexOf(inputstr)==0){
                       results.innerHTML += "<li><div class='l'>" + dl_items[i][0] + "</div><div class='r'>" + dl_items[i][1] + "</div></li>";
                       maxResults--;
                       if (maxResults == 0){
                            results.innerHTML += "<li><a href='javascript: searchSel_2(\""+inputstr+"\", 999)'>See all results for '"+inputstr+"'</a></li>";
                            break;
                       }
                   }else{
                       break;
                   }
               }
           }else{
                results.innerHTML = "<div id='d_filler'></div>No Results Founds";
           }
       }else{
           results.innerHTML = "<div id='d_filler'></div>";
       }
}
function fuzzyBinSearch_2(str, low, high){
    if(dl_items[low][0].toLowerCase().indexOf(str) == 0){  return low;  }
    if(low >= high){  return -1;  }
    mid = parseInt( (low + high) / 2 );
    if(dl_items[mid][0].toLowerCase() > str){  return fuzzyBinSearch_2(str, low, mid);  }
    else if(dl_items[mid][0].toLowerCase() < str){  return fuzzyBinSearch_2(str, mid + 1, high);  }
    else{  return mid;  }
}

//Closes Search window
function toggleSearch(bool){
        if(bool == 0){
                document.getElementById('searchResults').style.display = "none";
        }
        if(bool == 1){
                document.getElementById('searchResults').style.display = "block";
                //Position results window relatively
                center_search();
        }
}
function toggleSearch2(){
    var str = document.getElementById('iSearch').value;
    if(str=="Search Index..."){
        var results = document.getElementById('search_items');
        results.innerHTML = entireIndex;
        results.outerHTML = "<SELECT id='search_items' size='12' onchange='updateContent(this);'>"+entireIndex+"</select>";
    }
    toggleSearch(1);
}
// Clears message on index search..
function clearSearch(id, click){
        value = document.getElementById(id).value;
        check = "Search Index...";
        if(value == check){
                if(click == 1){
                        document.getElementById(id).value = "";
                        document.getElementById(id).className = "search_input_dark";
                }
        }else{
                document.getElementById(id).className = "search_input_dark";
              if(value == "" || value == " "){
                document.getElementById(id).value = check;
                document.getElementById(id).className = "search_input";
                toggleSearch(0);
              }
        }
        if(click == 0){
                if(document.getElementById('searchResults').style.display != "block"){
                        toggleSearch(0);
                }
        }else{
                toggleSearch(1);
        }
}
// For definitions view.. recreates anchor tag jump by altering the 'scrollTop' of the content div
function scroller(who){
        w = document.getElementById(who);
        if(w != null){
                document.getElementById('content').scrollTop = w.offsetTop + 140;
        }
}

function change_class(element, newClass){
        element.className = newClass;
}

function clearInput(id){
    document.getElementById(id).value = '';
}

function clearDiv(id){
    document.getElementById(id).innerHTML = '';
}

function dl_change_class(who,what){
        children = document.getElementById('dl_nav').childNodes;
        // Clear all children of CSS classes
        for(i=0;i<children.length;i++){
                if(children[i].nodeType == 1){
                        children[i].className = '';
                }
        }
        document.getElementById(who).className = what;
}


//TRSC INX Stuffs.  This will be sorted out later. -JLuna
function getInteractions(db_version){
    sbox = document.getElementById('trsc_inx_drugs');
    drug_ids = ""
    if (sbox.length > 0){
            for(i=0; i<sbox.length; i++){
            if(i != 0)
                drug_ids += "-"
            drug_ids += sbox.options[i].value;
        }
        url = "trsc/interactions/v"+db_version+"/"+drug_ids;
        HTTP.getText(url,populateDiv,"content");
        window.location.hash = url;
    }
}
//Toggle interaction details
function toggleInteractionDetails(div,id){
    if(document.getElementById(div).innerHTML == ''){
        HTTP.getText('trsc/interaction-info/'+id, populateDiv, div);
    }
    
    toggleLayer(div, true);
}


function moveOption(from_id, to_id){

    from = document.getElementById(from_id);
    to = document.getElementById(to_id);
    option = from.options[from.selectedIndex];
    addItem = true;
    for(i = 0; i < to.options.length; i++){
        if(to.options[i].value == option.value){
            addItem = false;
            break;
        }
    }
    if(addItem){
        to[(to.length)] = new Option(option.text, option.value, false, false);
    }
    //toSelectBox.add(optionCopy, null);
}
function removeOption(sboxid){
    sbox = document.getElementById(sboxid)
    sbox.options[sbox.selectedIndex] = null;
}
function searchSelectBox(e) {
        try{
                ev = event;
                inputstr = ev.srcElement.value;
        }catch(error){
                ev = e;
                inputstr = ev.target.value;
        }
		inputstr = inputstr.toLowerCase();
        sbox = document.getElementById('trsc_drugs');
        if(ev.keyCode == 13){
                moveOption("trsc_drugs", "trsc_inx_drugs");
        }
        else if(ev.keyCode == 38){
                sbox.selectedIndex -=1;
        }
        else if(ev.keyCode == 40){
                sbox.selectedIndex +=1;
        }
        else if(inputstr != ''){
            start = binaryOptionSearch(sbox.options, inputstr, 0, sbox.options.length - 1);
            if(start >= 0){
                sbox.selectedIndex = start + 11;  //set scroll position of select box
                sbox.selectedIndex = start;
            }
        }else{
            sbox.selectedIndex = null;
        }
}
function binaryOptionSearch(options, str, low, high){
    if(options[low].text.toLowerCase().indexOf(str) == 0){ return low; }
    if(low >= high){  return -1;  }
    mid = parseInt( (low + high) / 2 );
    if(options[mid].text.toLowerCase() > str){  return binaryOptionSearch(options, str, low, mid);  }
    else if(options[mid].text.toLowerCase() < str){  return binaryOptionSearch(options, str, mid + 1, high);  }
    else{  return mid;  }
}

// Check to see if enter has been pressed (for select box when input field is not focused)
function check_for_enter(e){
        select = document.getElementById("trsc_drugs");
         try{
                ev = event;
                inputstr = ev.srcElement.value;
        }catch(error){
                ev = e;
                inputstr = ev.target.value;
        }
        if(ev.keyCode == 13){
                moveOption("trsc_drugs", "trsc_inx_drugs");
        }
}

function index_events(e){
        var list = document.getElementById("search_items");
        try{
                ev = event;
                inputstr = ev.srcElement.value;
        }catch(error){
                ev = e;
                inputstr = ev.target.value;
        }
        
        if(ev.keyCode == 13){ //ENTER
                list.focus();
                indexLink();
        }else if(ev.keyCode == 38){ //up
                
                list.selectedIndex -=1;
        }else if(ev.keyCode == 40){ //down
                list.focus();
                list.selectedIndex += 1;
        }
}
function indexLink(){
        var selBox = document.getElementById("search_items");
        var value = selBox.options[selBox.selectedIndex].value;
        if (value == 0){
            var str = document.getElementById('iSearch').value;
            searchSel(str, 999);
            return;
        }
        if(value.substring(0,1) == 'v'){
            url = "v" + db_version + "/" + value.slice(1);
        }else{
            url = "u/" + value;
        }
        window.location.hash=url;
        document.getElementById("searchResults").style.display = "none";
}

function indexEnter(selBox,e){
        try{
                ev = event;
                inputstr = ev.srcElement.value;
        }catch(error){
                ev = e;
                inputstr = ev.target.value;
        }        

        if(ev.keyCode == 13){ //ENTER
                indexLink();
        }
        else if(ev.keyCode == 38){
                if(selBox.selectedIndex == 0){
                        document.getElementById("iSearch").focus();
                }
        }
        
}


//Clears list
function clear_list(){
        document.getElementById("trsc_inx_drugs").options.length = 0;
}
//For INX, goes back to search view
function back_to_search(){
    history.go(-1);
}

function isNumeric(value){
    return isNaN(Number(value))? false : true;
}

// Floating columns for CRT

function doSomething(){


        floats_list = getElementsByClassName(document, "div", "inner_float");
        try{
        if(floats_list.length > 0){
                box_left = document.getElementById('content').scrollLeft;
                if(box_left > 75){
                    for(x=0;x<=floats_list.length;x++){
                        if(eval(floats_list[x].style)){
                                floats_list[x].style.left = (box_left-((floats_list[x].offsetWidth/2)-10))+"px";
                        }
                    }
                }else{
                        for(x=0;x<=floats_list.length;x++){
                    //for(item in floats_list){
                        if(eval(floats_list[x].style)){
                                floats_list[x].style.left = 0+"px";
                        }
                    }
                }
        }
        }catch(e){

        }


}
function getElementsByClassName(oElm, strTagName, strClassName){
    var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    strClassName = strClassName.replace(/\-/g, "\\-");
    var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
    var oElement;
    for(var i=0; i<arrElements.length; i++){
        oElement = arrElements[i];
        if(oRegExp.test(oElement.className)){
            arrReturnElements.push(oElement);
        }
    }
    return (arrReturnElements)
}
function testFloat(){
  setInterval("doSomething()", 1);
}

// SG Calc
function calculate(range_val){
    var form = document.calc_form;
    var result = document.getElementById('calc_results');
    var result_html;
    if( !(range_val) ){
        result.innerHTML = 'Please make sure all values are correct.'
        return false;
    }

    if (validate_not_empty(form)){
        //For SG the calculation is not part of the reader project.  This should be updated for reader projects.
        if (form.Gender[0].checked){ //Man
            var fIBW = 50.0 + 2.3 * (form.Heightininches.value - 60.0);
        }else if (form.Gender[1].checked){ //Woman
            var fIBW = 45.5 + 2.3 * (form.Heightininches.value - 60.0);
        }

        var obese = false;
        var fOIBW = fIBW; // Save IBW for printout, and use fObeseIBW for calculation
        if(form.Weight.value > 1.3 * fIBW){
            fOIBW = fIBW + 0.4 * (form.Weight.value - fIBW); // Adjust for obesity.
            obese = true;
        }
        var fResult = ((140.0 - form.Age.value) * fOIBW) / (72.0 * form.SerumCreatinine.value);

        if(form.Gender[1].checked) //Woman
            fResult = fResult * 0.85;
        result.style.display = 'block';
        result_html = "<h2>Result:</h2><div id='result'>";
        result_html += "<h5>Creatinine Clearance</h5>";
        if(fResult > 90)
            result_html += "<div class='value'>Within normal limits: " + fResult.toFixed(2) + " ml/min</div>";
        else
            result_html += "<div class='value'>" + fResult.toFixed(2) + " ml/min.  Abnormal level.</div>";
        result_html += "<h5>Ideal Body Weight</h5>";
        result_html += "<div class='value'>" + fIBW.toFixed(1) + "kg. Actual Weight: " + form.Weight.value + "kg.</div>";
        result_html += "<h5>Obesity Adjustment</h5>";
        if(obese)
            result_html += "<div class='value'>Yes, adjusted appropriately for CrCl estimation.</div>";
        else
            result_html += "<div class='value'>None required.</div>";

        result_html += "</div>";
        result.innerHTML = result_html;
    }else{
        result.innerHTML = "<div class='warning'>Please make sure all fields are filled in.</div>";
    }

    return false;
}

function validate_not_empty(form) {
    var valid = true;

    var checkBoxes = false;
    var checkboxChecked = false;
    var radioButtons = false;
    var radioChecked = false;

    for (var i=0, j=form.elements.length; i<j; i++) {
        myType = form.elements[i].type;
        if (myType == 'radio') {
            radioButtons = true;
           if (form.elements[i].checked) radioChecked = true;
        }
        if (myType == 'checkbox') {
            checkBoxes = true;
            if (form.elements[i].checked) checkboxChecked = true;
        }
        if (myType == 'hidden' || myType == 'password' || myType == 'text' || myType == 'textarea')
            if ( form.elements[i].value.length == 0) valid = false;
            //if (form.elements[i].value == form.elements[i].defaultValue) valid = false;
        if (myType == 'select-one' || myType == 'select-multiple')
            if (form.elements[i].selectedIndex == 0) valid = false;
    }

    if ((checkBoxes && !checkboxChecked) || (radioButtons && !radioChecked)) valid = false;

    return valid;
}

function validate_range_obj(obj, min, max, unit){
    var val = obj.value;
    var name = obj.name;
    if(val.length > 0 && (val < min || val > max) ){
        alert(name + " must be a value between " + min + ' ' + unit + " and " + max +  ' ' + unit);
        return false;
    }
    return true;
}

function validate_range_event(event, min, max, unit){
    var val = event.target.value;
    var name = event.target.name;
    if(val.length > 0 && (val < min || val > max) ){
        alert(name + " must be a value between " + min + ' ' + unit + " and " + max +  ' ' + unit);
        return false;
    }
    return true;
}

