var alreadySubmitted = false;
function addVisit(f)
{
  if(f.visit.value=="") 
    alert("You must select a date/time for this visit"); 
  else
  {
    if(!alreadySubmitted)
    {
      alreadySubmitted = true;
      f.submit();
    }
  }
}

function alertuser(string,redirect)
{
  if(confirm(string))
    location.replace(redirect);
}

function insertRTE(editor,text)
{
  parent.tinyMCE.execInstanceCommand(editor,"mceInsertContent",false,text);
}

function changeText(div,text,concat)
{
  div.innerHTML = div.innerHTML + text;
}

function popWindow(winlink, width, height){
        portWindow = window.open(winlink, "popWin", "location=1,scrollbars=1,resizable=1,width=" + width + ",height=" + height)
        portWindow.focus()
}

function nav(u) { document.location.href = u; }

function hideLayer(whichLayer)
{
  whichLayer.display = 'none';
}
function showLayer(whichLayer)
{
  whichLayer.display = '';
}
function isVisible(whichLayer)
{
  return whichLayer.display!='none';
}
function toggleLayer(whichLayer)
{
  if(isVisible(whichLayer)) hideLayer(whichLayer); else showLayer(whichLayer);
}
function fillLayer(whichLayer,content,fetch)
{
  whichLayer = getLayer(whichLayer);

  content = getE(content);

  if(!isVisible(whichLayer))
  {
    if(content.innerHTML=="")
    {
      // fetch content
      content.innerHTML = getAjaxResponse(fetch);
    }
  }

  toggleLayer(whichLayer);
}
function getE(whichLayer)
{
  if( document.getElementById ) // this is the way the standards work
    elem = document.getElementById( whichLayer );
  else if( document.all ) // this is the way old msie versions work
    elem = document.all[whichLayer];
  else if( document.layers ) // this is the way nn4 works
    elem = document.layers[whichLayer];
}
function getLayer(whichLayer)
{
  return (getE(whichLayer)).style;
}

//********************************
//* AJAX functions
//* By Stephen Rusin
//********************************
function GetXmlHttpObject()
{
  var xh = null;
  try
  {
    // Firefox, Opera 8.0+, Safari
    xh = new XMLHttpRequest();
  }
  catch (e)
  {
    // Internet Explorer
    try
    {
      xh = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e)
    {
      xh = new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
  return xh;
}

function getAjaxResponse(url)
{
  var xmlHttp = GetXmlHttpObject()
  if(xmlHttp==null)
  {
    alert ("Your browser does not support AJAX! You won't be able to properly view this site!");
    return;
  }
  xmlHttp.open('GET',url+'&sid='+(new Date()).getTime(),false);
  xmlHttp.send(null);
  if(xmlHttp.status == 200)
    return xmlHttp.responseText;
}

function getE(element) { return document.getElementById(element); }

function addCustomer(key)
{
  var ret = false;

  var resp = getAjaxResponse('index.php?section=customers&subsection=add&key='+key);

  if(resp=="OK")
    ret = true;
  else
    dropDownMessage(resp,4000);
  
  return ret;
}

function dropDownMessage(text,delay)
{
  if(typeof dropinboxv2=="undefined")
    dropinboxv2 = getE("dropinboxv2");
  dropinboxv2.innerHTML = '<p align="right" style="z-index: -100; margin: 0px 0px 5px 0px; background: #63865C; background-image: url(\'images/gradient.jpg\'); background-repeat: repeat-x; padding: 2px 3px 2px 0px;"><a href="#" onClick="dismissboxv2();return false" style="padding: 0px; margin: 51px 0px 0px 0px; background: transparent;"><img src=images/close.png border=0></a></p><p align="center" style="margin: 25px 10px 0px 10px;">' + text + '</p>';
  initboxv2(delay);
}

// some icons from Freeiconsweb

/***********************************************
* Amazon style Drop-in content box- * Visit DynamicDrive.com for hundreds of DHTML scripts
* This notice must stay intact for legal use
* Go to http://www.dynamicdrive.com/ for full source code
***********************************************/

var dropboxleft=0 //set left position of box (in px)
var dropboxtop=0 //set top position of box (in px)
var dropspeed=30 //set speed of drop animation (larger=faster)

//1) "always"- This makes the fade-in box load each time the page is displayed
//2) "oncepersession"- This uses cookies to display the fade-in box only once per browser session
//3) integer (ie: 5)- Finally, you can specify an integer to display the box randomly via a frequency of 1/integer...
// For example, 2 would display the box about (1/2) 50% of the time the page loads.

//var displaymode="always"

///Don't edit beyond here///////////

//if (parseInt(displaymode)!=NaN)
//var random_num=Math.floor(Math.random()*displaymode)
var ie=document.all
var dom=document.getElementById

function initboxv2(delay)
{
  if(window.liftstart) clearInterval(liftstart);
  if(window.dismissstart) clearInterval(dismissstart);
  if (!dom&&!ie)
    return
  crossboxcover=(dom)?document.getElementById("dropinboxv2cover") : document.all.dropinboxv2cover
  crossbox=(dom)?document.getElementById("dropinboxv2"): document.all.dropinboxv2
  scroll_top=(ie)? truebody().scrollTop : window.pageYOffset
  crossbox.height=crossbox.offsetHeight
  crossboxcover.style.height=parseInt(crossbox.height)+"px"
  crossbox.style.top=crossbox.height*(-1)+"px"
  crossboxcover.style.left=dropboxleft+"px"
  crossboxcover.style.top=dropboxtop+"px"
  crossboxcover.style.visibility=(dom||ie)? "visible" : "show"
  dropstart=setInterval("dropinv2()",50)
  dismissstart=setInterval("dismissboxv2()",delay);
}

function dropinv2()
{
  scroll_top=(ie)? truebody().scrollTop : window.pageYOffset
  if (parseInt(crossbox.style.top)<0)
  {
    crossboxcover.style.top=scroll_top+dropboxtop+"px"
    crossbox.style.top=parseInt(crossbox.style.top)+dropspeed+"px"
  }
  else
  {
    clearInterval(dropstart)
    crossbox.style.top=0
  }
}

function dropoutv2()
{
  scroll_top=(ie)? truebody().scrollTop : window.pageYOffset
  if (parseInt(crossbox.style.top) > -1*parseInt(crossbox.height) )
  {
    crossboxcover.style.top = scroll_top - dropboxtop + "px"
    crossbox.style.top = parseInt(crossbox.style.top) - dropspeed + "px"
  }
  else
  {
    clearInterval(liftstart)
    clearInterval(dismissstart)
    crossboxcover.style.visibility="hidden"
  }
}

function dismissboxv2()
{
  if (window.dropstart) clearInterval(dropstart)
  if (window.liftstart) clearInterval(liftstart)
  liftstart=setInterval("dropoutv2()",50)
}

function truebody()
{
  return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}


/***********************************************
* Drop Down/ Overlapping Content- 
* This notice must stay intact for legal use.
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/
//Drop Down/ Overlapping Content: http://www.dynamicdrive.com
//Last updated: Dec 19th, 07': Added ability to dynamically populate a Drop Down content using an external file (Ajax feature)

var dropdowncontent={
 delaybeforehide: 2000, //set delay in milliseconds before content box disappears onMouseout (1000=1 sec)
	disableanchorlink: true, //when user clicks on anchor link, should it be disabled?
	ajaxloadingmsg: "Loading content. Please wait...", //HTML to show while ajax page is being feched
	ajaxbustcache: true, //Bust cache when fetching pages?

	getposOffset:function(what, offsettype){
		return (what.offsetParent)? what[offsettype]+this.getposOffset(what.offsetParent, offsettype) : what[offsettype]
	},

	isContained:function(m, e){
		var e=window.event || e
		var c=e.relatedTarget || ((e.type=="mouseover")? e.fromElement : e.toElement)
		while (c && c!=m)try {c=c.parentNode} catch(e){c=m}
		if (c==m)
			return true
		else
			return false
	},

	show:function(anchorobj, subobj, e){
		if (!this.isContained(anchorobj, e)){
			var horizontaloffset=(subobj.dropposition[0]=="left")? -(subobj.offsetWidth-anchorobj.offsetWidth) : 0 //calculate user added horizontal offset
			var verticaloffset=(subobj.dropposition[1]=="top")? -subobj.offsetHeight : anchorobj.offsetHeight //calculate user added vertical offset
			subobj.style.left=this.getposOffset(anchorobj, "offsetLeft") + horizontaloffset + "px"
			subobj.style.top=this.getposOffset(anchorobj, "offsetTop")+verticaloffset+"px"
			subobj.style.clip=(subobj.dropposition[1]=="top")? "rect(auto auto auto 0)" : "rect(0 auto 0 0)" //hide drop down box initially via clipping
			subobj.style.visibility="visible"
			subobj.startTime=new Date().getTime()
			subobj.contentheight=parseInt(subobj.offsetHeight)
			if (typeof window["hidetimer_"+subobj.id]!="undefined") //clear timer that hides drop down box?
				clearTimeout(window["hidetimer_"+subobj.id])
			this.slideengine(subobj, (subobj.dropposition[1]=="top")? "up" : "down")
		}
	},

	curveincrement:function(percent){
		return (1-Math.cos(percent*Math.PI)) / 2 //return cos curve based value from a percentage input
	},

	slideengine:function(obj, direction){
		var elapsed=new Date().getTime()-obj.startTime //get time animation has run
		if (elapsed<obj.glidetime){ //if time run is less than specified length
			var distancepercent=(direction=="down")? this.curveincrement(elapsed/obj.glidetime) : 1-this.curveincrement(elapsed/obj.glidetime)
			var currentclip=(distancepercent*obj.contentheight)+"px"
			obj.style.clip=(direction=="down")? "rect(0 auto "+currentclip+" 0)" : "rect("+currentclip+" auto auto 0)"
			window["glidetimer_"+obj.id]=setTimeout(function(){dropdowncontent.slideengine(obj, direction)}, 10)
		}
		else{ //if animation finished
			obj.style.clip="rect(0 auto auto 0)"
		}
	},

	hide:function(activeobj, subobj, e){
		if (!dropdowncontent.isContained(activeobj, e)){
			window["hidetimer_"+subobj.id]=setTimeout(function(){
				subobj.style.visibility="hidden"
				subobj.style.left=subobj.style.top=0
				clearTimeout(window["glidetimer_"+subobj.id])
			}, subobj.hidedelay)
//			}, dropdowncontent.delaybeforehide)
		}
	},

	ajaxconnect:function(pageurl, divId){
		var page_request = false
		var bustcacheparameter=""
		if (window.XMLHttpRequest) // if Mozilla, IE7, Safari etc
			page_request = new XMLHttpRequest()
		else if (window.ActiveXObject){ // if IE6 or below
			try {
			page_request = new ActiveXObject("Msxml2.XMLHTTP")
			} 
			catch (e){
				try{
				page_request = new ActiveXObject("Microsoft.XMLHTTP")
				}
				catch (e){}
			}
		}
		else
			return false
		document.getElementById(divId).innerHTML=this.ajaxloadingmsg //Display "fetching page message"
		page_request.onreadystatechange=function(){dropdowncontent.loadpage(page_request, divId)}
		if (this.ajaxbustcache) //if bust caching of external page
			bustcacheparameter=(pageurl.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
		page_request.open('GET', pageurl+bustcacheparameter, true)
		page_request.send(null)
	},

	loadpage:function(page_request, divId){
		if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)){
			document.getElementById(divId).innerHTML=page_request.responseText
		}
	},

 init:function(anchorid, pos, glidetime, hidedelay){
		var anchorobj=document.getElementById(anchorid)
		var subobj=document.getElementById(anchorobj.getAttribute("rel"))
		var subobjsource=anchorobj.getAttribute("rev")
		if (subobjsource!=null && subobjsource!="")
			this.ajaxconnect(subobjsource, anchorobj.getAttribute("rel"))
		subobj.dropposition=pos.split("-")
		subobj.glidetime=glidetime || 1000
                subobj.hidedelay = hidedelay;
		subobj.style.left=subobj.style.top=0
		anchorobj.onmouseover=function(e){dropdowncontent.show(this, subobj, e)}
		anchorobj.onmouseout=function(e){dropdowncontent.hide(subobj, subobj, e)}
		if (this.disableanchorlink) anchorobj.onclick=function(){return false}
		subobj.onmouseout=function(e){dropdowncontent.hide(this, subobj, e)}
	}
}

//*****************************
//* CALENDAR
//*****************************
// This function gets called when the end-user clicks on some date.
function selected(cal, date) {
  cal.sel.value = date; // just update the date in the input field.
  if (cal.dateClicked && (cal.sel.id == "sel1" || cal.sel.id == "sel3"))
    // if we add this call we close the calendar on single-click.
    // just to exemplify both cases, we are using this only for the 1st
    // and the 3rd field, while 2nd and 4th will still require double-click.
    cal.callCloseHandler();
}

// And this gets called when the end-user clicks on the _selected_ date,
// or clicks on the "Close" button.  It just hides the calendar without
// destroying it.
function closeHandler(cal) {
  cal.hide();                        // hide the calendar
//  cal.destroy();
  _dynarch_popupCalendar = null;
}

// This function shows the calendar under the element having the given id.
// It takes care of catching "mousedown" signals on document and hiding the
// calendar if the click was outside.
function showCalendar(id, format, showsTime, showsOtherMonths) {
  var el = document.getElementById(id);
  if (_dynarch_popupCalendar != null) {
    // we already have some calendar created
    _dynarch_popupCalendar.hide();                 // so we hide it first.
  } else {
    // first-time call, create the calendar.
    var cal = new Calendar(1, null, selected, closeHandler);
    // uncomment the following line to hide the week numbers
    // cal.weekNumbers = false;
    if (typeof showsTime == "string") {
      cal.showsTime = true;
      cal.time24 = (showsTime == "24");
    }
    if (showsOtherMonths) {
      cal.showsOtherMonths = true;
    }
    _dynarch_popupCalendar = cal;                  // remember it in the global var
    cal.setRange(1900, 2070);        // min/max year allowed.
    cal.create();
  }
  _dynarch_popupCalendar.setDateFormat(format);    // set the specified date format
  _dynarch_popupCalendar.parseDate(el.value);      // try to parse the text in field
  _dynarch_popupCalendar.sel = el;                 // inform it what input field we use

  // the reference element that we pass to showAtElement is the button that
  // triggers the calendar.  In this example we align the calendar bottom-right
  // to the button.
  _dynarch_popupCalendar.showAtElement(el.nextSibling, "Br");        // show the calendar

  return false;
}

// If this handler returns true then the "date" given as
// parameter will be disabled.  In this example we enable
// only days within a range of 10 days from the current
// date.
// You can use the functions date.getFullYear() -- returns the year
// as 4 digit number, date.getMonth() -- returns the month as 0..11,
// and date.getDate() -- returns the date of the month as 1..31, to
// make heavy calculations here.  However, beware that this function
// should be very fast, as it is called for each day in a month when
// the calendar is (re)constructed.
function isDisabled(date) {
  var today = new Date();
  return date.getTime() > today.getTime();
}

function flatSelected(cal, date) 
{
  var d = cal.date;
  document.f.visit.value = d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate()+" "+d.getHours()+":"+d.getMinutes()+":00";
}

function dateChanged(calendar) 
{
    // Beware that this function is called even if the end-user only
    // changed the month/year.  In order to determine if a date was
    // clicked you can use the dateClicked property of the calendar:
    if (calendar.dateClicked) {
      // OK, a date was clicked, redirect to /yyyy/mm/dd/index.php
      var y = calendar.date.getFullYear();
      var m = calendar.date.getMonth();     // integer, 0..11
      var d = calendar.date.getDate();      // integer, 1..31
    }
}

function showFlatCalendar() {
  var parent = document.getElementById("calendar-container");

  // construct a calendar giving only the "selected" handler.
  var cal = new Calendar(0, null, flatSelected);

  // hide week numbers & show 12 hour time
  cal.weekNumbers = false;
  cal.showsTime = true;
  cal.time24 = false;

  // We want some dates to be disabled; see function isDisabled above
  cal.setDisabledHandler(isDisabled);
  cal.setDateFormat("%A, %B %e");

  // this call must be the last as it might use data initialized above; if
  // we specify a parent, as opposite to the "showCalendar" function above,
  // then we create a flat calendar -- not popup.  Hidden, though, but...
  cal.create(parent);

  // ... we can show it here.
  cal.show();
}


/***********************************************
* Image w/ description tooltip- By Dynamic Web Coding (www.dyn-web.com)
* Copyright 2002-2007 by Sharon Paine
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

/* IMPORTANT: Put script after tooltip div or 
	 put tooltip div just before </BODY>. */

var dom = (document.getElementById) ? true : false;
var ns5 = (!document.all && dom || window.opera) ? true: false;
var ie5 = ((navigator.userAgent.indexOf("MSIE")>-1) && dom) ? true : false;
var ie4 = (document.all && !dom) ? true : false;
var nodyn = (!ns5 && !ie4 && !ie5 && !dom) ? true : false;

var origWidth, origHeight;

// avoid error of passing event object in older browsers
if (nodyn) { event = "nope" }

///////////////////////  CUSTOMIZE HERE   ////////////////////
// settings for tooltip 
// Do you want tip to move when mouse moves over link?
var tipFollowMouse= true;	
// Be sure to set tipWidth wide enough for widest image
var tipWidth= 210;
var offX= 20;	// how far from mouse to show tip
var offY= 12; 
var tipFontFamily= "Verdana, arial, helvetica, sans-serif";
var tipFontSize= "8pt";
// set default text color and background color for tooltip here
// individual tooltips can have their own (set in messages arrays)
// but don't have to
var tipFontColor= "#000000";
var tipBgColor= "#ECDCBB"; 
var tipBorderColor= "#000080";
var tipBorderWidth= 2;
var tipBorderStyle= "ridge";
var tipPadding= 4;

// tooltip content goes here (image, description, optional bgColor, optional textcolor)
//var messages = new Array();
// multi-dimensional arrays containing: 
// image and text for tooltip
// optional: bgColor and color to be sent to tooltip
//messages[0] = new Array('red_balloon.gif','Here is a red balloon on a white background',"#FFFFFF");
//messages[1] = new Array('duck2.gif','Here is a duck on a light blue background.',"#DDECFF");
//messages[2] = new Array('test.gif','Test description','black','white');

////////////////////  END OF CUSTOMIZATION AREA  ///////////////////

// preload images that are to appear in tooltip
// from arrays above
/*
if (document.images) {
	var theImgs = new Array();
	for (var i=0; i<messages.length; i++) {
  	theImgs[i] = new Image();
		theImgs[i].src = messages[i][0];
  }
}
*/

// to layout image and text, 2-row table, image centered in top cell
// these go in var tip in doTooltip function
// startStr goes before image, midStr goes between image and text
var startStr = '<table width="' + tipWidth + '"><tr><td align="center" width="100%"><img src="';
var midStr = '" border="0"></td></tr><tr><td valign="top">';
var endStr = '</td></tr></table>';

////////////////////////////////////////////////////////////
//  initTip	- initialization for tooltip.
//		Global variables for tooltip. 
//		Set styles
//		Set up mousemove capture if tipFollowMouse set true.
////////////////////////////////////////////////////////////
var tooltip, tipcss;
function initTip() {
	if (nodyn) return;
	tooltip = (ie4)? document.all['tipDiv']: (ie5||ns5)? document.getElementById('tipDiv'): null;
	tipcss = tooltip.style;
	if (ie4||ie5||ns5) {	// ns4 would lose all this on rewrites
		tipcss.width = tipWidth+"px";
		tipcss.fontFamily = tipFontFamily;
		tipcss.fontSize = tipFontSize;
		tipcss.color = tipFontColor;
		tipcss.backgroundColor = tipBgColor;
		tipcss.borderColor = tipBorderColor;
		tipcss.borderWidth = tipBorderWidth+"px";
		tipcss.padding = tipPadding+"px";
		tipcss.borderStyle = tipBorderStyle;
	}
	if (tooltip&&tipFollowMouse) {
		document.onmousemove = trackMouse;
	}
  setInterval("hideTip()",1000);
}

var divX, divY, divW, divH;
function setDivCoords(div)
{
  e = getE(div);
  divX = e.offsetLeft;
  divY = e.offsetTop;
  divW = e.offsetWidth;
  divH = e.offsetHeight;
}

function IsMouseOverDiv()
{
  if( (mouseX>divX && mouseX<divX+divW) && (mouseY>divY && mouseY<divY+divH) ) 
    return true; 
  return false;
}

/////////////////////////////////////////////////
//  doTooltip function
//			Assembles content for tooltip and writes 
//			it to tipDiv
/////////////////////////////////////////////////
var t1,t2;	// for setTimeouts
var tipOn = false;	// check if over tooltip link
function doTooltip(evt,evtimg,evtstr) {
	if (!tooltip) return;
	if (t1) clearTimeout(t1);	if (t2) clearTimeout(t2);
	tipOn = true;
	// set colors if included in messages array
        curBgColor = tipBgColor;
        curFontColor = tipFontColor;
	if (ie4||ie5||ns5) {
		var tip = startStr + evtimg + midStr + '<span style="font-family:' + tipFontFamily + '; font-size:' + tipFontSize + '; color:' + curFontColor + ';">' + evtstr + '</span>' + endStr;
		tipcss.backgroundColor = curBgColor;
	 	tooltip.innerHTML = tip;
	}
	if (!tipFollowMouse) positionTip(evt);
	else t1=setTimeout("tipcss.visibility='visible'",100);
}

var mouseX, mouseY;
function trackMouse(evt) {
	standardbody=(document.compatMode=="CSS1Compat")? document.documentElement : document.body //create reference to common "body" across doctypes
	mouseX = (ns5)? evt.pageX: window.event.clientX + standardbody.scrollLeft;
	mouseY = (ns5)? evt.pageY: window.event.clientY + standardbody.scrollTop;
	if (tipOn) positionTip(evt);
}

/////////////////////////////////////////////////////////////
//  positionTip function
//		If tipFollowMouse set false, so trackMouse function
//		not being used, get position of mouseover event.
//		Calculations use mouseover event position, 
//		offset amounts and tooltip width to position
//		tooltip within window.
/////////////////////////////////////////////////////////////
function positionTip(evt) {
	if (!tipFollowMouse) {
		standardbody=(document.compatMode=="CSS1Compat")? document.documentElement : document.body
		mouseX = (ns5)? evt.pageX: window.event.clientX + standardbody.scrollLeft;
		mouseY = (ns5)? evt.pageY: window.event.clientY + standardbody.scrollTop;
	}
	// tooltip width and height
	var tpWd = (ie4||ie5)? tooltip.clientWidth: tooltip.offsetWidth;
	var tpHt = (ie4||ie5)? tooltip.clientHeight: tooltip.offsetHeight;
	// document area in view (subtract scrollbar width for ns)
	var winWd = (ns5)? window.innerWidth-20+window.pageXOffset: standardbody.clientWidth+standardbody.scrollLeft;
	var winHt = (ns5)? window.innerHeight-20+window.pageYOffset: standardbody.clientHeight+standardbody.scrollTop;
	// check mouse position against tip and window dimensions
	// and position the tooltip 
	if ((mouseX+offX+tpWd)>winWd) 
		tipcss.left = mouseX-(tpWd+offX)+"px";
	else tipcss.left = mouseX+offX+"px";
	if ((mouseY+offY+tpHt)>winHt) 
		tipcss.top = winHt-(tpHt+offY)+"px";
	else tipcss.top = mouseY+offY+"px";
	if (!tipFollowMouse) t1=setTimeout("tipcss.visibility='visible'",100);
}


function hideTip() {
  if(IsMouseOverDiv()) return;
  if(!tooltip) return;
  t2=setTimeout("tipcss.visibility='hidden'",10);
  tipOn = false;
}


