//----------------------------[ Utility Functions ]----------------------------

// ::: qs

	/*
	* Utilities for working with asynchronous javascripts
	*/

	var async_jscript = null;

	function exec_js(script, parameters, onload_callback)
	{

		if(!document)
			return false;
		if(!document.body)
			return false;

		if(async_jscript != null)
		{
			document.body.removeChild(async_jscript);
		}

		async_jscript = document.createElement("SCRIPT");

		async_jscript.onload = function() { eval(onload_callback); };

		async_jscript.onreadystatechange = function () { if(/loaded|complete/.test(this.readyState)) eval(onload_callback); };

		async_jscript.src = script + "?" + "rnd=" + Math.random(99999999) + "&" + parameters;

		document.body.appendChild(async_jscript);

		return true;
	}
	
// :::

	function show_props(obj, name)
	{
	 		 var result="";
			 var count=0;
			 for( i in obj )
			 {
			  	  result += name + "." + i + " = " + obj[i] + "\n";
				  
				  if( count++ > 20 )
				  {
				   	  alert(result);
					  count=0;
					  result="";
			      }
			 }
		  	 alert(result);
	}

	function show_frames(obj)
	{
		var result="";
		var count=0;

		for (var i=0;i<parent.frames.length;i++)
                {
			result += "Frame = " + parent.frames[i].name + "\n" ;

			if( count++ > 20 )
			{
                                          alert(result);
                                          count=0;
                                          result="";
			}
                }

		alert(result);

	}

	function statusbar_message(txt, timeout) {
		   window.status = txt;
		   setTimeout("clear_statusbar()",timeout);
	}

	function clear_statusbar() {
	   window.status="";
	}

/*	function frame_exists(what) 
	{
		for (var i=0;i<parent.frames.length;i++) 
		{
		if (parent.frames[i].name == what)
			return true;
		}
		return false;
	}
*/
	
        function frame_exists(what)
        {
                for (var i=0;i<top.frames.length;i++)
                {
	                if (top.frames[i].name == what)
	                        return true;

			if (top.frames[i].frames.length > 0 )
			{
				if( child_frame_exists(top.frames[i], what) == 1 )
					return true;
			}
                }
                return false;
        }

	function child_frame_exists(frame, what)
	{
//		alert("Checking Frame: " + frame + " for " + what );

		for (var i=0;i<frame.frames.length;i++)
                {
                        if (frame.frames[i].name == what)
                                return 1;

			//
			// If this frame has child frames then check them!
			//
                        if (frame.frames[i].frames.length > 0 )
                        {
                                if( child_frame_exists(frame.frames[i], what) == 1 )
                                        return 1;
                        }
                }

		return 0;
	}

        function variable_exists(what)
        {
//              alert( "Checking if variable [ " + what + " ] exists" );
                if ( eval("window." + what) )
                {
//                        alert("variable " + what + " exists");
                        return true;
                }
                else
                {
//                        alert("variable " + what + " doesnt exist");
                        return false;
                }
        }


     function getCurrentDate()
	 {
	  		  var dateStr;
	  		  currentTime = new Date();
			  
			  //
			  // Netscape stores the year since 1900
			  //
	  		  if( isIE() == true )
			  			  dateStr = currentTime.getDate() + "/" + (currentTime.getMonth()+1) + "/" + currentTime.getYear();
			  else
			  			  dateStr = currentTime.getDate() + "/" + (currentTime.getMonth()+1) + "/" + (currentTime.getYear()+1900);
			  
//			  alert("DAY: " + currentTime.getDate() + "\nMONTH: " + (currentTime.getMonth()+1) + "\nYEAR: " + currentTime.getYear() );
			  
			  return dateStr;  
	 }
	 
	 function getCurrentDateOffset(offset_day, offset_month, offset_year)
	 {
	  		  var dateStr = "NULL";
	  		  currentTime = new Date();
			  var year = currentTime.getYear() + offset_year;
			  var month = (currentTime.getMonth()+1) + offset_month; 
			  var day = currentTime.getDate() + offset_day;		  
			  
	  		  if( isIE() != true )
			  	  year+=1900;

			  if( year < 0 ) year = 0;
			  			  
			  if( month <= 0 )
			  { 
			  	  month += 12;
				  year--;
			  }
			  
			  if( month > 12 )
			  {
			   	  month-=12;
				  year++;
			  }
			  
		  	  switch( month )
		  	  {
				  case 1:
				  case 3:
				  case 5:
				  case 7:
				  case 8:
				  case 10:
				  case 12:
				  	   if( day <= 0 )
					   {
					   	   day+=31;
						   month --;
					   }
					   
					   if( day > 31 )
					   {
					        day-=31;
							month++;
					   }
					
					   break;
				  case 2:
				       if( day <= 0)
					   {
				  	   	   day+=28;
						   month --;
					   }
					   
					   if( day > 28 )
					   {
					       day-=28;
						   month++;
					   }
					   break;
				  case 4:
				  case 6:
				  case 9:
				  case 11:
				       if( day <= 0)
					   {
				  	   	   day+=30;
						   month --;
					   }
					   
					   if( day > 30 )
					   {
					       day-=30;
						   month++;
					   }
					   break			  	 
		      }			  
	   
			  dateStr = day + "/" + month + "/" + year;
			  return dateStr;
	 }
	 
	 function sendmail( address )
	 {
		   		   document.location = "mailto:" + address;
	 }	 
	 
	 function isIE()
	 {
//Your browser is Microsoft Internet Explorer
//Your browser version is 4.0 (compatible; MSIE 5.5; Windows NT 5.0; Supplied by blueyonder)
//Browser version number is 4
//Your browser code name is Mozilla
//Your user agent is Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0; Supplied by blueyonder)
//Your browser supports JavaScript version 1.3	 
 
	  	  //-- Putting browser info into global variables in the head of a page
	  	  //-- gives access to those variables to all scripts within the page.
		  var browserName = navigator.appName
		  var browserVersion = navigator.appVersion
		  var browserVersionNum = parseFloat(browserVersion)
		  var codeName=navigator.appCodeName
		  var userAgent=navigator.userAgent
		  
		  if (checkIt(userAgent.toLowerCase(),'msie') || checkIt(browserName.toLowerCase(),'microsoft') )
		  {
		   	 return true;		  
		  } 
		  
		  return false;
	 }  
	 
	 function checkIt(detect, string)
	 {
	  place = detect.indexOf(string) + 1;
	  
//	  alert("Searching For: [" + string + "] in [ " + detect + " ] - indexof = " + place );
	  
	  thestring = string;
	  return place;
	 }
	 



          function getRootDomainName(url)
          {
                                 var name = new String( url );
				 var protocol = "https://";

                                 name = name.toLowerCase();

                                 // 
				 // Try and find the https:// start protocol tag
				 //
                                 pos = name.indexOf(protocol);

				 //
				 // Could we find the protocol start tag?
				 //
                                 if( pos == -1 )
				 {
					//
					// Set the protocol to http
					//
					protocol = "http://";
					pos = name.indexOf(protocol);
				 }

				//
				// Dont know what the protocol is - return error
				//
				 if( pos == -1 )
					return "unknown";

                                 start_pos = pos + protocol.length;

                                 // Find the end char
                                 pos = name.indexOf("/",start_pos+1);

                                 if( pos == -1 )
                                         end_pos = name.length;
                                 else
                                 {
                                 	//
                                 	// Check to see if the url has a "~" if it does then that part of
                                 	// the domain/root node [ www.xyz.com/~spickett ] would be the root.
                                 	//
                                 	pos2 = name.indexOf("~",pos);
                                 	if( pos2 == -1 )                                 
	                                 	end_pos = pos;
	                                else
	                                {
	                                	// include the ~ element
	                                	pos2 = name.indexOf("/",pos+1);
	                                	
	                                	if( pos2 == -1 )
	                                		end_pos = name.length;
	                                	else
	                                		end_pos = pos2;
	                                
	                                }
                                 }

                                 // Grab the domain name
                                 var name = new String( url );
                                 domain = name.substr(start_pos,end_pos-start_pos);

                               alert("domain = " + domain + " - start = " + start_pos + " -  end = " + end_pos);

                                 return domain;
          }

	 function loadJavascriptFile(file)
	 {
//		alert( "<SCRIPT LANGUAGE=\"JavaScript1.2\" SRC=\""+file+"\"><\/SCRIPT>" );
//		alert( "Document Loaction: " + document.location );

//	 	file = "https://" + getRootDomainName(document.location) + "/javascript/" + file;
		file = getProtocol(document.location) +  "://" + getRootDomainName(document.location) + "/javascript/" + file;
//		alert(file);
		document.write("<SCRIPT LANGUAGE=\"JavaScript1.2\" SRC=\""+file+"\"><\/SCRIPT>");
	 }

	function disableMouseRightClick()
	{
//		document.writeln("<script language=\"javascript\">");
		document.writeln("function noRightClick() {");
		document.writeln("if (event.button==2) {");
		document.writeln("alert('You can NOT Right-Click on this page -- HTML Source Code Is Protected.');");
		document.writeln("}");
		document.writeln("}");
		document.writeln("document.onmousedown=noRightClick");
//		document.writeln("</script>");
	}

        //
        // This function return sthe protocol of the URL (i.e. HTTP, HTTPS, FTP, etc...
        //
        function getProtocol(domain_url)
        {  
                var url = new String( domain_url );
                var pos = url.indexOf(":",1);

                if( pos == -1 )
                        return "unknown";

                var name = new String( url );
                var domain = name.substr(0,pos);

                return domain;

        }



         //
         // NOTE: This function *must* be the same as the one defined in [ utils.js ]
         //
         function getRootDomainName(url)
         {
                                 var name = new String( url );
                                 name = name.toUpperCase();

                                 // Find the start char
                                pos = name.indexOf("HTTPS://");

                                if( pos == -1 )
                                        pos = name.indexOf("HTTP://");

                                if( pos == -1 )
                                        pos = name.indexOf("FTP://");

                                 if( pos == -1 )
                                         return "unknown";

                                 start_pos = pos + getProtocol(url).length + 3;

                                 // Find the end char
                                 pos = name.indexOf("/",start_pos+1);

                                 if( pos == -1 )
                                         end_pos = name.length;
                                 else
                                 {
                                        //
                                        // Check to see if the url has a "~" if it does then that part of
                                        // the domain/root node [ www.xyz.com/~spickett ] would be the root.
                                        //
                                        pos2 = name.indexOf("~",pos);
                                        if( pos2 == -1 )
                                                end_pos = pos;
                                        else
                                        {
                                                // include the ~ element
                                                pos2 = name.indexOf("/",pos+1);

                                                if( pos2 == -1 )
                                                        end_pos = name.length;
                                                else
                                                        end_pos = pos2;

                                        }
                                 }

                                 // Grab the domain name
                                 var name = new String( url );
                                 domain = name.substr(start_pos,end_pos-start_pos);

//                               alert("domain = " + domain + " - start = " + start_pos + " -  end = " + end_pos);

                                 return domain;
          }


         function random(max_val)
          {
                  // Generate a unique session ID [32 bit value]
                  var generatornum=Math.random();
                  var maxnumber=max_val;
                  var randomnum=Math.round(generatornum*maxnumber);
                  return randomnum;
          }


        <!-- Original:  Cyanide_7 (leo7278@hotmail.com) -->
        function formatCurrency(num)
        {
                num = num.toString().replace(/\$|\,/g,'');
                if(isNaN(num))
                        num = "0";

                sign = (num == (num = Math.abs(num)));
                num = Math.floor(num*100+0.50000000001);
                cents = num%100;
                num = Math.floor(num/100).toString();
                if(cents<10)
                        cents = "0" + cents;
                for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
                        num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
                return (((sign)?'':'-') + num + '.' + cents);
        }



        function changeBg(color)
        {	
                //sets bg color to new value
                window.document.bgColor= color
        }
        
        function changeText(color)
        {
        	//sets text color to new value
                window.document.fgColor= color
        }
        
        function changeLink(color)
        {	
                //sets link color to new value
                window.document.linkColor= color;
        }
        
        function changeVlink(color)
        {	
                //sets vlink color to new value
                window.document.vlinkColor= color
        }  
        
                

        function open_window( url, width, height)
        {
                        var center_left = (screen.width)/2 - width/2;
                        var center_top =(screen.height)/2 - height/2;
                        var attributes = 'toolbar=0,location=0,left=' + center_left + ',top=' + center_top + ',directories=0,status=0,menubar=0,scrollbars=NO,scrolling=NO,resizable=NO,noresize,width=' + width + ',height=' + height;

                        window.name = 'RESULTS';
                        var winvar = window.open("myWin","TOP",attributes);
                        winvar.location = url; 
                        if (window.focus) {winvar.focus()}
        }

	function open_scroll_window( url, width, height)
        {
                        var center_left = (screen.width)/2 - width/2;
                        var center_top =(screen.height)/2 - height/2;
                        var attributes = 'toolbar=0,location=0,left=' + center_left + ',top=' + center_top + ',directories=0,status=1,menubar=0,scrollbars=YES,scrolling=YES,resizable=YES,width=' + width + ',height=' + height;

                        window.name = 'RESULTS';
                        var winvar = window.open("myWin","TOP",attributes);
                        winvar.location = url; 
                        if (window.focus) {winvar.focus()}
        }

        function goto_map(post_code)
        {
                var url = "http://www.multimap.com/map/browse.cgi?client=public&db=pc&addr1=&client=public&addr2=&advanced=&addr3=&pc=" + post_code + "&quicksearch=" + post_code + "&cidr_client=none";
                open_scroll_window( url, 800, 600 );
        }


//
// Date validation Functionality
//
// Usage: (assumming u have a form called [ myForm ]
//
// <SCRIPT>CreateDateField("myForm", "myDate" );</SCRIPT>
//
// Will create a field called myDate - with day/month/year format!
//
// The date string is formatted as "dd/mm/yyyy".  You can deformat that in
// C as follows:
//	
//	fscanf(date_str, "%d/%d/%d", &d, &m, &y);
//
	var date_arr = new Array;
	date_arr[0]=new Option("January",31);
	date_arr[1]=new Option("February",28);
	date_arr[2]=new Option("March",31);
	date_arr[3]=new Option("April",30);
	date_arr[4]=new Option("May",31);
	date_arr[5]=new Option("June",30);
	date_arr[6]=new Option("July",31);
	date_arr[7]=new Option("August",30);
	date_arr[8]=new Option("September",30);
	date_arr[9]=new Option("October",31);
	date_arr[10]=new Option("November",31);
	date_arr[11]=new Option("December",30);	

	function UpdateDate(form_name, field_name)
	{
			var seperator = "/";

			//
			// Update the days in month
			//
			UpdateDaysInMonth(form_name, field_name);

			 var day_selected_index = eval("document." + form_name + ".day_" + field_name + ".selectedIndex");
			 var day =  eval("document." + form_name + ".day_" + field_name + "[" + day_selected_index + "].text" );
		 
			 var month_selected_index = eval("document." + form_name + ".month_" + field_name + ".selectedIndex");
//			 var month =  eval("document." + form_name + ".month_" + field_name + "[" + month_selected_index + "].text" );
			 var month = month_selected_index+1;

			 var year_selected_index = eval("document." + form_name + ".year_" + field_name + ".selectedIndex");
			 var year =  eval("document." + form_name + ".year_" + field_name + "[" + year_selected_index + "].text" );

			 var string_date = day + seperator + month + seperator + year;	
			 eval("document." + form_name + "." + field_name + ".value=\"" + string_date + "\"");	 
	}

	var Gl_month=0;

	function UpdateDaysInMonth(form_name, field_name)
	{
		var month_selected_index = eval("document." + form_name + ".month_" + field_name + ".selectedIndex");

		// Has the month changed?
		if( Gl_month == month_selected_index )
			return; // No change 

		Gl_month = month_selected_index; // Update the current month

		var day_selected_index = eval("document." + form_name + ".day_" + field_name + ".selectedIndex");

                // Populate day field
                var days = parseInt(date_arr[month_selected_index].value);	// Reset the array length

		eval("document." + form_name + ".day_" + field_name + ".options.length=0;");

                for( i=0; i<days; i++ )
                {
                         eval("document." + form_name + ".day_" + field_name + ".options[i]=Option(" + (i+1) + " );");
                }

		if( (days-1) >= day_selected_index )
		{
			eval("document." + form_name + ".day_" + field_name + ".selectedIndex=" + day_selected_index);
		}
	}

	var date = new Date();
	var min_year = date.getYear()-110;
	var max_year = date.getYear();

	function CreateDateField(form_name, field_name)
	{
	 		CreateDateFieldStyle(form_name, field_name, ""); 
	}
	
	function CreateDateFieldStyle(form_name, field_name, style)
	{
		CreateDateFieldStyleDefault(form_name, field_name, style, -1, -1, -1);
	}


	function CreateDateFieldStyleDefault(form_name, field_name, style, day, month, year)
	{
		var date = new Date();

		document.writeln("<INPUT type=hidden value='' name='" + field_name + "'>");
		
		//
		// Now create the date fields
		//
 		document.writeln("<TABLE border=0> <TR>");
 		document.writeln("<TD> <SELECT name='month_" + field_name + "' onChange='UpdateDate(\"" + form_name + "\", \"" + field_name + "\");' class='" + style + "'></SELECT> <TD>");
		document.writeln("<TD> <SELECT name='day_" + field_name + "' onChange='UpdateDate(\"" + form_name + "\", \"" + field_name + "\");'  class='" + style + "'></SELECT> </TD>");
 		document.writeln("<TD> <SELECT name='year_" + field_name + "' onChange='UpdateDate(\"" + form_name + "\", \"" + field_name + "\");'  class='" + style + "'></SELECT> </TD>");
 		document.writeln("</TR></TABLE>");

		//
		// Populate month field
		//
		for( i in date_arr )
		{
		 	 eval("document." + form_name + ".month_" + field_name + ".options[i]=Option(date_arr[i].text );");
		}

		if( month == -1 )
		{
			eval("document." + form_name + ".month_" + field_name + ".selectedIndex=" + date.getMonth());
			Gl_month = date.getMonth();
		}
		else
		{
			eval("document." + form_name + ".month_" + field_name + ".selectedIndex=" + (month-1));
			Gl_month = (month-1);
		}

		//
		// Populate day field
		//
//		var days = parseInt(date_arr[date.getMonth()].value);
		var days = parseInt(date_arr[Gl_month].value);

//alert("There are " + days + " in month " + Gl_month );
		 
		for( i=0; i<days; i++ )
		{
		 	 eval("document." + form_name + ".day_" + field_name + ".options[i]=Option(" + (i+1) + " );");
		}

		if( day == -1 )
			eval("document." + form_name + ".day_" + field_name + ".selectedIndex=" + (date.getDate()-1));
		else
			eval("document." + form_name + ".day_" + field_name + ".selectedIndex=" + (day-1) );
		
		//
		// Populate the year
		//
		for( i=0; i<=max_year-min_year; i++ )
		{
		 	 eval("document." + form_name + ".year_" + field_name + ".options[i]=Option(" + (i+min_year) + " );");
		}

		if( year == -1 )
		{
			if( min_year <= date.getYear() && max_year >= date.getYear() )
			    	eval("document." + form_name + ".year_" + field_name + ".selectedIndex=" + (date.getYear()-min_year));
		}
		else
		{
			if( min_year <= year && max_year >= year )
                                eval("document." + form_name + ".year_" + field_name + ".selectedIndex=" + (year-min_year));
			else
				alert("Date Range Error");
		}
				
		UpdateDate(form_name, field_name);
	}


	function variableExists(objToTest) {
		if (null == objToTest) {
			return false;
		}
		if ("undefined" == typeof(objToTest) ) {
			return false;
		}
		return true;

	}


        //
        // This function will search for the specified IFRAME and will return an
        // object reference that allows JavaScripts to be invoked within that
        // page
        //
        function getScriptFrame(iframe_name)
        {
		var frame;
                frame = recursiveFrameSearch( iframe_name, top.frames[0] )
		if (typeof frame != "undefined")
		{
			frame = recursiveFrameSearch( iframe_name, top.frames );
		}

		return frame;
		
        }

        //
        // This function will search for the specified frame object - and if found
        // will return it.
        //
        function getFrame(iframe_name)
        {
                if( top.frames.length == 0 )
                {
                        if( top.frames.name == iframe_name )
                                return top;

                        return null;
                }

                try
                {
                        if( top.frames[iframe_name] != null )
                                return top.frames[iframe_name];

                } catch( e )
                {
                        // Do nothing
                }

                var frame_object = recursiveFrameSearch( iframe_name, top.frames[0] );
                if( frame_object != null )
                {
                        //
                        // We need the correct object
                        //
                        return frame_object.parent.document.getElementById(iframe_name);
                }

                return frame_object;
        }

        function recursiveFrameSearch( iframe_name, frames )
        {
//alert(frames.name);
                //
                // Check to see if the current frame is the frame we are looking
                // for.
                //
                if( frames.name == iframe_name )
                {
//alert("Match Found: " + frames.name );
                        return frames;
                }
//alert(frames.name + " != " + iframe_name );
//alert( frames.name );
//alert( "Length: " + frames.length);
		if( typeof(frames[iframe_name]) != "undefined" )
		{
			return frames[iframe_name];
		}
		if( typeof(frames["MainFrame"]) != "undefined" )
		{
			if(typeof(frames["MainFrame"][iframe_name]) != "undefined" )
			{
				return frames["MainFrame"][iframe_name];
			}
		}
                //
                // Are there any more child frames?
                //
                if( frames.length == 0 )
                        return null;

                //
                // Check to see if this frame has any child frames.  If it does then
                // recursively visit each of these child frames and search for the
                // requested frame.
                //
                var max_frames = frames.length;
                var loop=0;
//show_props(frames.frame[0], "frames.frame[0]");
                while(loop<max_frames)
                {
//                      alert("Searching For Frame Match [" + iframe_name + "] = [" + frames[loop].name + "]");
                        frame_object = recursiveFrameSearch( iframe_name, frames[loop] );

                        //
                        // If the frame object is not null then we have a match!
                        //
                        if( frame_object != null )
                        {
                                return frame_object;
                        }
                        loop++;
                }
//alert(loop + " !< " + max_frames );
                return null;
        }



function getFrameObject( iframe_name)
{

        if( document.getElementById(iframe_name) != null )
        {
                return document.getElementById(iframe_name);
        }

        if( parent.document.getElementById(iframe_name) != null )
        {
                return parent.document.getElementById(iframe_name);
        }

        if( top.frames['ROOT'].document.getElementById(iframe_name) != null )
        {
                return top.frames['ROOT'].document.getElementById(iframe_name);
        }

        if( top.document.getElementById(iframe_name) != null )
        {
                return top.document.getElementById(iframe_name);
        }

        //
        // Last try to resolve frame.
        //
        return getFrame(iframe_name);
}


//
// n = decimal number (must be a string!!!)
// d = decimal places
//
function formatDecimal(n,d){
	var xx = n.indexOf('.')
	var l = n.length
	var zstr = '0000000000000000000000'
	var theInt = ''
	var theFrac = ''
	var theNo = ''
	rfac = ''
	rfacx = 0
	nx = 0
	var xt = parseInt(d) + 1
	var rstr = '' + zstr.substring(1,xt)
	var rfac = '.' + rstr + '5'
	var rfacx = parseFloat(rfac)
	if (xx == -1 ) 	{    // No fraction
		theFrac = zstr
		theInt = "" + n
	}
	else if (xx == 0) {
		theInt = '0'
		nx = 0 + parseFloat(n) + parseFloat(rfacx)
		n = nx + zstr
		theFrac = '' + n.substring(1, n.length)
	}
	else {
		theInt = n.substring(0,xx)
		nx = parseFloat(n) + rfacx
		n = '' + nx + zstr
		theFrac = '' + n.substring(xx+1,xx + 1 + parseInt(d))
		var astr = 'd = ' + d
	}
	theFrac = theFrac.substring(0,parseInt(d))
	var ii = 0
	theNo = theInt + '.' + theFrac
	return theNo
}


function GetToken( data, seperator, index )
{
	value="";
	pos=0;
	field_no=1;

	for(loop=0; loop<data.length; loop++)
	{
		if( data.charAt(loop) == ":" )
		{
			if( field_no == index )
				return value;

			value="";		
			field_no ++;
			continue;
		}
	
		if( field_no == index )
		{
			value+=data.charAt(loop);			
		}
	}

	if( value != "" )
		return value;
	
	return "NULL"
} 






/**
This is a JavaScript library that will allow you to easily add some basic DHTML
drop-down datepicker functionality to your Notes forms. This script is not as
full-featured as others you may find on the Internet, but it's free, it's easy to
understand, and it's easy to change.

You'll also want to include a stylesheet that makes the datepicker elements
look nice. An example one can be found in the database that this script was
originally released with, at:

http://www.nsftools.com/tips/NotesTips.htm#datepicker

I've tested this lightly with Internet Explorer 6 and Mozilla Firefox. I have no idea
how compatible it is with other browsers.

version 1.5
December 4, 2005
Julian Robichaux -- http://www.nsftools.com

HISTORY
--  version 1.0 (Sept. 4, 2004):
Initial release.

--  version 1.1 (Sept. 5, 2004):
Added capability to define the date format to be used, either globally (using the
defaultDateSeparator and defaultDateFormat variables) or when the displayDatePicker
function is called.

--  version 1.2 (Sept. 7, 2004):
Fixed problem where datepicker x-y coordinates weren't right inside of a table.
Fixed problem where datepicker wouldn't display over selection lists on a page.
Added a call to the datePickerClosed function (if one exists) after the datepicker
is closed, to allow the developer to add their own custom validation after a date
has been chosen. For this to work, you must have a function called datePickerClosed
somewhere on the page, that accepts a field object as a parameter. See the
example in the comments of the updateDateField function for more details.

--  version 1.3 (Sept. 9, 2004)
Fixed problem where adding the <div> and <iFrame> used for displaying the datepicker
was causing problems on IE 6 with global variables that had handles to objects on
the page (I fixed the problem by adding the elements using document.createElement()
and document.body.appendChild() instead of document.body.innerHTML += ...).

--  version 1.4 (Dec. 20, 2004)
Added "targetDateField.focus();" to the updateDateField function (as suggested
by Alan Lepofsky) to avoid a situation where the cursor focus is at the top of the
form after a date has been picked. Added "padding: 0px;" to the dpButton CSS
style, to keep the table from being so wide when displayed in Firefox.

-- version 1.5 (Dec 4, 2005)
Added display=none when datepicker is hidden, to fix problem where cursor is
not visible on input fields that are beneath the date picker. Added additional null
date handling for date errors in Safari when the date is empty. Added additional
error handling for iFrame creation, to avoid reported errors in Opera. Added
onMouseOver event for day cells, to allow color changes when the mouse hovers
over a cell (to make it easier to determine what cell you're over). Added comments
in the style sheet, to make it more clear what the different style elements are for.
*/

var datePickerDivID = "datepicker";
var iFrameDivID = "datepickeriframe";

var dayArrayShort = new Array('Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa');
var dayArrayMed = new Array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
var dayArrayLong = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
var monthArrayShort = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
var monthArrayMed = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec');
var monthArrayLong = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
 
// these variables define the date formatting we're expecting and outputting.
// If you want to use a different format by default, change the defaultDateSeparator
// and defaultDateFormat variables either here or on your HTML page.
var defaultDateSeparator = "/";        // common values would be "/" or "."
var defaultDateFormat = "mdy"    // valid values are "mdy", "dmy", and "ymd"
var dateSeparator = defaultDateSeparator;
var dateFormat = defaultDateFormat;

/**
This is the main function you'll call from the onClick event of a button.
Normally, you'll have something like this on your HTML page:

Start Date: <input name="StartDate">
<input type=button value="select" onclick="displayDatePicker('StartDate');">

That will cause the datepicker to be displayed beneath the StartDate field and
any date that is chosen will update the value of that field. If you'd rather have the
datepicker display beneath the button that was clicked, you can code the button
like this:

<input type=button value="select" onclick="displayDatePicker('StartDate', this);">

So, pretty much, the first argument (dateFieldName) is a string representing the
name of the field that will be modified if the user picks a date, and the second
argument (displayBelowThisObject) is optional and represents an actual node
on the HTML document that the datepicker should be displayed below.

In version 1.1 of this code, the dtFormat and dtSep variables were added, allowing
you to use a specific date format or date separator for a given call to this function.
Normally, you'll just want to set these defaults globally with the defaultDateSeparator
and defaultDateFormat variables, but it doesn't hurt anything to add them as optional
parameters here. An example of use is:

<input type=button value="select" onclick="displayDatePicker('StartDate', false, 'dmy', '.');">

This would display the datepicker beneath the StartDate field (because the
displayBelowThisObject parameter was false), and update the StartDate field with
the chosen value of the datepicker using a date format of dd.mm.yyyy
*/
function displayDatePicker(dateFieldName, displayBelowThisObject, dtFormat, dtSep)
{
  var targetDateField = document.getElementsByName (dateFieldName).item(0);
 
  // if we weren't told what node to display the datepicker beneath, just display it
  // beneath the date field we're updating
  if (!displayBelowThisObject)
    displayBelowThisObject = targetDateField;
 
  // if a date separator character was given, update the dateSeparator variable
  if (dtSep)
    dateSeparator = dtSep;
  else
    dateSeparator = defaultDateSeparator;
 
  // if a date format was given, update the dateFormat variable
  if (dtFormat)
    dateFormat = dtFormat;
  else
    dateFormat = defaultDateFormat;
 
  var x = displayBelowThisObject.offsetLeft;
  var y = displayBelowThisObject.offsetTop + displayBelowThisObject.offsetHeight ;
 
  // deal with elements inside tables and such
  var parent = displayBelowThisObject;
  while (parent.offsetParent) {
    parent = parent.offsetParent;
    x += parent.offsetLeft;
    y += parent.offsetTop ;
  }
 
  drawDatePicker(targetDateField, x, y);
}


/**
Draw the datepicker object (which is just a table with calendar elements) at the
specified x and y coordinates, using the targetDateField object as the input tag
that will ultimately be populated with a date.

This function will normally be called by the displayDatePicker function.
*/
function drawDatePicker(targetDateField, x, y)
{
  var dt = getFieldDate(targetDateField.value );
 
  // the datepicker table will be drawn inside of a <div> with an ID defined by the
  // global datePickerDivID variable. If such a div doesn't yet exist on the HTML
  // document we're working with, add one.
  if (!document.getElementById(datePickerDivID)) {
    // don't use innerHTML to update the body, because it can cause global variables
    // that are currently pointing to objects on the page to have bad references
    //document.body.innerHTML += "<div id='" + datePickerDivID + "' class='dpDiv'></div>";
    var newNode = document.createElement("div");
    newNode.setAttribute("id", datePickerDivID);
    newNode.setAttribute("class", "dpDiv");
    newNode.setAttribute("style", "visibility: hidden;");
    document.body.appendChild(newNode);
  }
 
  // move the datepicker div to the proper x,y coordinate and toggle the visiblity
  var pickerDiv = document.getElementById(datePickerDivID);
  pickerDiv.style.position = "absolute";
  pickerDiv.style.left = x + "px";
  pickerDiv.style.top = y + "px";
  pickerDiv.style.visibility = (pickerDiv.style.visibility == "visible" ? "hidden" : "visible");
  pickerDiv.style.display = (pickerDiv.style.display == "block" ? "none" : "block");
  pickerDiv.style.zIndex = 10000;
 
  // draw the datepicker table
  refreshDatePicker(targetDateField.name, dt.getFullYear(), dt.getMonth(), dt.getDate());
}


/**
This is the function that actually draws the datepicker calendar.
*/
function refreshDatePicker(dateFieldName, year, month, day)
{
  // if no arguments are passed, use today's date; otherwise, month and year
  // are required (if a day is passed, it will be highlighted later)
  var thisDay = new Date();
 
  if ((month >= 0) && (year > 0)) {
    thisDay = new Date(year, month, 1);
  } else {
    day = thisDay.getDate();
    thisDay.setDate(1);
  }
 
  // the calendar will be drawn as a table
  // you can customize the table elements with a global CSS style sheet,
  // or by hardcoding style and formatting elements below
  var crlf = "\r\n";
  var TABLE = "<table cols=7 class='dpTable'>" + crlf;
  var xTABLE = "</table>" + crlf;
  var TR = "<tr class='dpTR'>";
  var TR_title = "<tr class='dpTitleTR'>";
  var TR_days = "<tr class='dpDayTR'>";
  var TR_todaybutton = "<tr class='dpTodayButtonTR'>";
  var xTR = "</tr>" + crlf;
  var TD = "<td class='dpTD' onMouseOut='this.className=\"dpTD\";' onMouseOver=' this.className=\"dpTDHover\";' ";    // leave this tag open, because we'll be adding an onClick event
  var TD_title = "<td colspan=5 class='dpTitleTD'>";
  var TD_buttons = "<td class='dpButtonTD'>";
  var TD_todaybutton = "<td colspan=7 class='dpTodayButtonTD'>";
  var TD_days = "<td class='dpDayTD'>";
  var TD_selected = "<td class='dpDayHighlightTD' onMouseOut='this.className=\"dpDayHighlightTD\";' onMouseOver='this.className=\"dpTDHover\";' ";    // leave this tag open, because we'll be adding an onClick event
  var xTD = "</td>" + crlf;
  var DIV_title = "<div class='dpTitleText'>";
  var DIV_selected = "<div class='dpDayHighlight'>";
  var xDIV = "</div>";
 
  // start generating the code for the calendar table
  var html = TABLE;
 
  // this is the title bar, which displays the month and the buttons to
  // go back to a previous month or forward to the next month
  html += TR_title;
  html += TD_buttons + getButtonCode(dateFieldName, thisDay, -1, "&lt;") + xTD;
  html += TD_title + DIV_title + monthArrayLong[ thisDay.getMonth()] + " " + thisDay.getFullYear() + xDIV + xTD;
  html += TD_buttons + getButtonCode(dateFieldName, thisDay, 1, "&gt;") + xTD;
  html += xTR;
 
  // this is the row that indicates which day of the week we're on
  html += TR_days;
  for(i = 0; i < dayArrayShort.length; i++)
    html += TD_days + dayArrayShort[i] + xTD;
  html += xTR;
 
  // now we'll start populating the table with days of the month
  html += TR;
 
  // first, the leading blanks
  for (i = 0; i < thisDay.getDay(); i++)
    html += TD + "&nbsp;" + xTD;
 
  // now, the days of the month
  do {
    dayNum = thisDay.getDate();
    TD_onclick = " onclick=\"updateDateField('" + dateFieldName + "', '" + getDateString(thisDay) + "');\">";
    
    if (dayNum == day)
      html += TD_selected + TD_onclick + DIV_selected + dayNum + xDIV + xTD;
    else
      html += TD + TD_onclick + dayNum + xTD;
    
    // if this is a Saturday, start a new row
    if (thisDay.getDay() == 6)
      html += xTR + TR;
    
    // increment the day
    thisDay.setDate(thisDay.getDate() + 1);
  } while (thisDay.getDate() > 1)
 
  // fill in any trailing blanks
  if (thisDay.getDay() > 0) {
    for (i = 6; i > thisDay.getDay(); i--)
      html += TD + "&nbsp;" + xTD;
  }
  html += xTR;
 
  // add a button to allow the user to easily return to today, or close the calendar
  var today = new Date();
  var todayString = "Today is " + dayArrayMed[today.getDay()] + ", " + monthArrayMed[ today.getMonth()] + " " + today.getDate();
  html += TR_todaybutton + TD_todaybutton;
  html += "<button class='dpTodayButton' onClick='refreshDatePicker(\"" + dateFieldName + "\");'>this month</button> ";
  html += "<button class='dpTodayButton' onClick='updateDateField(\"" + dateFieldName + "\");'>close</button>";
  html += xTD + xTR;
 
  // and finally, close the table
  html += xTABLE;
 
  document.getElementById(datePickerDivID).innerHTML = html;
  // add an "iFrame shim" to allow the datepicker to display above selection lists
  adjustiFrame();
}


/**
Convenience function for writing the code for the buttons that bring us back or forward
a month.
*/
function getButtonCode(dateFieldName, dateVal, adjust, label)
{
  var newMonth = (dateVal.getMonth () + adjust) % 12;
  var newYear = dateVal.getFullYear() + parseInt((dateVal.getMonth() + adjust) / 12);
  if (newMonth < 0) {
    newMonth += 12;
    newYear += -1;
  }
 
  return "<button class='dpButton' onClick='refreshDatePicker(\"" + dateFieldName + "\", " + newYear + ", " + newMonth + ");'>" + label + "</button>";
}


/**
Convert a JavaScript Date object to a string, based on the dateFormat and dateSeparator
variables at the beginning of this script library.
*/
function getDateString(dateVal)
{
  var dayString = "00" + dateVal.getDate();
  var monthString = "00" + (dateVal.getMonth()+1);
  dayString = dayString.substring(dayString.length - 2);
  monthString = monthString.substring(monthString.length - 2);
 
  switch (dateFormat) {
    case "dmy" :
      return dayString + dateSeparator + monthString + dateSeparator + dateVal.getFullYear();
    case "ymd" :
      return dateVal.getFullYear() + dateSeparator + monthString + dateSeparator + dayString;
    case "mdy" :
    default :
      return monthString + dateSeparator + dayString + dateSeparator + dateVal.getFullYear();
  }
}


/**
Convert a string to a JavaScript Date object.
*/
function getFieldDate(dateString)
{
  var dateVal;
  var dArray;
  var d, m, y;
 
  try {
    dArray = splitDateString(dateString);
    if (dArray) {
      switch (dateFormat) {
        case "dmy" :
          d = parseInt(dArray[0], 10);
          m = parseInt(dArray[1], 10) - 1;
          y = parseInt(dArray[2], 10);
          break;
        case "ymd" :
          d = parseInt(dArray[2], 10);
          m = parseInt(dArray[1], 10) - 1;
          y = parseInt(dArray[0], 10);
          break;
        case "mdy" :
        default :
          d = parseInt(dArray[1], 10);
          m = parseInt(dArray[0], 10) - 1;
          y = parseInt(dArray[2], 10);
          break;
      }
      dateVal = new Date(y, m, d);
    } else if (dateString) {
      dateVal = new Date(dateString);
    } else {
      dateVal = new Date();
    }
  } catch(e) {
    dateVal = new Date();
  }
 
  return dateVal;
}


/**
Try to split a date string into an array of elements, using common date separators.
If the date is split, an array is returned; otherwise, we just return false.
*/
function splitDateString(dateString)
{
  var dArray;
  if (dateString.indexOf("/") >= 0)
    dArray = dateString.split("/");
  else if (dateString.indexOf(".") >= 0)
    dArray = dateString.split(".");
  else if (dateString.indexOf("-") >= 0)
    dArray = dateString.split("-");
  else if (dateString.indexOf("\\") >= 0)
    dArray = dateString.split("\\");
  else
    dArray = false;
 
  return dArray;
}

/**
Update the field with the given dateFieldName with the dateString that has been passed,
and hide the datepicker. If no dateString is passed, just close the datepicker without
changing the field value.

Also, if the page developer has defined a function called datePickerClosed anywhere on
the page or in an imported library, we will attempt to run that function with the updated
field as a parameter. This can be used for such things as date validation, setting default
values for related fields, etc. For example, you might have a function like this to validate
a start date field:

function datePickerClosed(dateField)
{
  var dateObj = getFieldDate(dateField.value);
  var today = new Date();
  today = new Date(today.getFullYear(), today.getMonth(), today.getDate());
 
  if (dateField.name == "StartDate") {
    if (dateObj < today) {
      // if the date is before today, alert the user and display the datepicker again
      alert("Please enter a date that is today or later");
      dateField.value = "";
      document.getElementById(datePickerDivID).style.visibility = "visible";
      adjustiFrame();
    } else {
      // if the date is okay, set the EndDate field to 7 days after the StartDate
      dateObj.setTime(dateObj.getTime() + (7 * 24 * 60 * 60 * 1000));
      var endDateField = document.getElementsByName ("EndDate").item(0);
      endDateField.value = getDateString(dateObj);
    }
  }
}

*/
function updateDateField(dateFieldName, dateString)
{
  var targetDateField = document.getElementsByName (dateFieldName).item(0);
  if (dateString)
    targetDateField.value = dateString;
 
  var pickerDiv = document.getElementById(datePickerDivID);
  pickerDiv.style.visibility = "hidden";
  pickerDiv.style.display = "none";
 
  adjustiFrame();
  targetDateField.focus();
 
  // after the datepicker has closed, optionally run a user-defined function called
  // datePickerClosed, passing the field that was just updated as a parameter
  // (note that this will only run if the user actually selected a date from the datepicker)
  if ((dateString) && (typeof(datePickerClosed) == "function"))
    datePickerClosed(targetDateField);
}


/**
Use an "iFrame shim" to deal with problems where the datepicker shows up behind
selection list elements, if they're below the datepicker. The problem and solution are
described at:

http://dotnetjunkies.com/WebLog/jking/archive/2003/07/21/488.aspx
http://dotnetjunkies.com/WebLog/jking/archive/2003/10/30/2975.aspx
*/
function adjustiFrame(pickerDiv, iFrameDiv)
{
  // we know that Opera doesn't like something about this, so if we
  // think we're using Opera, don't even try
  var is_opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
  if (is_opera)
    return;
  
  // put a try/catch block around the whole thing, just in case
  try {
    if (!document.getElementById(iFrameDivID)) {
      // don't use innerHTML to update the body, because it can cause global variables
      // that are currently pointing to objects on the page to have bad references
      //document.body.innerHTML += "<iframe id='" + iFrameDivID + "' src='javascript:false;' scrolling='no' frameborder='0'>";
      var newNode = document.createElement("iFrame");
      newNode.setAttribute("id", iFrameDivID);
      newNode.setAttribute("src", "javascript:false;");
      newNode.setAttribute("scrolling", "no");
      newNode.setAttribute ("frameborder", "0");
      document.body.appendChild(newNode);
    }
    
    if (!pickerDiv)
      pickerDiv = document.getElementById(datePickerDivID);
    if (!iFrameDiv)
      iFrameDiv = document.getElementById(iFrameDivID);
    
    try {
      iFrameDiv.style.position = "absolute";
      iFrameDiv.style.width = pickerDiv.offsetWidth;
      iFrameDiv.style.height = pickerDiv.offsetHeight ;
      iFrameDiv.style.top = pickerDiv.style.top;
      iFrameDiv.style.left = pickerDiv.style.left;
      iFrameDiv.style.zIndex = pickerDiv.style.zIndex - 1;
      iFrameDiv.style.visibility = pickerDiv.style.visibility ;
      iFrameDiv.style.display = pickerDiv.style.display;
    } catch(e) {
    }
 
  } catch (ee) {
  }
 
}
function getObj(name)
{
  if (document.getElementById)
  {
        this.obj = document.getElementById(name);
        this.style = document.getElementById(name).style;
  }
  else if (document.all)
  {
        this.obj = document.all[name];
        this.style = document.all[name].style;
  }
  else if (document.layers)
  {
        this.obj = document.layers[name];
        this.style = document.layers[name];
  }
}

