// JavaScript Document
//http://www.alistapart.com/articles/makingcompactformsmoreaccessible
addEvent(window,'load',lblControler);
addEvent(window,'load',OverMenu);
addEvent(window,'load',fixHeightContainers);
addEvent(window,'load',fixHeightLists);
addEvent(window,'load',initFormsSubmit);
/*addEvent(window,'load',breakAllWords);*/

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');
  //console.debug("labels", labels);
  for (var i = 0; i < labels.length; i++) {
    //console.debug("over label found %b",(labels[i].className.indexOf('overlabel') == 0) );
    if (labels[i].className.indexOf('overlabel ') == 0) {

      // 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.
	  //console.debug("before find and replace: %s",labels[i].className);
      labels[i].className = labels[i].className.replace('overlabel','overlabel-apply');
	  //console.debug("after replace: %s",labels[i].className);
	  
      // 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) ? '-3000px' : '0px';
      return true;
    }
  }
}

var loaded = false;
function lblControler()
{
	if(!loaded) 
	{ initOverLabels(); 
		loaded = true;
	}
	setTimeout(initOverLabels, 100);
}

// firebug degradiation
if (! ("console" in window) || !("firebug" in console)) {
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group"
                 , "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
    window.console = {};
    for (var i = 0; i <names.length; ++i) window.console[names[i]] = function() {};
}

// utility functions 
function endBubble(evt)
{
    if(evt.cancelBubble == false){ 
        evt.cancelBubble = true; 
        evt.returnValue = false;
        
     }
	 if (evt.stopPropagation) {
	    evt.stopPropagation(); 
	    evt.preventDefault();
    	
	 }
}
function addEvent(_target,_event,_function){
	if (_target.addEventListener)
		_target.addEventListener(_event, _function, false );
	else{
		_target.attachEvent('on'+_event, _function);
		ieModel = true;	
	}	
}
/**
 * This function allows the programmer to retrieve objects biased on the class name you 
 * want to retrieve. Similar to the GetElementByID and GetElementByTagName.
 * @member UtilNS
 * @param {object} oElm The object you want to search, could be a whole document or something more specific.
 * @param {string} strTagName The string containing the name of the tag name i.e. "a", "div", "span" what ever the class name is attached to.
 * If no tag is given it will search all elements.
 * @param {string} strClassName The string containing the class name you're searching for
 * @returns An array filled with the class names found in the search
 * @type Array
 * {@link  http://www.robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/#more-256 getElementsByClassName} Utility Function
 */
 
 
 // code Seaarch
 
 function initFormsSubmit(){
   try{
      var _form=document.forms[0];
      //searchSubmit
	  var searchBtn = document.getElementById("searchButton");
		if(searchBtn)
		addEvent(searchBtn,'click',searchSubmit);
	  
	  var searchInput = document.getElementById("searchInput");
      	if(searchInput)
      	addEvent(searchInput,'keypress',function(e){
        	 if(catchKeyEvent(e,13)==true)
         	{
            	searchSubmit(e);
         	}
      	});
   }catch(ex){ }
}
function searchSubmit(e){
   try{
	  var _form=document.forms[0];
	  var _keyword =  _form.searchInput.value; // document.getElementById('search');
      document.location='/search.aspx?id=3852&keyword='+_keyword;
   }catch(ex){}
}

function catchKeyEvent(e,key){
   var _keyCode=keyCodeEvent(e);
   if(_keyCode!=null && key==_keyCode){
      cancelEvent(e);
      return true;
   }
   return false;
}
function keyCodeEvent(e){
   var _keyCode=null;
   if (!e) e = window.event;
   if(e.keyCode){
      _keyCode=e.keyCode;
   }else if(e.which){
      _keyCode=e.which;
   }else if(e.charCode){
      _keyCode=e.charcode;
   }
   return _keyCode;
}
function cancelEvent(e) {
   if (!e) e = window.event;
   if (e.preventDefault) {
      e.preventDefault();
   } else {
      e.returnValue = false;
   }
}



 

function getElementsByClassName(oElm, strTagName, strClassName){
	var arrElements = (strTagName == "*" && document.all)? document.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 OverMenu(){
		menu=document.getElementById("nav_top");	
		if (menu != null )
		{
		    bgmenu=document.getElementById("nav_main");
		    for (i=0; i<menu.childNodes.length; i++) {
			    node = menu.childNodes[i];
			    if (node.nodeName=="LI") {
				    node.onmouseover=function() {					
					    if((document.body.className=="interior")||(document.body.className=="exterior")){
					    this.className+=" Over";
					    }
				    }
				    node.onmouseout=function() {
					    if((document.body.className=="interior")||(document.body.className=="exterior")){
						    this.className=this.className.replace("Over", "");
					    }					
				    }
			    }
		    }
		}
	}
function fixHeightContainers() {
	var rowBoxes = getElementsByClassName(document, "div", "row");
		for(var i=0; i < rowBoxes.length; i++)
		{
			var divs = new Array();
			
			for(var j=0; j < rowBoxes[i].childNodes.length; j++)
			{
				if(rowBoxes[i].childNodes[j].tagName == "DIV")
				{
					divs.push(rowBoxes[i].childNodes[j]);					
				}
			}
			
			switch(divs.length) {
			case 2:
				setTall(divs[0],divs[1] );
			break;
			
			case 3:
				setTall(divs[0],divs[1],divs[2] );
			break;
			
			default:;
				
			}
		}
}
function fixHeightLists() {
	var rowBoxes = getElementsByClassName(document, "ul", "row");
		for(var i=0; i < rowBoxes.length; i++)
		{
			var lis = new Array();
			
			for(var j=0; j < rowBoxes[i].childNodes.length; j++)
			{
				if(rowBoxes[i].childNodes[j].tagName == "LI")
				{
					lis.push(rowBoxes[i].childNodes[j]);					
				}
			}
			
			switch(lis.length) {
			case 2:
				setTallList(lis[0],lis[1] );
			break;
			
			case 3:
				setTallList(lis[0],lis[1],lis[2] );
			break;
			
			case 4:
				setTallList(lis[0],lis[1],lis[2],lis[3] );
			break;
			
			case 5:
				setTallList(lis[0],lis[1],lis[2],lis[3],lis[4] );
			break;
			
			default:;
				
			}
		}
}
function setTallList() {	
		lis = arguments;
		// Let's determine the maximum height out of all columns specified
		var maxHeight = 0;
		for (var i = 0; i < divs.length; i++) {
			if (lis[i].offsetHeight > maxHeight) maxHeight = lis[i].offsetHeight;
		}
		
		for (var i = 0; i < lis.length; i++) {
			lis[i].style.height = maxHeight + 'px';
			
			if (lis[i].offsetHeight > maxHeight) {
				lis[i].style.height = (maxHeight - (lis[i].offsetHeight - maxHeight)) + 'px';
				
			}
			
		}
}
function setTall() {	
		divs = arguments;
		// Let's determine the maximum height out of all columns specified
		var maxHeight = 0;
		for (var i = 0; i < divs.length; i++) {
			if (divs[i].offsetHeight > maxHeight) maxHeight = divs[i].offsetHeight;
		}
		
		for (var i = 0; i < divs.length; i++) {
			divs[i].style.height = maxHeight + 'px';
			
			if (divs[i].offsetHeight > maxHeight) {
				divs[i].style.height = (maxHeight - (divs[i].offsetHeight - maxHeight)) + 'px';
				
			}
			
		}
}



/* for PNG Images in IE 6 */
function applyPNGFilters(){
if( navigator.appVersion.indexOf('MSIE 6')!=-1 && document.body.filters){
for(var i=0; i<document.images.length; i++) {
var img = document.images[i];
var imgName = img.src.toUpperCase()
if (imgName.substring(imgName.length-3, imgName.length) == "PNG"){
var imgID = (img.id) ? "id='" + img.id + "' " : "";
var imgClass = (img.className) ? "class='" + img.className + "' " : "";
var imgTitle = (img.title) ? 'title="' + img.title + '" ' : 'title="' + img.alt + '" ';
var imgStyle = "display:inline-block;" + img.style.cssText;
if (img.align == "left") imgStyle = "float:left;" + imgStyle;
if (img.align == "right") imgStyle = "float:right;" + imgStyle;
if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle;
var strNewHTML = "<span " + imgID + imgClass + imgTitle
+ " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
+ "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>";
img.outerHTML = strNewHTML;
i = i-1;
}
}
}
}
//Add Emulation of LI:hover for IE 6/
if(navigator.appVersion.indexOf('MSIE 6')!=-1){
addEvent(window,'load',applyPNGFilters);
}

function fileUpload(button,text){
		textbox=document.getElementById(""+text);
		textbox.value=button.value;
		textbox.stylezIndex=3;
	}
	/*--START--FOR DYNAMIC QUESTION TREE*/
	function DynQueTreechekIn(){
    var docElement=document.getElementById('divList');
    
        for (i=0; i<docElement.getElementsByTagName('INPUT').length; i++) {
            docElement.getElementsByTagName('INPUT')[i].checked=true;	            
	        }
	}
		function DynQueTreechekOut(){
        var docElement=document.getElementById('divList');
		for (i=0; i<docElement.getElementsByTagName('INPUT').length; i++) {
	            docElement.getElementsByTagName('INPUT')[i].checked=false;
	        }
	}
	function DynQueTreegetCatID(){
	   var cid = new Array;
	   var docElement=document.getElementById('divList');
	   for(i=0; i<docElement.getElementsByTagName('INPUT').length; i++){
	       if ( docElement.getElementsByTagName('INPUT')[i].checked ) {
	           cid.push(docElement.getElementsByTagName('INPUT')[i].value);
	       }
	   }
	   return cid.join();
	}
	/*--END-- FOR DYNAMIC QUESTION TREE*/
	
	/******************************************** BEGIN MODAL WINDOW **************************************/
function showIframe(url,width,height){
var internalPopupShadow=document.getElementById("internalPopupShadow");
var internalPopupDiv=document.getElementById("internalPopupDiv");
var iframe=document.getElementById("internalPopupIframe");

internalPopupShadow.style.display="block";
internalPopupDiv.style.display="block";
iframe.src=url;
internalPopupDiv.style.width=width+"px";
internalPopupDiv.style.height=height+"px";
internalPopupDiv.style.display="block";
iframe.style.width=width+"px";
iframe.style.height=height+"px";
iframe.style.display="block";
}
function closeIframe(){
var internalPopupShadow=document.getElementById("internalPopupShadow");
var internalPopupDiv=document.getElementById("internalPopupDiv");
var iframe=document.getElementById("internalPopupIframe");
internalPopupShadow.style.display="none";
internalPopupDiv.style.display="none";
iframe.style.display="none";
	}
	/******************************************** END MODAL WINDOW ********************************************/
	
		function breakWord(dEl){
        
        
        if(!dEl || dEl.nodeType !== 1){
          
          return false;
        
        } else if(dEl.currentStyle && typeof dEl.currentStyle.wordBreak === 'string'){
          
          //Lazy Function Definition Pattern, Peter's Blog
          //From http://peter.michaux.ca/article/3556
          
          breakWord = function(dEl){
            //For Internet Explorer
            dEl.runtimeStyle.wordBreak = 'break-all';
            return true;
          }
          
          return breakWord(dEl);
         
        }else if(document.createTreeWalker){
       
          //Faster Trim in Javascript, Flagrant Badassery
          //http://blog.stevenlevithan.com/archives/faster-trim-javascript
          
          var trim = function  (str) {
            str = str.replace(/^\s\s*/, '');
            var ws = /\s/,
            i = str.length;
            while (ws.test(str.charAt(--i)));
            return str.slice(0, i + 1);
          }
          
          //Lazy Function Definition Pattern, Peter's Blog
          //From http://peter.michaux.ca/article/3556
          
          breakWord = function(dEl){
            
            //For Opera, Safari, and Firefox
            var dWalker = document.createTreeWalker(dEl, NodeFilter.SHOW_TEXT, null, false);
            var node,s,c = String.fromCharCode('8203');
            while (dWalker.nextNode())
            {
              node = dWalker.currentNode;
              //we need to trim String otherwise Firefox will display 
              //incorect text-indent with space characters
              s = trim( node.nodeValue ) .split('').join(c);
              node.nodeValue = s;
            }
            return true;
          }
          
          return breakWord(dEl);
          
          
        }else{
          return false;
        }
      }

 //Break All Words

  function breakAllWords(){
        var dEl = document.getElementById('pageContent');
         breakWord(dEl);
      }
      
  function ClearFields(formName)
  {
    if(formName == 'EJ_SEARCH')
    {
        document.getElementById('ctl00_ContentPlaceHolder1_txtKeywords').value = '';
        document.getElementById('ctl00_ContentPlaceHolder1_txtAuthor').value = '';
        
        var topicLen = document.getElementById('ctl00_ContentPlaceHolder1_datTopic').options.length;
        var yearLen = document.getElementById('ctl00_ContentPlaceHolder1_ddlYear').options.length;
        var quarterLen = document.getElementById('ctl00_ContentPlaceHolder1_ddlQuarter').options.length;
        
        for(i=0; i<topicLen; i++)
            document.getElementById('ctl00_ContentPlaceHolder1_datTopic').options[i].selected = false;

        for(i=0; i<yearLen; i++)
            if(document.getElementById('ctl00_ContentPlaceHolder1_ddlYear').options[i].text == '')
            {
                document.getElementById('ctl00_ContentPlaceHolder1_ddlYear').options[i].selected = true;
                break;
            }

        for(i=0; i<quarterLen; i++)
            if(document.getElementById('ctl00_ContentPlaceHolder1_ddlQuarter').options[i].text == '')
            {
                document.getElementById('ctl00_ContentPlaceHolder1_ddlQuarter').options[i].selected = true;
                break;
            }
    }
    
    else if(formName == 'CP_SEARCH')
    {
        document.getElementById('ctl00_ContentPlaceHolder1_txtKeywords').value = '';
        document.getElementById('ctl00_ContentPlaceHolder1_txtAuthor').value = '';
        
        var topicLen = document.getElementById('ctl00_ContentPlaceHolder1_datTopic').options.length;
        var yearLen = document.getElementById('ctl00_ContentPlaceHolder1_ddlYear').options.length;
        
        for(i=0; i<topicLen; i++)
            document.getElementById('ctl00_ContentPlaceHolder1_datTopic').options[i].selected = false;

        for(i=0; i<yearLen; i++)
            if(document.getElementById('ctl00_ContentPlaceHolder1_ddlYear').options[i].text == '')
            {
                document.getElementById('ctl00_ContentPlaceHolder1_ddlYear').options[i].selected = true;
                break;
            }
    }
  }


