/*************************************  Common Variables *********************************************************/
BR_DOM  = (document.getElementById) ? true : false;
BR_NS4  = (document.layers) ? true : false;
BR_IE   = (document.all) ? true : false;
BR_IE4  =  BR_IE && !BR_DOM;
BR_Mac  = (navigator.appVersion.indexOf("Mac") != -1);
BR_IE4M =  BR_IE4 && BR_Mac;
BR_NS6  =  BR_DOM && !BR_IE;
BR_Safari  = (navigator.appVersion.indexOf("Safari") != -1);

/*************************************** Event Related Functions ************************************************/

function replaceParamValueInURL(url, paramName, newValue){
	paramName = paramName + "=";
	var startIndex = url.indexOf(paramName) + paramName.length;
	var endIndex = url.indexOf("&", startIndex);
	if(endIndex == -1)
		endIndex=url.length;
	var paramValue = url.substring(startIndex, endIndex);
	return url.replace(paramName + paramValue, paramName + newValue);
}

function addEvent(obj, eventType, fn){
 	if(obj == null) return false;
	if (obj.addEventListener){
    	obj.addEventListener(eventType, fn,true );
	    return true;
	} else if (obj.attachEvent){
		return obj.attachEvent("on"+eventType, fn);
	}
	return false;
}

function addWindowLoadEvent(func){
	addToCallStack(window,"onload",func,true);
}

function addWindowUnLoadEvent(func){
	addToCallStack(window,"onunload",func,true);
}

function addLoadEvent(obj, fn){
	addEvent(obj, "load", fn);
}

function addKeyPressEvent(obj,fn){
	addEvent(obj, "keypress", fn);
}

function addKeyPressEventForId(id,fn){
	addKeyPressEvent(getElementById(id), fn);
}

function addClickEvent(obj, fn){
	addEvent(obj, "click", fn);

}

function addClickEventForId(id, fn){
	addClickEvent(getElementById(id), fn);
}

function addSubmitEvent(obj, func){
	addEvent(obj, "submit", func);
}

function addMouseOverEvent(id, fn){
	addEvent(getElementById(id), "mouseover", fn);
}

function addMouseOutEvent(id, fn){
	addEvent(getElementById(id), "mouseout", fn);
}

function addChangeEvent(obj,fn) {
	addEvent(obj, "change",fn);
}

function addChangeEventForId(id, fn){
	addChangeEvent(getElementById(id), fn);
}

function cancelEvent(evt) {
	if (document.layers){
    	return false;
    }else if (evt.stopPropagation) {
    	evt.stopPropagation();
	    evt.preventDefault();
	}else if (window.event){
    	return false;
    }
}

function addToCallStack(obj ,eventType,func,once){
	var prevFunc = obj[eventType];
	var prevFuncCopy = prevFunc;
	if(!(typeof (prevFunc) == "function" && prevFunc.callStack)){
		var prevFuncCopy = function(){
						   	  var prevFuncCopyStack=prevFuncCopy.callStack;
							  for(var i=0;i<prevFuncCopyStack.length;i++){
								  if(prevFuncCopyStack[i].apply(this,arguments)===false){
									  break;
								  }
							  }
							  if(once){
								  try{
									  obj[eventType]=null;
								  } catch(e){
								  }
							  }
						  };
		prevFuncCopy.callStack = [];
		if(typeof (prevFunc)=="function"){
			prevFuncCopy.callStack.push(prevFunc);
		}
		obj[eventType]=prevFuncCopy;
	}
	prevFuncCopy.callStack.push(func);
}
/*
 * Gets the Text node for an HTML element
 */
function getTextNode(element)
{
        if (element != null)
        {
            var nodes = element.childNodes;
            for (var j = 0; j < nodes.length; j++)
            {
                var node = nodes[j];
                if (node.nodeType == 3)
                {
                    return node;
                }
            }
        }
        return null;
}

/*********************************** Setting target attributes and child windows ***************************/

function setTargetForElementById(id, target){
	var element = getElementById(id);
	element.target = target;
}

function setTargetForElementsWithClass(name, target){
	for(var i = 0; i < document.links.length; i++) {
      if(document.links[i].className == name){
        document.links[i].target = target;
      }
    }
}

function attachTarget(id, target){
	var obj = getElementById(id);
	if(obj != null){
		if(obj.tagName == "A"){
			obj.target = target;
		}else{
			var linkArray = obj.getElementsByTagName("A");
		    for (i=0; i < linkArray.length; ++i) {
		    	if(linkArray[i].className != "primaryNavigation"){
			       linkArray[i].target = target;
			    }
		    }
		}
	}
}

function openGaleChildWindow(){
   window.open(this.href,"galeChildWindow","toolbar=no, directories=no, status=no, location=no, resizable=yes, menubar=no, scrollbars=yes,screenX=50,screenY=50,top=50,left=50,width=750,height=550");
   return false;
}

function openVideoWindow(){
   window.open(this.href,"galeChildWindow","toolbar=no, directories=no, status=no, location=no, resizable=no, menubar=no, scrollbars=no,screenX=50,screenY=50,top=50,left=50,width=320,height=340");
   return false;
}

function openPrintWindow(){
   window.open(this.href,"galeChildWindow","toolbar=no, directories=no, status=no, location=no, resizable=yes, menubar=yes, scrollbars=yes,screenX=50,screenY=50,top=50,left=50,width=750,height=550");
   return false;
}

function openInfomarkWindow(){
   window.open(this.href,"galeChildWindow","menubar=yes,toolbar=no,resizable=yes,scrollbars=yes,width=850,height=500");
   return false;
}

function openInChildWindow(url, childWindowName){
   window.open(url, childWindowName,"toolbar=no, directories=no, status=no, location=no, resizable=yes, menubar=no, scrollbars=yes,screenX=50,screenY=50,top=50,left=50,width=750,height=550");
}

function openInChildWindowWithMenuBar(url, childWindowName){
   window.open(url, childWindowName,"toolbar=yes, directories=no, status=no, location=no, resizable=yes, menubar=yes, scrollbars=yes,screenX=50,screenY=50,top=50,left=50,width=750,height=550");
}

function attachEventForLink(id, fn){
	var obj = getElementById(id);
	if(obj != null){
		if(obj.tagName == "A"){
			obj.onclick = fn;
		}else{
			attachEventToChildLinks(obj, fn);
		}
	}
}

function attachPopup(id, fn){
	attachEventForLink(id, fn);
}

function attachPopupForSelector(selector, fn){
	var obj = document.getElementsBySelector(selector);
	if(isValidObject(obj) && obj.length >0){
		if(obj[0].tagName == "UL"){
			for(var i=0;i<obj.length;i++){
				var liCollection = obj[i].getElementsByTagName("LI");
				for(var j=0;j<liCollection.length;j++){
					attachEventToChildLinks(liCollection[j], fn);
				}
			}
		}else if(obj[0].tagName == "LI"){
			for(var j=0;j<obj.length;j++){
				attachEventToChildLinks(obj[j], fn);
			}
		}
		else if( obj[0].tagName == "A" )
		{
			for( var j=0; j<obj.length; j++ )
			{
				obj[j].onclick = fn;
			}
		}
		else{
			attachEventToChildLinks(obj, fn);
		}
	}
}

function attachEventToChildLinks(obj, fn){
	var linkArray = obj.getElementsByTagName("A");
    for (i=0; i < linkArray.length; ++i) {
       linkArray[i].onclick = fn;
    }
}

function getXmlHttpRequest() {
	var xmlHttpReq = false;
    if (window.XMLHttpRequest) {
		xmlHttpReq = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		try {
      		xmlHttpReq = new ActiveXObject("MSXML2.XMLHttp");
	    } catch (ex) {
			try{
		    	xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
       		}catch (execp){
	    	}
    	}
	}
	return xmlHttpReq;
}

/* parse and post a request using XML HTTP Request */
function postRequest(url) {
	url = unescape(url);
	var urlParams = "";
	var baseURL = url;
    var ipos = url.indexOf('?');
    if (ipos > -1) {
		urlParams = url.substr(ipos+1);
		baseURL = url.substr(0, ipos);
	}

    var xmlhttp = getXmlHttpRequest();
 	xmlhttp.open("POST", baseURL, true);
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlhttp.send(urlParams);
}
/************************************************ Common Scripts *************************************************/

function getElementById(name) {
	var thisObj;
	if (document.getElementById) {
		thisObj = document.getElementById(name);
	} else if (document.all) {
		thisObj = document.all[name];
	} else if (document.layers) {
		thisObj = document.layers[name];
	}
	return thisObj;
}

function getElementByName(name) {
	var thisObj;
	if (document.getElementByName) {
		thisObj = document.getElementByName(name);
	} else if (document.all) {
		thisObj = document.all[name];
	} else if (document.layers) {
		thisObj = document.layers[name];
	}
	return thisObj;
}

function trim(stringValue){
	return stringValue.replace( /^\s*/, "" ).replace( /\s*$/, "" );
}

function lTrim(stringValue){
	return stringValue.replace( /^\s*/, "" );
}

function rTrim(stringValue){
	return stringValue.replace( /\s*$/, "" );
}

function getCookie(name) {
	var cookieName = name + "=";
	var cookieString = document.cookie;
	var cookieValue = null;
	if (cookieString.length > 0) {
		begin = cookieString.indexOf(cookieName);
		if (begin!= -1) {
			begin += cookieName.length;
			end = cookieString.indexOf(";", begin);
			if (end == -1)  end = cookieString.length;
			cookieValue = unescape(cookieString.substring(begin, end));
		}
	}
	return cookieValue;
}

function setCookie(name, value) {
	document.cookie = name + "=" + escape (value);
}

/************************************ get Element by selector *****************************************************/
function getAllChildren(e) {
  // Returns all children of element. Workaround required for IE5/Windows. Ugh.
  return e.all ? e.all : e.getElementsByTagName('*');
}

document.getElementsBySelector = function(selector) {
  // Attempt to fail gracefully in lesser browsers
  if (!document.getElementsByTagName) {
    return new Array();
  }
  // Split selector in to tokens
  var tokens = selector.split(' ');
  var currentContext = new Array(document);
  for (var i = 0; i < tokens.length; i++) {
    token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');;
    if (token.indexOf('#') > -1) {
      // Token is an ID selector
      var bits = token.split('#');
      var tagName = bits[0];
      var id = bits[1];
      var element = document.getElementById(id);
      if (tagName && element.nodeName.toLowerCase() != tagName) {
        // tag with that ID not found, return false
        return new Array();
      }
      // Set currentContext to contain just this element
      currentContext = new Array(element);
      continue; // Skip to next token
    }
    if (token.indexOf('.') > -1) {
      // Token contains a class selector
      var bits = token.split('.');
      var tagName = bits[0];
      var className = bits[1];
      if (!tagName) {
        tagName = '*';
      }
      // Get elements matching tag, filter them for class selector
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      continue; // Skip to next token
    }
    // Code to deal with attribute selectors
    if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
      var tagName = RegExp.$1;
      var attrName = RegExp.$2;
      var attrOperator = RegExp.$3;
      var attrValue = RegExp.$4;
      if (!tagName) {
        tagName = '*';
      }
      // Grab all of the tagName elements within current context
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var checkFunction; // This function will be used to filter the elements
      switch (attrOperator) {
        case '=': // Equality
          checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
          break;
        case '~': // Match one of space seperated words
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
          break;
        case '|': // Match start with value followed by optional hyphen
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
          break;
        case '^': // Match starts with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
          break;
        case '$': // Match ends with value - fails with "Warning" in Opera 7
          checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
          break;
        case '*': // Match ends with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
          break;
        default :
          // Just test for existence of attribute
          checkFunction = function(e) { return e.getAttribute(attrName); };
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (checkFunction(found[k])) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
      continue; // Skip to next token
    }
    // If we get here, token is JUST an element (not a class or ID selector)
    tagName = token;
    var found = new Array;
    var foundCount = 0;
    for (var h = 0; h < currentContext.length; h++) {
      var elements = currentContext[h].getElementsByTagName(tagName);
      for (var j = 0; j < elements.length; j++) {
        found[foundCount++] = elements[j];
      }
    }
    currentContext = found;
  }
  return currentContext;
}

/* That revolting regular expression explained
/^(\w+)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/
  \---/  \---/\-------------/    \-------/
    |      |         |               |
    |      |         |           The value
    |      |    ~,|,^,$,* or =
    |   Attribute
   Tag
*/

/* document.getElementsBySelector(selector)
   - returns an array of element objects from the current document
     matching the CSS selector. Selectors can contain element names,
     class names and ids and can be nested. For example:

       elements = document.getElementsBySelect('div#main p a.external')

     Will return an array of all 'a' elements with 'external' in their
     class attribute that are contained inside 'p' elements that are
     contained inside the 'div' element which has id="main"
     */
/******************************** Setting base font for the page **********************************************/

function setInitialFontSize(){
	var size = getCookie("base-font");
	if(!isValidObject(size)){
		size = getDefaultFontSize();
        setCookie("base-font", size);
    }
	setBaseFontSize(size);
}

function setBaseFontSize(size){
    document.getElementsByTagName("html")[0].style.fontSize = size + "%";
}

function getDefaultFontSize(){
    return "100";
}

function getBaseFontSize() {
    var size = getCookie("base-font");
 	if(!isValidObject(size)){
		size = getDefaultFontSize();
    }
    return size;
}

function isValidObject(obj) {
	return (obj == null || obj == undefined || obj == false)? false : true;
}

function getParamValueInURL(url, paramName){
	paramName = paramName + "=";
	var startIndex = url.indexOf(paramName) + paramName.length;
	var endIndex = url.indexOf("&", startIndex);
	if(endIndex == -1)
		endIndex=url.length;
	var paramValue = url.substring(startIndex, endIndex);
	return paramValue;

}
function addChangeEventForSubDivId(fn){
var divIds=document.getElementsByName("termsBy");
for(index=0;index<divIds.length;index++)
{
var id=divIds[index].id;
addChangeEvent(getElementById(id),fn);
}
}
function isNumeric(numberString){
	if (numberString.length == 0 || isNaN(numberString) ) return false;
	//just to make sure only numeric terms were entered.
	var numericPattern = "^[0-9]+$";
	var numericExp = new RegExp(numericPattern);
	return numericExp.test(numberString);
}


	function ShowDiv(){
			var dv=document.getElementById('addthis_dropdown15');
			dv.style.display="block";
			
			}

	function HideDiv(){
			var dv=document.getElementById('addthis_dropdown15');
			dv.style.display="none";
			
			
}


 sfHover = function() {

     attachDropDownMenu("toolbox");
            $('#toolbox a.noopen').click(function(){
                   return false;
            })

             if($('#research_tools').length > 0) {attachDropDownMenu("research_tools");}
             if($('#educator_resources').length > 0) {attachDropDownMenu("educator_resources");}
            //alert("The browser version is:" + jQuery.browser.version);
      }

function attachDropDownMenu(id) {
            if(isValidObject(getElementById(id))) {

                $("#"+id).hover(
                function() {
                    $(this).addClass("sfhover")
                    if($('#'+id+' ul').length > 0) {

                        if((id == "research_tools" || id == "educator_resources") ) {
                           $('#searchNav li ul').css('left','auto'); 
                        }   else {
                            $('#titleBar_holder li ul').css('left','auto');
                        }
                    }
                },
                function() {

                    $(this).removeClass("sfhover");

                    if($('#'+id+' ul').length > 0) {

                         if((id == "research_tools" || id == "educator_resources")) {
                           $('#searchNav li ul').css('left','-9999px');
                        }   else {
                            $('#titleBar_holder li ul').css('left','-9999px');
                        }
                    }

                }
                )

            }
		}

     if (window.attachEvent) {
          addWindowLoadEvent(sfHover);
     }

      //--><!]]>
      function setStyle(where,theclass){

      document.getElementById(where).className=theclass;

      }

function fixZindex() {
     if (window.attachEvent) {
          if($('.fix-z-index').length > 0)  {
              $('.fix-z-index').bgiframe();
          }
     }
}

addWindowLoadEvent(fixZindex);

function handleEscapeXml(url) {
    return url.replace(new RegExp("&amp;", "gi"), "&");
}

addWindowLoadEvent(setInitialFontSize);


function checkImgSize() {
   if($('#feat_vid_img').length > 0) {

    var imgWidth = $("#feat_vid_img").width();
    var imgHeight = $("#feat_vid_img").height();

    //alert('height:'+imgHeight+', width:'+imgWidth)

   $('.vid_overlay a').css('height',imgHeight)
   $('.vid_overlay a').css('width',imgWidth)
   }

}


function homeworkHelper(id) {
    $('#homework_helper a').click(function(e){
        e.preventDefault();
         window.open($(this).attr('href'),"galeChildWindow","menubar=yes,toolbar=no,resizable=yes,scrollbars=yes,width=1000,height=500");

    });
}


function homeworkHelperm(id) {
    $('#homework_helper_m a').click(function(e){
        e.preventDefault();
         window.open($(this).attr('href'),"galeChildWindow","menubar=yes,toolbar=no,resizable=yes,scrollbars=yes,width=1000,height=500");

    });
}

addWindowLoadEvent(homeworkHelper);
addWindowLoadEvent(homeworkHelperm);
addWindowLoadEvent(checkImgSize);