
/**
 * Show/hide tabs and other things on the basis
 * of an id
 * 
 */
 function showHideTabs(tabSetId, tabId, panelId){
     
     var tabsId = "#" + tabSetId;
     
     // select everything in the tabset with tabOn class and change
     // it to tabOff
     dojo.query(tabsId + " .tabOn").forEach(
         function(el) {el.className = 'tabOff';}
     );
     dojo.query(tabsId + " .tabOnLeftImageDiv").forEach(
         function(el) {el.className = 'tabOffLeftImageDiv';}
     );
     dojo.query(tabsId + " .tabOnRightImageDiv").forEach(
         function(el) {el.className = 'tabOffRightImageDiv';}
     );
     
     // select everything with panelOn class and change that to 
     // panelOff
     dojo.query(tabsId + " .panelOn").forEach(
         function(el) {el.className = 'panelOff';}
     );
     
     // set tabId on
     dojo.byId(tabId).className = 'tabOn';
     dojo.byId(tabId + "-right").className = 'tabOnRightImageDiv';
     dojo.byId(tabId + "-left").className = 'tabOnLeftImageDiv';

     // set panelId on
     dojo.byId(panelId).className = 'panelOn';
     
 }


/**
    populates a record
    takes the fields of the record to be
    identified by the recordName-fieldName.
    Data, including fieldNames, is retrieved
    from the server at the uri
*/
function popRecord(url, recordName){
    
    // get a handle on the feedback div
    // so we can write messages to it
    var md = dojo.byId(recordName + 'InfoDiv');
    
    // tell the user we are working on it
    if(md){
        md.innerHTML = "Loading...";
        md.className = "messageDivWaitOn";        
    }
    
    //  get the data back
    dojo.xhrGet( {
            url: url, 
            handleAs: "json",
            timeout: 30000,
            load: function(response, ioArgs){

                // work through the response 
                // and update the relevant fields
                for(var field in response){
                    var span = document.getElementById(recordName + "-" + field);
                    if (span){
                        span.innerHTML =  response[field];
                    }else{
                        console.debug("No element by id for:" + recordName + "-" + field);
                    }
                }
                
                // best practice to return response.
                return response;
            },
            error: function(response, ioArgs){
                // problems talking to the server so 
                // display error
                if(md){
                    md.innerHTML = ioArgs.xhr.status;
                    md.className = "messageDivAlertOn";
                }
                console.error("HTTP status code: ", ioArgs.xhr.status);
                return response;
            }
    });  
    
}


function popChunk(url, chunkName){
    
    // get a handle on the feedback div
    // so we can write messages to it
    var md = dojo.byId(chunkName);
    if (md == null) return;// do nothing with nothing
    var mdInitialClass = md.className; // need this for later
    
    // md may be wrapped in a hiding div
    // make sure the parent is visible
    md.parentNode.style.display = 'block';
    
    // tell the user we are working on it
    if(md){
        md.innerHTML = "Loading...";
        md.className = "messageDivWaitOn " + mdInitialClass;
             
    }
    
    //  get the data back
    dojo.xhrGet( {
            url: url, 
            handleAs: "text",
            timeout: 30000,
            load: function(response, ioArgs){

                md.innerHTML = response;
                md.className = mdInitialClass;
                
                // if the repsonse was empty we should hide it
                if (response.length < 1){
                    md.parentNode.style.display = 'none';
                }
                
                // best practice to return response.
                return response;
            },
            error: function(response, ioArgs){
                // problems talking to the server so 
                // display error
                if(md){
                    md.innerHTML = ioArgs.xhr.status;
                    md.className = "messageDivAlertOn";
                }
                console.error("HTTP status code: ", ioArgs.xhr.status);
                return response;
            }
    });  
    
}

/*
The effect of including this script is that a global property with the
name "windowState" is assigned an object that has 4 methods that will
tell you what you need to know about the viewport/window:-

var viewPortWidth = windowState.getWidth();
var viewPortHeight = windowState.getHeight();
var horizontalScroll = windowState.getScrollX();
var verticalScroll = windowState.getScrollY();
*/

var windowState = (
    function(){
        var readScroll = {scrollLeft:0,scrollTop:0};
        var readSize = {clientWidth:0,clientHeight:0};
        var readScrollX = 'scrollLeft';
        var readScrollY = 'scrollTop';
        var readWidth = 'clientWidth';
        var readHeight = 'clientHeight';

    function otherWindowTest(obj){
        if(
            (document.compatMode) &&
            (document.compatMode == 'CSS1Compat') &&
            (document.documentElement)){
                return document.documentElement;
            }else if(document.body){
                return document.body;
            }else{
                return obj;
            }
    };

    if(
        (typeof this.innerHeight == 'number')
        &&
        (typeof this.innerWidth == 'number'))
    {
            readSize = this;
            readWidth = 'innerWidth';
            readHeight = 'innerHeight';
    }else{
            readSize = otherWindowTest(readSize);
    }
    
    if(
        (typeof this.pageYOffset == 'number')
        &&
        (typeof this.pageXOffset == 'number'))
    {
        readScroll = this;
        readScrollY = 'pageYOffset';
        readScrollX = 'pageXOffset';
    }else{
        readScroll = otherWindowTest(readScroll);
    }

    return {
        getScrollX:function(){
            return (readScroll[readScrollX]||0);
        },
        getScrollY:function(){
            return (readScroll[readScrollY]||0);
        },
        getWidth:function(){
            return (readSize[readWidth]||0);
        },
        getHeight:function(){
            return (readSize[readHeight]||0);
        }
    };

})();

/* L O O K U P - I N P U T */


 var currentLookupFilters = new Object();

 function updateLookup(input, filterSize, url) {

     var controlName = input.parentNode.parentNode.id;
     var currentValue =  input.value.replace(/^\s+/, '');
     currentValue = currentValue.replace(/\s+$/, '');
     var currentFilter = null;
     var choicesDiv = input.parentNode.getElementsByTagName('div')[0];

     // if we don't have the filter size then clear the
     // lookup area.
     if (currentValue.length < filterSize){
         choicesDiv.innerHTML = "Please enter the first " + filterSize  +" letters of the lookup.";
         // still set the current filter as it will trigger a search next time - on change
         currentLookupFilters.controlName = currentValue;
         return;
     }else{

         currentFilter = currentValue.substr(0, filterSize);

         // check is we have loaded some divisions.
         var currentChoices = choicesDiv.getElementsByTagName('div');

         if (currentFilter == currentLookupFilters.controlName && currentChoices > 0){
             filterWithinLookup(choicesDiv);
             return;
         }else{
             choicesDiv.innerHTML = "Loading list generated on the basis of '" + currentFilter + "' ... ";
             currentLookupFilters.controlName = currentFilter;
             populateLookup(choicesDiv, currentFilter, url);
             return;
         }

     }
 }

 function filterWithinLookup(choicesDiv){

     // get the value in the text input
     var inp = choicesDiv.parentNode.getElementsByTagName('input')[0];
     var currentVal =  inp.value.replace(/^\s+/, '');
     currentVal = currentVal.replace(/\s+$/, '');

     var choices = choicesDiv.getElementsByTagName('div');
     var lastTurnedOn = null;
     var numberTurnedOn = 0;

     for(var i = 0; i < choices.length; i++){

         var regie = RegExp(currentVal, 'i'); 
         var choDiv = choices[i];
         if (!regie.exec(choDiv.innerHTML)){
            choDiv.style.display = 'none';
         }else{
            choDiv.style.display = 'block';
            lastTurnedOn = choDiv;
            numberTurnedOn++;
         }

     }

     // if there are no items selected issue a warning
     if (numberTurnedOn == 0){
         inp.style.color = 'red';
     }else{
         inp.style.color = 'black';
     }

     // if there is only one to display click on it for them.
     if (numberTurnedOn == 1 && lastTurnedOn != null){
         lastTurnedOn.onclick(lastTurnedOn);
     }



 }

 function populateLookup(choicesDiv, filterString, url){

     // build the url
     //var furl = url + '?field_value=' + escape(filterString);

     // call to get the list of choices
     dojo.xhrGet( {
               url: url, 
               handleAs: "text",
               timeout: 30000,
               content: {"field_value": filterString },
               load: function(response, ioArgs){

                     console.debug("Successful submission");  
                     console.debug('Got response length = ' + response.length);

                     choicesDiv.style.display = 'block';

                     if (response.length > 0){
                         choicesDiv.innerHTML = response;
                         filterWithinLookup(choicesDiv);
                     }else{
                         choicesDiv.innerHTML = "No results found for '" + filterString + "'" ;
                     }

                     //turn off the loading div
                     choicesDiv.setAttribute('loading_items', 'false');        

                     // always return response - dojo likes it
                     return response;
               },
               error: function(response, ioArgs){
                     console.error("HTTP status code: ", ioArgs.xhr.status);
                     md.innerHTML = "Error! HTTP status code: " . ioArgs.xhr.status;
                     md.className = "messageDivAlertOn";
                     return response;
               }
       });


 }

function chooseItemLookup(itemDiv){

    var recordId = itemDiv.getAttribute('item_id');

    var wrapper = itemDiv.parentNode.parentNode.parentNode;
    var lookupDisplayDiv = wrapper.getElementsByTagName('div')[0];

    var lookupDisplay = lookupDisplayDiv.getElementsByTagName('span')[0];
    lookupDisplay.innerHTML = itemDiv.innerHTML;

    var lookupReturnInput = lookupDisplayDiv.getElementsByTagName('input')[0];
    lookupReturnInput.value = recordId;

    hideLookup(itemDiv.parentNode);
    

}

function showLookup(input){

    var wrapper = input.parentNode.parentNode;

    var lookupDisplayDiv = wrapper.getElementsByTagName('div')[0];
    lookupDisplayDiv.style.display = 'none';

    var lookupEditDiv = wrapper.getElementsByTagName('div')[1];
    lookupEditDiv.style.display = 'block';

    var lookupTextInput = lookupEditDiv.getElementsByTagName('input')[0];
    lookupTextInput.focus();
    lookupTextInput.select();

}

function hideLookup(input){

     var wrapper = input.parentNode.parentNode;

     var lookupDisplayDiv = wrapper.getElementsByTagName('div')[0];
     lookupDisplayDiv.style.display = 'block';
     var lookupEditDiv = wrapper.getElementsByTagName('div')[1];
     lookupEditDiv.style.display = 'none';

}

/**
* listens for up down and enter events 
* 
*/

function lookupKeyboardNav(lookupTextInput, event){

    var lookupEditDiv = lookupTextInput.parentNode;
    var pickListDiv =  lookupEditDiv.getElementsByTagName('div')[0];
    var pickListElements = pickListDiv.getElementsByTagName('div');

    // fail quickly for unrecognised keys or any items
    if (event.keyCode == 38 || event.keyCode == 40 || event.keyCode == 13 || pickListElements.length > 0){

        var currentItem = null;
        var nextItem = null;
        var totalHeight = 0;
        var initialScrollTop =  pickListDiv.scrollTop;
        var initialScrollBottom = initialScrollTop + pickListDiv.offsetHeight;

        // find the currently selected div

        for (var i = 0; i < pickListElements.length; i++){

            // keep track of all the height of all the elements till we get to the bottom
            totalHeight = totalHeight + pickListElements[i].offsetHeight;

            if (pickListElements[i].className == 'lookupChoiceItemSelected'){
                currentItem = pickListElements[i];
                break;
            }

        }

        switch(event.keyCode) {
            case 38: //up arrow
                if (currentItem == null){
                    nextItem =  pickListElements[pickListElements.length -1];
                }else if (currentItem.previousSibling == null){
                    nextItem = currentItem // i.e. we don't move
                }else{
                    nextItem = currentItem.previousSibling;
                    totalHeight = totalHeight - nextItem.offsetHeight;
                }
                break;
            case 40: //down arrow
                 // on the input so move onto the list
                 if (currentItem == null){
                     nextItem =  pickListElements[0];
                     totalHeight = 0;
                 }else if (currentItem.nextSibling == null){
                     nextItem = currentItem // i.e. we don't move
                 }else{
                     nextItem = currentItem.nextSibling;
                     totalHeight = totalHeight + nextItem.offsetHeight;
                 }
                 break;

            case 13: //enter
                
                if (currentItem != null){
                    currentItem.onclick(currentItem);
                }
                return;
                break;
        }


        // change the look of them
        if (currentItem != null) currentItem.className = 'lookupChoiceItem';
        if (nextItem != null){
            nextItem.className = 'lookupChoiceItemSelected';

            // calculate the scroll position

            // only act if the item isn't entirely visible
            var scroll;
            var topOfNext = totalHeight - nextItem.offsetHeight;
            var bottomOfNext = totalHeight;
            if (bottomOfNext >  initialScrollBottom || topOfNext < initialScrollTop){

                // if we are moving up we should move it just into sight at the top
                // if we are moving down then it goes just into sight at the bottom
                if (event.keyCode == 38){
                    // we are going up so the top of the item must be the top
                    // of the scroll.
                    scroll = topOfNext;
                }else{
                    // we are going down so the bottom of the item must be the
                    // bottom of the scroll window.
                    scroll = bottomOfNext - pickListDiv.offsetHeight;
                }

                // finally scroll
                pickListDiv.scrollTop = scroll;
            }

        }

    }

}

function showBalloonHelp(helpDiv){
    
    var helpPopUp = helpDiv.getElementsByTagName('div')[0];
    var helpPos = findPos(helpDiv);
    
    // draw it but keep it invisible.
    helpPopUp.style.display = 'block';
    helpPopUp.style.visibility = 'hidden';
    
    // calculate the right edge of the view port.
    var viewPortWidth = windowState.getWidth();
    var horizontalScroll = windowState.getScrollX();
    var rightEdge = viewPortWidth + horizontalScroll;
    var spaceToRight = rightEdge - helpPos[0] - 20;
    
    // display to right if there is room. if not to left
    if ( spaceToRight > helpPopUp.offsetWidth ){
        helpPopUp.style.left = '20px';
    }else{
        helpPopUp.style.left = '-' + helpPopUp.offsetWidth + 'px';
    }
    
    // calculate the bottom edge of the view port
    var viewPortHeight = windowState.getHeight();
    var verticalScroll = windowState.getScrollY();
    var bottomEdge = viewPortHeight + verticalScroll;
    var spaceToBottom = bottomEdge - helpPos[1] - 30;
    if ( spaceToBottom > helpPopUp.offsetHeight ){
        helpPopUp.style.top = '20px';
    }else{
        helpPopUp.style.top = '-' + helpPopUp.offsetHeight + 'px';
    }
    
    // now we have positioned it make it visible
    helpPopUp.style.visibility = 'visible';
    
} 


function hideBalloonHelp(helpDiv){
    var helpPopUp = helpDiv.getElementsByTagName('div')[0];
    helpPopUp.style.display = 'none';
    helpPopUp.style.top = 0;
    helpPopUp.style.left = 0;
} 


function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
	    do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
        return [curleft,curtop];
    }
}
        