/* -----------------------------------------------------------
general form element and event handling functions
-------------------------------------------------------------- */

function getElement (elementId) {
	var elem, vis;
	if( document.getElementById ) // this is the way the standards work
		elem = document.getElementById( elementId );
	else if( document.all ) // this is the way old msie versions work
		elem = document.all[elementId];
	else if( document.layers ) // this is the way nn4 works
		elem = document.layers[elementId];
	return elem;
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

function addEvent(elm, evType, fn, useCapture)
// addEvent and removeEvent
// cross-browser event handling for IE5+,	NS6 and Mozilla
// By Scott Andrew
{
	if (elm.addEventListener){
		elm.addEventListener(evType, fn, useCapture);
		return true;
	} else if (elm.attachEvent){
		var r = elm.attachEvent("on"+evType, fn);
		return r;
	} else {
		alert("Handler could not be removed");
	}
}

function captureEvent (FFevent, IEevent) {
	if (FFevent) return FFevent;
	else return IEevent;
}

function getCheckBoxValues (elementName) {
	var cbArray = document.getElementsByName(elementName);
	var checkBoxValues = "";
	for (var i=0; i<cbArray.length; i++) {
		if (cbArray[i].checked) checkBoxValues = checkBoxValues + cbArray[i].value + "+";
	}
	
	if (checkBoxValues.length > 0) checkBoxValues = checkBoxValues.substring(0,checkBoxValues.length-1);
	
	return checkBoxValues;
}

/* -----------------------------------------------------------
MKC front page slide show
-------------------------------------------------------------- */

function mkiSlideShowInit (containerId, imgUrlArray, fadeDuration, pauseDuration) {
	
	// container must have a "position" property other than "static"
	var e = getElement(containerId);
	var eW = e.offsetWidth;
	var eH = e.offsetHeight;
	
	var d;
	var img;
	var imgArray = new Array();
	
	// create a new div for each image in imgArray
	for (var i=0; i<imgUrlArray.length; i++) {	
		// load image into browser memory
		imgArray[i] = new Image();
		imgArray[i].src = imgUrlArray[i];
		
		// create a div for each image
		d = document.createElement("div");
		d.setAttribute('id',containerId + 'Slide-' + i);
		// alert ("Creating element " + d.getAttribute('id'));
		d.style.backgroundImage = "url(" + imgUrlArray[i] + ")";
		// might be just "background"
		d.style.width = eW + 'px';
		d.style.height = eH + 'px';
		d.style.zIndex = '0';
		d.style.position = 'absolute';
		d.style.top = '0px';
		d.style.left = '0px';
		d.style.opacity = '0';
		d.style.filter  = "alpha(opacity=0)";
		e.appendChild(d);
	} // for
	
	// make first slide visible
	d = getElement(containerId + 'Slide-0');
	d.style.zIndex = '1';
	mkiSlideShowSetOpacity (d, 1);

	if (fadeDuration < 1000) fadeDuration = 1000;
	var fadeInterval = fadeDuration / 10;
	
	// set slideshow in motion
	// window.setTimeout(function () { mkiSlideShowPlay(containerId,0,imgUrlArray.length,fadeInterval,pauseDuration); }, pauseDuration);

	// setTimeout("mkiSlideShowPlay('" + containerId + "', 0, " + imgUrlArray.length + ", " + fadeDuration + ", " + pauseDuration + ")",pauseDuration);
	
} // mkiSlideShowInit

function mkiSlideShowPlay (containerId, currentSlideIndex, slideCount, fadeInterval, pauseDuration) {
	alert ("Slide show is playing");
	// calculate next slide index
	var s = currentSlideIndex + 1;
	if (s > slideCount) s = 0;
	
	// identify current and next slides
	var currentSlide = getElement(containerId + 'Slide-' + currentSlideIndex);
	var nextSlide = getElement(containerId + 'Slide-' + s);

	// bring next slide to front, and current slide to back
	// next slide is still invisible
	currentSlide.style.zIndex = '1';
	nextSlide.style.zIndex = '2';
	
	// fade-in the next slide after waiting for pauseDuration
	var t = function () { mkiSlideShowFadeInCallBack(currentSlide,nextSlide,0,fadeInterval); }
	// window.setTimeout(t, pauseDuration);
	
	// window.setTimeOut ("mkiSlideShowFadeIn ('" + nextSlide.getAttribute('id') + "'," + fadeDuration + ")", pauseDuration);
	
} // mkiSlideShowPlay


function mkiSlideShowFadeInCallBack (currentSlide, nextSlide, nextOpacityAsDecimal, interval) {
	// increase opacity by 10%
	var o = nextOpacityAsDecimal + 0.1;
	mkiSlideShowSetOpacity (nextSlide, o);
	
	// if opacity has not yet reached 1.0, increment it again
	if (o < 1) {		
		window.setTimeout(function () { mkiSlideShowFadeInCallBack(currentSlide, nextSlide, o, interval); }, interval);
	}
	// otherwise, fade-in is complete, so move previous slide back to layer 0
	else {
		currentSlide.style.zIndex = '0';
		nextSlide.style.zIndex = '1';	
	}
}

function mkiSlideShowSetOpacity (e, opacityAsDecimal) {
	if (opacityAsDecimal < 0) opacityAsDecimal = 0;
	if (opacityAsDecimal > 1) opacityAsDecimal = 1;
	
	var opacityAsInt = opacityAsDecimal * 100;
	if (opacityAsInt < 1) opacityAsInt = 1; // IE7 bug, text smoothing cuts out if 0
	if (opacityAsInt > 100) opacityAsInt = 100;
	
	e.style.opacity = opacityAsDecimal;
	e.style.filter  = "alpha(opacity=" + opacityAsInt + ")";
	alert ("Setting opacity of " + e.getAttribute('id') + " to " + opacityAsDecimal);
}

function gradiate(elementId, color) {
	var e = getElement(elementId);
	var eW = e.offsetWidth;
	var eH = e.offsetHeight;
	
	if (eW < 100) {
		// create eW x 1px divs
		var opacityInterval = 100 / eW;
		for (var i=0; i<eW; i++) {
			newDiv = document.createElement("DIV");
			newDiv.style.background = color;
			newDiv.style.width = '1px';
			newDiv.style.height = eH + 'px';
			newDiv.style.cssFloat = 'left';
			newDiv.style.styleFloat = 'left';
			
			opacityAsInt = Math.round (i * opacityInterval);
			if (opacityAsInt < 1) opacityAsInt = 1; // IE7 bug, text smoothing cuts out if 0
			if (opacityAsInt > 100) opacityAsInt = 100;
			opacityAsDecimal = opacityAsInt / 100;
			
			newDiv.style.opacity = opacityAsDecimal;
			newDiv.style.filter  = "alpha(opacity=" + opacityAsInt + ")";
			
			e.appendChild(newDiv);
		}
	}
	else {
		alert ("The gradiate function does not create gradients wider than 100 pixels");
	}
}

/* -----------------------------------------------------------
MKC infoLinks
-------------------------------------------------------------- */

addEvent(window, "load", infoLinkInit);

function infoLinkInit() {
	// find all anchors whose name is "infoLink"
	if (!document.getElementsByTagName) return;

	var myAnchors, myAnchor, myDivId, myDiv, myLinkType, myLinkName;

	myAnchors = document.getElementsByTagName("a");
	for (i=0; i<myAnchors.length; i++) {
		myAnchor = myAnchors[i];
		myLinkType = myAnchor.getAttribute("infoLinkTypeID");
		myLinkId = myAnchor.getAttribute("id");
		if (myLinkType) {

			// check for the presence of a hidden tooltip div
			// that will contain the relatedinfo for this link
			myDivId = "tooltip_" + myLinkId;
			myDiv = document.getElementById(myDivId);

			// if it doesn't exist, create it
			if (!myDiv) {
				// create a div for each image
				myDiv = document.createElement("div");
				myDiv.setAttribute('id',myDivId);
				// myDiv.setAttribute('class','tooltip');
				myDiv.className = 'tooltip';
				document.getElementsByTagName("body")[0].appendChild(myDiv);
			}

			// load the innerHtml of the div with the content
			getAjaxPage('/InfoLinkAjax.aspx?t=' + myLinkType + '&id=' + myLinkId, myDivId);

		}
	}
}

var prevTooltip;

function getWindowWidth() {
    
    if(window.innerWidth) {
        return window.innerWidth;
    } 
    
    return document.body.clientWidth;
}

function mouseX(e) {

    if(e.pageX) {
        return e.pageX;
    }
    return e.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
}

function mouseY(e) {
   
   if(e.pageY) {
        return e.pageY;
    } 
    return e.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);    
}

function mkiInfoLink (e) {

	oLink = e.target;
	if (! oLink) oLink = e.srcElement;
	if (! oLink) {
		alert ("Could not identify source of event " + e.type);
		return;
	}

	myLinkId = oLink.getAttribute("id");
	myDivId = "tooltip_" + myLinkId;
	o = document.getElementById(myDivId);

	if (! o) {
		alert ("Could not find a tooltip div with id " + myDivId);
		return;
	}
	
	// if there's a different tooltip being displayed, hide it
	if(prevTooltip && prevTooltip != o) {
		prevTooltip.style.visibility = 'hidden';
	}
	
	// if event is mouseover, don't move the
	// tooltip if it is already visible
	if (e.type == "click" && o.style.visibility != 'visible') {

		var windowWidth = getWindowWidth();

		if(o.offsetWidth) {
			ew = o.offsetWidth;
		} else if(o.clip.width) {
			ew = o.clip.width;
		}
	
		y = mouseY(e) + 16;
		x = mouseX(e) - (ew / 4);
		
		if (x < 2) {
			x = 2;
		} else if(x + ew > windowWidth) {
			x = windowWidth - ew - 4;
		}
		
		o.style.left = x + 'px';
		o.style.top = y + 'px';    
		
		o.style.visibility = 'visible';
		
		prevTooltip = o;
	}
}
	
/* -----------------------------------------------------------
MKC ajax functions
-------------------------------------------------------------- */

var bustcachevar=1 //bust potential caching of external pages after initial request? (1=yes, 0=no)
var loadedobjects=""
var rootdomain="http://"+window.location.hostname
var bustcacheparameter=""

function getAjaxString(url) {
	var ajaxRequest = buildAjaxRequest();
	
	if (ajaxRequest) {
		ajaxRequest.open("GET", url, false);                             
		ajaxRequest.send(null);
		return ajaxRequest.responseText;                                         
	} 
	else {
		return false;
	}
}

function getAjaxPage (url, containerid) {
	var ajaxRequest = buildAjaxRequest();
	if (ajaxRequest) {
		ajaxRequest.onreadystatechange=function() {
			loadpage(ajaxRequest, containerid)
		}
		if (bustcachevar) //if bust caching of external page
			bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
		
		ajaxRequest.open('GET', url+bustcacheparameter, true)
		ajaxRequest.send(null)
	}
}

function sendAjaxForm (url, urlEncodedData) {
	var ajaxRequest = buildAjaxRequest();
	
	if (ajaxRequest) {
		ajaxRequest.open("POST", url, true);                             
		ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		ajaxRequest.send(urlEncodedData);
		return ajaxRequest.responseText;                                         
	} 
	else {
		return false;
	}

}

function buildAjaxRequest () {
	var ajaxRequest = false;
	if (window.XMLHttpRequest)           
		ajaxRequest=new XMLHttpRequest();              
	else
		ajaxRequest=new ActiveXObject("Microsoft.XMLHTTP");
	return ajaxRequest;
}


function loadpage(ajaxRequest, containerid) {
	if (ajaxRequest.readyState == 4 && (ajaxRequest.status==200 || window.location.href.indexOf("http")==-1))
	document.getElementById(containerid).innerHTML=ajaxRequest.responseText
}

function loadobjs(){
	if (!document.getElementById) return;
	for (i=0; i<arguments.length; i++) {
		var file=arguments[i];
		var fileref="";
		if (loadedobjects.indexOf(file)==-1) { 
			//Check to see if this object has not already been added to page before proceeding
			if (file.indexOf(".js")!=-1) { //If object is a js file
				fileref=document.createElement('script');
				fileref.setAttribute("type","text/javascript");
				fileref.setAttribute("src", file);
			}
			else if (file.indexOf(".css")!=-1) { //If object is a css file
				fileref=document.createElement("link");
				fileref.setAttribute("rel", "stylesheet");
				fileref.setAttribute("type", "text/css");
				fileref.setAttribute("href", file);
			}
		}
		if (fileref!="") {
			document.getElementsByTagName("head").item(0).appendChild(fileref);
			loadedobjects+=file+" "; //Remember this object as being already added to page
		}
	}
}

