﻿//
//	util.js
//		General purpose scripts
//

//  These are browser detection variables  Use across functions needing browser types  //

var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false
var isFirefox = (navigator.userAgent.indexOf("Firefox") != -1) ? true : false
var isSafari = (navigator.userAgent.indexOf("Safari") != -1) ? true : false
var divCount = 0;

//used for debug/troubleshooting browser type
function displayBrowserDetection()
{
    console.log('Browser Detection: ');
    console.log('IE: '+isIE);
    console.log('Opera: '+isOpera);
    console.log('Firefox: '+isFirefox);
    console.log('Safari: '+isSafari);
}

function openImg(pth)
{
	if (pth != "")
		window.open(pth, "Image", "toolbar=no,status=no,scrollbars=1");
}

function popUp(strURL,strType,strHeight,strWidth)
{
	var strOptions="";
	if (strType=="console") strOptions="resizable,height="+strHeight+",width="+strWidth;
	if (strType=="scrollconsole") strOptions="resizable,scrollbars,height="+strHeight+",width="+strWidth;
	if (strType=="fixed") strOptions="status,height="+strHeight+",width="+strWidth;
	if (strType=="elastic") strOptions="toolbar,menubar,scrollbars,resizable,location,height="+strHeight+",width="+strWidth;
	window.open(strURL, 'newWin', strOptions);
}

// Returns true if specified key is in specified array
function inArray(arr, key)
{
 	for (var i = 0; i < arr.length; i++)
 	{
 		if (arr[i] == key)
 		{
 			return true;
 		}
 	}
 	return false;
}

// Function taLimit is used for the Key Press event for the text box or text
// area : When a key is pressed this function checks if the total number of
// characters typed equals the limit given by the property maxLength for the
// field. If the limit is reached then it return false thus not allowing any
// further key press event.
function taLimit(taObj, maxLength)
{
	//alert("name='" + taObj.name + "'\nvalue='" + taObj.value + "'\nlength=" + taObj.value.length + "\nmaxlength=" + maxLength)


 	//check if exceeded:
  if (taObj.value.length >= maxLength*1)
 	{
 		if (!event || !event.keyCode)
 		{
 			return false;
 		}

 		// check if key pressed was arrow, backspace or such
 		var allowedChars = new Array(8, 9, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46);
 		return inArray(allowedChars, event.keyCode);
 	}
}

// Function taCount is used for the Key Up event : We use this to change the
// value of the counter displayed and to truncate the excess characters if any
// (example if someone has cut and pasted the value into the field when we have
// allowed paste). To disable paste add the property onpaste="return false" to
// the field. We use the inner text property of the span element to change the
// counter displayed.
function taCount(taObj, visID, maxLength)
{
  if (taObj.value.length > maxLength * 1)
  {
    taObj.value = taObj.value.substring(0, maxLength * 1);
  }

  var visCnt = document.getElementById(visID);
  if (visCnt)
  {
    visCnt.innerText = maxLength - taObj.value.length; // IE
    visCnt.innerHTML = maxLength - taObj.value.length; // FireFox
  }
}



/********************************************************************
 * You may use this code for free on any web page provided that     *
 * these comment lines and the following credit remain in the code. *
 * Keep In View (c) JavaScript-FX. (www.javascript-fx.com)          *
 ********************************************************************/
 function JSFX_KeepInView(id, container_id)
 {
  var getPageY = function(el){return(el==null)?0:el.offsetTop+getPageY(el.offsetParent);};
  var getScrollTop = function(){return document.body.scrollTop||document.documentElement.scrollTop};

  var el = document.getElementById(id);
  if (el==null) return;

  if (el.style.position == "absolute")
  {
    el.startPageTop = -el.offsetTop;
    el.currentX = el.offsetLeft;
    el.currentY = el.offsetTop;
    document.getElementById('MapColumn').style.height = el.offsetTop;
  }
  else
  {
    el.style.position = "relative";
    el.startPageTop = getPageY(el);
    el.currentX = el.currentY=0;
    document.getElementById('MapColumn').style.height = el.offsetTop;
  }

  el.floatInView=function(){
    var padding = 10
    var scrollTop = getScrollTop()
	  var targetY = 0
	  if (scrollTop > this.startPageTop - padding)
	  {
	    targetY = scrollTop - (this.startPageTop - padding);
	  }
	  this.currentY += (targetY - this.currentY) / 4;
	  this.style.top = this.currentY+"px";
	  document.getElementById(container_id).style.height = this.currentY+"px";
	  };

  setInterval('document.getElementById("' + id + '").floatInView()', 40);
};

function addListener(a,b,c,d)
{
  if (a.addEventListener)
  {
    a.addEventListener(b,c,d);
    return true;
  }
  else if (a.attachEvent)
  {
    var e = a.attachEvent("on"+b,c);
    return e;
  }
  else
  {
    alert("Handler could not be attached");
  }
}

// Find position of an element.
// http://www.quirksmode.org/js/findpos.html
// The while loop uses one =, and is not an == bug.
// It's recursively assigning the parent, to walk up the dom until null.
function findPos(obj)
{
  var curleft = curtop = 0;
  if (obj.offsetParent)
  {
    curleft = obj.offsetLeft;
    curtop = obj.offsetTop;
    while (obj = obj.offsetParent)
    {
      curleft += obj.offsetLeft;
      curtop += obj.offsetTop;
    }
  }
  return [curleft, curtop];
}

// Reference to document body, depending on compatibility mode.
// From image trail script.
function truebody()
{
  return (!window.opera && document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

// clears out the default text from an element and resets the style to
// normal for input
function clearDefault(id, defaulttext)
{
  var el = document.getElementById(id);
	if (defaulttext == el.value) el.value = ""
	if (el.style)
  {
	  el.style.fontStyle = "normal";
    el.style.color = "#333333";
	}
}

// sets an element back to default text and "help" style if we don't have
// any content
function recallDefault(id, defaulttext)
{
  var el = document.getElementById(id);
  if (el.value == "")
  {
    el.value = defaulttext;
  }

  if (el.value == defaulttext)
  {
	  if (el.style)
    {
	    el.style.fontStyle = "italic";
	    el.style.color = "#888888";
	  }
  }
}

function setAllCheckBoxes(FormName, FieldName, CheckValue)
{
  if(!document.forms[FormName])
    return;
  var objCheckBoxes = document.forms[FormName].elements[FieldName];
  if(!objCheckBoxes)
    return;
  var countCheckBoxes = objCheckBoxes.length;
  if(!countCheckBoxes)
    objCheckBoxes.checked = CheckValue;
  else
    // set the check value for all check boxes
    for(var i = 0; i < countCheckBoxes; i++)
      objCheckBoxes[i].checked = CheckValue;
}

////////////////////////////////////
//  The following code contains routines commonly used to track mouse movement
//  on the pages.  These are used for positioning of overlay pop-ups (ajax).
////////////////////////////////////

    var MouseX = 0, MouseY = 0;
    var PageHeight = 0;
    var offX = 22;
    var offY = -30;

    // Main function to retrieve mouse x-y pos.s
    function getMouseXY(e) {
      // Detect if the browser is IE or not.
      // If it is not IE, we assume that the browser is NS.
      var IE = document.all?true:false;

      // Temporary variables to hold mouse x-y pos.s
      var tempX = 0;
      var tempY = 0;

      if (IE) { // grab the x-y pos.s if browser is IE
        tempX = event.clientX + document.body.scrollLeft;
        tempY = event.clientY + document.body.scrollTop;
      } else {  // grab the x-y pos.s if browser is NS
        tempX = e.pageX;
        tempY = e.pageY;
      }
      // catch possible negative values in NS4
      if (tempX < 0){tempX = 0}
      if (tempY < 0){tempY = 0}
      // show the position values in the form named Show
      // in the text fields named MouseX and MouseY
      MouseX = tempX + offX;
      MouseY = tempY + offY;
      return true;
    }

    function getMouseX()
    {
        return MouseX;
    }

    function getMouseY()
    {
        return MouseY;
    }

    function bindMouseMove()
    {
      // Detect if the browser is IE or not.
      // If it is not IE, we assume that the browser is NS.
      var IE = document.all?true:false;

      // If NS -- that is, !IE -- then set up for mouse capture
      if (!IE) document.addEventListener("mousemove", getMouseXY, false);
      else document.onmousemove = getMouseXY;
    }

    // function hides the overlay popups
    function doHide()
    {
      var div = document.getElementById('OverlayContent');
      div.style.display = "none";
      var div2 = document.getElementById('OverlayDiv');
      div2.style.display = "none";
    }

    // this function resizes the overlayDiv to full page height, so the lightbox
    // shadow covers the whole page and not just a portion of it
    function fullsizeOverlay()
    {

        var div = document.getElementById('OverlayDiv');
        new Effect.Appear('OverlayDiv', { to: 0.5, duration: 0.1 });

        var winwidth= window.innerWidth-15;
        var winheight= document.body.scrollHeight+55;

        if(isIE)
        {
          winheight = document.body.scrollHeight;
          winwidth = document.body.clientWidth;
        }

        //var strvar = 'winheight: '+winheight+' winwidth: '+winwidth;
        //alert(strvar);

        div.style.left='0px';
        div.style.width=winwidth+'px';

        div.style.top='0px';
        div.style.height=winheight+'px';

        positionOverlay();
    }

    function fixOverlayWidth()
    {

        var div = document.getElementById('OverlayContent');
        var od = document.getElementById('overlayWidth');
        od.style.float = 'left';
        var ow = od.offsetWidth;
        var oh = od.offsetHeight;
        od.style.float = 'none';

        if(ow > 0 && ow < 750)
        {
          var newidth = ow+'px';
        }
        else
        {
          var newidth = '750px';
        }

        var newheight = oh+'px';

        new Effect.Morph('OverlayContent', {
          style: 'width: '+newidth, // CSS Properties
          duration: 0.2 // Core Effect properties
        });

        new Effect.Morph('OverlayContent', {
          style: 'height: '+newheight, // CSS Properties
          duration: 0.2 // Core Effect properties
        });

        div.style.height = 'auto';
        setTimeout("$('OverlayContent').style.overflow = 'visible';", 350);
    }

    function fixFaqSize()
    {
        var od = document.getElementById('overlayWidth');
        var oh = od.offsetHeight;
        var newheight = oh+'px';

        new Effect.Morph('OverlayContent', {
          style: 'height: '+newheight, // CSS Properties
          duration: 0.5 // Core Effect properties
        });
        setTimeout("$('OverlayContent').style.overflow = 'visible';", 350);
    }

////////////////////////////////////
//  The following code is for displaying and positioning the help pop-ups
//
////////////////////////////////////

    function showHelp(id)
    {
      var div = $(id);
      var cdiv = $('OverlayHelp');
      var pid = 'pointer'+id;
      var pointer = '<img src="/images/help-up.png" class="HelpPointer" id="'+pid+'" />';
      cdiv.innerHTML = div.innerHTML+pointer;
      doPositionHelp('OverlayHelp', pid);
    }

    function hideHelp(id)
    {
      $('OverlayHelp').style.display = 'none';
    }

    function doPositionHelp(id, pid)
    {
        var div = document.getElementById(id);
        var pin = document.getElementById(pid);

        var offsetfromcursorX=-35; //Customize x offset of tooltip
        var offsetfromcursorY=0; //Customize y offset of tooltip

        var curX=MouseX;
        var curY=MouseY;

        div.style.display = "block";

        //Find out how close the mouse is to the corner of the window
        var winwidth= window.innerWidth-15;
        var winheight= window.innerHeight-15;

        var divheight = div.offsetHeight;
        var divwidth = div.offsetWidth;

        if(isIE)
        {
          var fullheight = document.body.clientHeight;
          var offScroll = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
          winheight = fullheight - offScroll;
          winwidth = document.body.clientWidth;
          offsetfromcursorY = offScroll;
        }

        var strvar = 'winheight: '+winheight+' winwidth: '+winwidth+' divheight: '+divheight+' divwidth: '+divwidth+' MouseX: '+MouseX+' MouseY: '+MouseY;
        //alert(strvar);
        var xPos = (curX+offsetfromcursorX);
        if(xPos < 0) { xPos = 5; }
        div.style.left=xPos+'px';

        if((curY-divheight+offsetfromcursorY)<0)
        {
          div.style.top = "5px";
          pin.style.display = "none";

        }
        else
        {
          div.style.top=curY-divheight+offsetfromcursorY+"px";
        }
    }

    function positionOverlay()
    {
        var div = document.getElementById('OverlayContent');

        var offsetfromcursorY=60; //Customize y offset of tooltip
        var curY=MouseY;

        //Find out how close the mouse is to the corner of the window
        var winheight= window.innerHeight-15;
        var divheight = div.offsetHeight;
        var offScroll = window.pageYOffset;

        if(isIE)
        {
          var fullheight = document.body.clientHeight;
          offScroll = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
          winheight = fullheight - offScroll;
        }

        var strvar = 'winheight: '+winheight+' divheight: '+divheight+' MouseY: '+MouseY;
        //alert(strvar);

        if((curY-divheight+offsetfromcursorY)<0)
        {
          div.style.top = "15px";
        }
        else
        {
          div.style.top=(offScroll+offsetfromcursorY)+"px";
        }

        //this prepares the content div for growth in fixOverlayWidth()
        div.style.overflow = 'hidden';
        div.style.width = '0px';
        div.style.height = '0px';
        div.style.display = 'block';

        setTimeout('fixOverlayWidth()', 200);
    }

    function NewImageResize(filename)
    {
      var div = document.getElementById('OverlayContent');
      var picDiv = document.getElementById('PhotoShow');
      var pic = document.getElementById('viewPhoto');

      div.style.overflow = 'hidden';
      picDiv.style.overflow = 'hidden';
      pic.style.display = 'block';
      setTimeout('fixOverlayWidth()', 100);
    }

/*

CUSTOM FORM ELEMENTS

Created by Ryan Fait
www.ryanfait.com

The only thing you need to change in this file is the following
variables: checkboxHeight, radioHeight and selectWidth.

Replace the first two numbers with the height of the checkbox and
radio button. The actual height of both the checkbox and radio
images should be 4 times the height of these two variables. The
selectWidth value should be the width of your select list image.

You may need to adjust your images a bit if there is a slight
vertical movement during the different stages of the button
activation.

Visit http://ryanfait.com/ for more information.

*/

var checkboxHeight = "25";
var radioHeight = "25";
var selectWidth = "190";

/* No need to change anything after this */

document.write('<style type="text/css">input.styled { display: none; } select.styled { position: relative; width: ' + selectWidth + 'px; opacity: 0; filter: alpha(opacity=0); z-index: 5; }</style>');

var Custom = {
	init: function() {
		var inputs = document.getElementsByTagName("input"), span = Array(), textnode, option, active;
		for(a = 0; a < inputs.length; a++) {
			if((inputs[a].type == "checkbox" || inputs[a].type == "radio") && inputs[a].className == "styled") {
				span[a] = document.createElement("span");
				span[a].className = inputs[a].type;

				if(inputs[a].checked == true) {
					if(inputs[a].type == "checkbox") {
						position = "0 -" + (checkboxHeight*2) + "px";
						span[a].style.backgroundPosition = position;
					} else {
						position = "0 -" + (radioHeight*2) + "px";
						span[a].style.backgroundPosition = position;
					}
				}
				span[a].style.marginLeft = "-20px";
				inputs[a].parentNode.insertBefore(span[a], inputs[a]);
				inputs[a].onchange = Custom.clear;
				span[a].onmousedown = Custom.pushed;
				span[a].onmouseup = Custom.check;
				document.onmouseup = Custom.clear;
			}
		}
		inputs = document.getElementsByTagName("select");
		for(a = 0; a < inputs.length; a++) {
			if(inputs[a].className == "styled") {
				option = inputs[a].getElementsByTagName("option");
				active = option[0].childNodes[0].nodeValue;
				textnode = document.createTextNode(active);
				for(b = 0; b < option.length; b++) {
					if(option[b].selected == true) {
						textnode = document.createTextNode(option[b].childNodes[0].nodeValue);
					}
				}
				span[a] = document.createElement("span");
				span[a].className = "select";
				span[a].id = "select" + inputs[a].name;
				span[a].appendChild(textnode);
				inputs[a].parentNode.insertBefore(span[a], inputs[a]);
				inputs[a].onchange = Custom.choose;
			}
		}
	},
	pushed: function() {
		element = this.nextSibling;
		if(element.checked == true && element.type == "checkbox") {
			this.style.backgroundPosition = "0 -" + checkboxHeight*3 + "px";
		} else if(element.checked == true && element.type == "radio") {
			this.style.backgroundPosition = "0 -" + radioHeight*3 + "px";
		} else if(element.checked != true && element.type == "checkbox") {
			this.style.backgroundPosition = "0 -" + checkboxHeight + "px";
		} else {
			this.style.backgroundPosition = "0 -" + radioHeight + "px";
		}
	},
	check: function() {
		element = this.nextSibling;
		if(element.checked == true && element.type == "checkbox") {
			this.style.backgroundPosition = "0 0";
			element.checked = false;
		} else {
			if(element.type == "checkbox") {
				this.style.backgroundPosition = "0 -" + checkboxHeight*2 + "px";
			} else {
				this.style.backgroundPosition = "0 -" + radioHeight*2 + "px";
				group = this.nextSibling.name;
				inputs = document.getElementsByTagName("input");
				for(a = 0; a < inputs.length; a++) {
					if(inputs[a].name == group && inputs[a] != this.nextSibling) {
						inputs[a].previousSibling.style.backgroundPosition = "0 0";
					}
				}
			}
			element.checked = true;
		}
	},
	clear: function() {
		inputs = document.getElementsByTagName("input");
		for(var b = 0; b < inputs.length; b++) {
			if(inputs[b].type == "checkbox" && inputs[b].checked == true && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 -" + checkboxHeight*2 + "px";
			} else if(inputs[b].type == "checkbox" && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 0";
			} else if(inputs[b].type == "radio" && inputs[b].checked == true && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 -" + radioHeight*2 + "px";
			} else if(inputs[b].type == "radio" && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 0";
			}
		}
	},
	choose: function() {
		option = this.getElementsByTagName("option");
		for(d = 0; d < option.length; d++) {
			if(option[d].selected == true) {
				document.getElementById("select" + this.name).childNodes[0].nodeValue = option[d].childNodes[0].nodeValue;
			}
		}
	}
}
window.onload = Custom.init;

function getDivCount()
{
  var cnt = document.getElementsByTagName('div').length;
  return cnt+5000;
}

function setZindex(id)
{
  if(divCount==0) { divCount = getDivCount(); }
  ++divCount;
  var div = $(id);
  div.style.zIndex = divCount;
}

function fixZindex()  { }


////////////////////////////////////
// This is used for the show/hide functionality used in the
// quicklinks menu and other places around the site.
// the "+" "-" images need be surrounded by an a tag with an ID of XXX_img
// id is the ID of the div being shown/hidden
// EX:
// <a id="SUBID_img" href="#" onClick="javascript:switchQLSub('SUBID', false);"> + </a>
////////////////////////////////////

var menuStatus = new Array();

function switchQLSub(id, status)
{
  if(menuStatus[id]==undefined)
  {
    //if we don't have a saved status already, set it to the default one
    menuStatus[id] = status;
  }

  var img = id + '_img';

  if(menuStatus[id]==false)
  {
    new Effect.BlindDown(id, {});
    $(img).innerHTML = '<img src=\"/images/icons/ql-minus.gif\" alt=\"-\" title=\"-\">';

    menuStatus[id] = true;
  }
  else
  {
    new Effect.BlindUp(id, {});
    $(img).innerHTML = '<img src=\"/images/icons/ql-plus.gif\" alt=\"+\" title=\"+\">';
    menuStatus[id] = false;
  }
}
