/* Append events to the onLoad event */


/// Helper method to allow us to add multiple events to the Body onload event
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}


// unloads event
function addUnloadEvent(func) {
    var oldonunload = window.onunload;
    if (typeof window.onunload != 'function') {
        window.onunload = func;
    } else {
        window.onunload = function() {
            oldonunload();
            func();
        }
    }
} 

/// Helper method to insert a new element after a provided element
function insertAfter(newElement,targetElement) {
  var parent = targetElement.parentNode;
  if (parent.lastChild == targetElement) {
    parent.appendChild(newElement);
  } else {
    parent.insertBefore(newElement,targetElement.nextSibling);
  }
}

/// Helper method to add a html class to the provided element
function addClass(element,value) {
  if (!element.className) {
    element.className = value;
  } else {
    newClassName = element.className;
    newClassName+= " ";
    newClassName+= value;
    element.className = newClassName;
  }
}

// RemoveClass
function removeClass(el,cl){
    if(typeof el=='undefined')return;
    if(el.className===null)return;
    var classes=el.className.split(" ")
    var result=[]
    for(i in classes){
        if(classes[i] !=cl) result[result.length]=classes[i];
    }
    el.className=result.join(" ")
}

/// Method to set form focus on the supplied element
function setFocus(elementId){
    if (!document.getElementById) return false;
    
    var textField;
    textField  = document.getElementById(elementId);

    if (!textField)
    {
        return false; 
    }
    else
    {
        textField.focus();
    }
}


// Method to set form focus on the supplied element
// accepting a second parameter of a second element that, if has focus,
// we should not take the focus from
function setFocusNotIntrusive(elementId, elementIdDoNotTakeFocus) {
    if (!document.getElementById) return false;
    if (!document.activeElement) return false;

    var textFieldToFocusOn;
    textFieldToFocusOn = document.getElementById(elementId);

    var textFieldToNotTakeFocusFrom;
    textFieldToNotTakeFocusFrom = document.getElementById(elementIdDoNotTakeFocus);

    if (!textFieldToFocusOn || !textFieldToNotTakeFocusFrom) 
    {
        return false;
    }
    else if (document.activeElement == textFieldToNotTakeFocusFrom) 
    {
        return false;
    }
    else
    {
        // both elements exist and the latter doesn't currently have focus so we can go ahead
        textFieldToFocusOn.focus();
    }
}



///Method to stripe tables
function stripeTables() {

    
  if (!document.getElementsByTagName) return false;
  var tables = document.getElementsByTagName("table");
 
  for (var i=0; i<tables.length; i++) {

      if (tables[i].className.indexOf("noStripe") == -1 && tables[i].className.indexOf("cke_editor") == -1)
      {
            var odd = false;
            var rows = tables[i].getElementsByTagName("tr");
                      
            for (var j=0; j<rows.length; j++) 
            {  
              if (odd == true) 
              {
                addClass(rows[j],"even");
                odd = false;
              } 
              else 
              {
	            addClass(rows[j],"odd");        
	            odd = true;
               }
            }
       }
      else
      {
      } 
  }
}

///Helper method to find elements by Class Name - pass the classname to search for, the tag to look for (* for all) and the element to search under
function getElementsByClassName(className, tag, elm){
	var testClass = new RegExp("(^|\\\\s)" + className + "(\\\\s|$)");
	var tag = tag || "*";
	var elm = elm || document;
	var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
	var returnElements = [];
	var current;
	var length = elements.length;
	for(var i=0; i<length; i++){
		current = elements[i];
		if(testClass.test(current.className)){
			returnElements.push(current);
		}
	}
	return returnElements;
}

// this is a function to test whether the browser is javascript enabled
// use results cautiously
function TestJavaScript()
{

    if(document.getElementById('testJavaScript') != null)
    {
        document.getElementById('testJavaScript').value = '1';
    }
     if(document.getElementById('testJavaScriptSubform') != null)
    {
        document.getElementById('testJavaScriptSubform').value = '1';
    }
}

///Method to show the Back button container and attach the JS back functionality to the OnClick event
function showBackButton(){
    
    var buttonContainer = document.getElementById("dvBack");
    var backButton =  document.getElementById("btnBack");

    if(buttonContainer.style.display == 'none')
       {
            buttonContainer.style.display = 'block'; 
        }

        // attach a simple back function to the button
        backButton.onclick = function() {   
            history.go(-1);
            } 
    }

///Method to show the print button attach the JS print functionality to the OnClick event
function showPrintButton(newDisplay){

    var printButton =  document.getElementById("btnPrint");

    if(printButton.style.display == 'none')
       {
            printButton.style.display = newDisplay; 
        }

        // attach a simple print function to the button
        printButton.onclick = function() {   
            window.print();
            } 
    }

///Method to show the Refine search container and attach the JS back functionality to the OnClick event of the link
function showRefineSearchButton()
{

   // get all list items on the page with a class of jsRefineButton 
    var buttonContainers = getElementsByClassName("jsRefineButton", "li", document);
    
    for (var i=0; i<buttonContainers.length; i++)
    {
        // rate a new link inside the matching list items
        var newLink = document.createElement("A");
        var defaultLinkText = document.createTextNode("[Back]");
        // append the text node to the link
        newLink.appendChild(defaultLinkText);
        newLink.setAttribute("href", "#");
        // attach a simple back function to the link
        newLink.onclick = function() 
        {   
        history.go(-1); return false;
        }
        buttonContainers[i].appendChild(newLink);
        
        if(buttonContainers[i].style.display == 'none')
        {
            buttonContainers[i].style.display = 'inline'; 
         }
       }   
    }


    //added to freeze the screen to prevent users from double-clicking submit buttons
    function FreezeScreen() {
        scroll(0, 0);
        var outerPane = document.getElementById('FreezePane');
        var innerPane = document.getElementById('InnerFreezePane');
        if (outerPane) outerPane.className = 'FreezePaneOn';
        if (innerPane) innerPane.innerHTML = 'Your data is being processed.  Please wait.';
        
    }

    //used in the simple search control
    function overlayTextBoxes() {
        // Search for inputs and overlay text if they have a txtOverlay class and their title attribute is set
        var inputs = document.getElementsByTagName("INPUT");
        var n_inputs = inputs.length;
        var j;
        for (j = 0; j < n_inputs; j++) {
            if ((inputs[j].className.indexOf('txtOverlay') > 0)) {
                // set the default text to whatever is in the title attribute
                inputs[j].value = inputs[j].title;
            }
        }
    }

    function initOverLabels() {
        if (!document.getElementById) return;

        var labels, id, field;

        // Set focus and blur handlers to hide and show
        // LABELs with 'overlabel' class names.
        labels = document.getElementsByTagName('label');
        for (var i = 0; i < labels.length; i++) {

            if (labels[i].className == 'overlabel') {

                // Skip labels that do not have a named association
                // with another field.
                id = labels[i].htmlFor || labels[i].getAttribute('for');
                if (!id || !(field = document.getElementById(id))) {
                    continue;
                }

                // Change the applied class to hover the label
                // over the form field.
                labels[i].className = 'overlabel-apply';

                // Hide any fields having an initial value.
                if (field.value !== '') {
                    hideLabel(field.getAttribute('id'), true);
                }

                // Set handlers to show and hide labels.
                field.onfocus = function() {
                    hideLabel(this.getAttribute('id'), true);
                };
                field.onblur = function() {
                    if (this.value === '') {
                        hideLabel(this.getAttribute('id'), false);
                    }
                };

                // Handle clicks to LABEL elements (for Safari).
                labels[i].onclick = function() {
                    var id, field;
                    id = this.getAttribute('for');
                    if (id && (field = document.getElementById(id))) {
                        field.focus();
                    }
                };

            }
        }
    };

    function hideLabel(field_id, hide) {
        var field_for;
        var labels = document.getElementsByTagName('label');
        for (var i = 0; i < labels.length; i++) {
            field_for = labels[i].htmlFor || labels[i].getAttribute('for');
            if (field_for == field_id) {
                labels[i].style.textIndent = (hide) ? '-1000px' : '0px';
                return true;
            }
        }
    }


    /// Helper method to allow us to scroll to an element onscreen
    function skipTo(element) 
    {
        if (document.getElementById(element)) 
        {
            document.getElementById(element).scrollIntoView(true);
        }
    }


    function yellowFade(el) {

        var b = 155;
        function f() {
            el.style.background = 'rgb(255,255,' + (b += 4) + ')';
            if (b < 255) {
                setTimeout(f, 40);
            }
        };
        f();
    }


    function ConfirmDelete(entityName) {
        return confirm('are you sure you want to delete this ' + entityName + '?');
    }       
