
function bakst (eId){
	document.location.href=document.getElementById(eId).getElementsByTagName('td')[0].getElementsByTagName('a')[0].href;
}


function svyst (eId, col){
	document.getElementById(eId).style.backgroundColor=col;
}

function nesvyst (eId, col){
	document.getElementById(eId).style.backgroundColor=col;
}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

function empty_check(e){
	var el = document.getElementById(e);
	if (el != null){
		if (trim(el.value) == '') return false;
		return true;
	}
	return false;
}

function expandArea(e) {
	var el = document.getElementById(e);
	var val = el.value;
	var len = val.length;
	var size = len/40*10;
	el.style.height = size+60+"px"
} 

function checkMacSn(el_mac, el_sn){
	var mac = document.getElementById(el_mac).value;
	var sn = document.getElementById(el_sn).value;
	if (mac == '' && sn == '')
	{
		document.getElementById('error_place').innerHTML = 'Empty both MAC and Serial Number fields. At least one of them is necesary.';
		return false;
	}
	return true;
}

function getSelectValue(sel){
	var e = document.getElementById(sel);
	if (e != null){
		return e.options[e.selectedIndex].value;
	}
	return '';
}

function selectSelectValue(sel, val)
{
	var e = document.getElementById(sel);
	var i;
	var found = 0;
	if (e!=null) {
		for (i = e.length - 1; i>=0; i--) {
			if (e.options[i].value == val) {
				e.selectedIndex = i;
				found = 1;
				return true;
			}
		}
		if (found == 0) return false;
	}
	return false;
}

function setSelectedIndex(sel, idx)
{
	var e = document.getElementById(sel);
	var i;
	if (e!=null) {
		e.selectedIndex = idx;
		return true;
	}
	return false;
}

function auto_select_purchase_file(select, value, status, def){
	var res;
	clearElement(select+'_note');			
	if (status == true){
		res = selectSelectValue(select, value);
		if (res == false){
			addHTML(select+'_note', 'Unable to select file: '+value);			
		}
	} else {
		if (def == '')
			res =  setSelectedIndex(select, 0);
		else
			res = selectSelectValue(select, def);
	}
	
}

function removeSelectedID(sel){
	var e = document.getElementById(sel);
	if (e != null){
		e.options[e.selectedIndex] = null;
	}
}

function addSelectValue(sel, val, key){
	var e = document.getElementById(sel);
	if (e != null){
		var n = e.length;
		var select = selectSelectValue(sel, key);
		if (select == false){
			e.options[n] = new Option(val, key);
			selectSelectValue(sel, key);
		}
	}
}

function goToValue(url, id){
	var val = getSelectValue(id);
	if (val != '')
	{
		window.location= url + "/?status=" + val;
	} else {
		window.location= url;
	}
}

function check_support_form(){
	if (!empty_check('subject') || !empty_check('description') || !empty_check('fw_version1') || !empty_check('net_topology')){
		fillElement('errorField', 'Some required fields left empty<br/><br/>');
		return false;
	}
	
	if (getSelectValue('product1')=='' || (getSelectValue('product1')==-1 && !empty_check('other_product1'))) {
		fillElement('errorField', 'Please select at least one involved product or specify your own<br/><br/>');
		return false;
	}
	
	if (getSelectValue('repeatability')=='') {
		fillElement('errorField', 'Please select repeatability of the problem<br/><br/>');
		return false;
	}
	return true;
}

var create_order_user_selected = 0;
function validate_create_order_form(){
    if (getSelectValue('product_select') == ''){
    	fillElement('errorField', 'Please select product.<br/><br/>');
        return false;
    }
    if (!empty_check('quantity')){
    	fillElement('errorField', 'Please specify quantity.<br/><br/>');
        return false;
    }
    if (create_order_user_selected == 0){
    	fillElement('errorField', 'Please select user.<br/><br/>');
        return false;    
    }
    return true;
}

function checkNewPrForm(){
	if (!empty_check('priceField')){
		fillElement('errorField', 'Price field is empty.<br/><br/>');
		return false;		
	}
	if (!empty_check('countField')){
		fillElement('errorField', 'Count field is empty.<br/><br/>');
		return false;	
	}
	return true;
}

function maybeShowOther(id){
	if (getSelectValue('product'+id)=='-1'){
		showElement('otherProduct'+id);
	} else {
		hideElement('otherProduct'+id);
	}
}

var loadingDiv;
var activeID;
var a;

function create_edit_form(id){
	var ajax = new sack();
	
	activeID = id;
	loadingDiv = 'edit'+id;
	clearElement('edit'+id);

	ajax.setVar('id', id);
	ajax.setVar('action', 'save_comment_form');
	ajax.requestFile = "http://www.wilibox.com/ajax.actions.php";
	ajax.method = 'post';
	ajax.element = 'edit'+id;


	ajax.onLoading = startLoading;
	ajax.onCompletion = stopLoading;

	ajax.runAJAX();
	return false;
}

function ajax_add_company(){
	var ajax = new sack();
	a = ajax;

	ajax.setVar('company_name', getValue('company_name'));
	ajax.setVar('action', 'add_company');
	ajax.requestFile = "http://www.wilibox.com/ajax.actions.php";
	ajax.method = 'post';
	ajax.onCompletion = addedCompany;
	ajax.runAJAX();
	return false;
}

var alertAfterRemoval;
function ajax_remove_company(id){
	var ajax = new sack();
	a = ajax;
	var argv = ajax_remove_company.arguments;
	var argc = argv.length;	
	activeID = id;
	ajax.setVar('cid', id);
	ajax.setVar('action', 'remove_company');
	if (argc > 1) alertAfterRemoval = 1;
	ajax.requestFile = "http://www.wilibox.com/ajax.actions.php";
	ajax.method = 'post';
	ajax.onCompletion = removedCompany;
	ajax.runAJAX();
	return false;
}

function removedCompany(){
	if (a.response == 1){
	removeSelectedID('company_select');
	if (alertAfterRemoval == 1) window.location.reload();
	} else {
	
	}
}

function ajax_update_company_name(id){
	var ajax = new sack();
	a = ajax;

	ajax.setVar('company_name', getValue('current_company_name'));
	ajax.setVar('cid', id);	
	ajax.setVar('action', 'update_company');
	ajax.requestFile = "http://www.wilibox.com/ajax.actions.php";
	ajax.method = 'post';
	ajax.element = 'company_name_update_msg';
	ajax.runAJAX();
	return false;
}

function addedCompany(){
	if (a.response != 0){
		addSelectValue('company_select', getValue('company_name'), a.response);
	}
}

var product_data_visible = 0;

function get_product_data(id){
	if (product_data_visible == 0){
		var ajax = new sack();
		activeID = id;
		loadingDiv = 'product';
		clearElement('product');

		ajax.setVar('id', id);
		ajax.setVar('action', 'get_product');
		ajax.requestFile = "http://www.wilibox.com/ajax.actions.php";
		ajax.method = 'post';
		ajax.element = 'product';
	
		ajax.onLoading = startLoading;
		ajax.onCompletion = stopLoading;
		ajax.runAJAX();
		product_data_visible = 1;
		setValue('get_product_info_button', 'Hide product info');
	} else {
		clearElement('product');
		setValue('get_product_info_button', 'Get product info');
		product_data_visible = 0;
	}
	return false;
}

function create_ticket_edit_form(id){
	var ajax = new sack();
	
	activeID = id;
	loadingDiv = 'edit_ticket'+id;
	clearElement('edit_ticket'+id);

	ajax.setVar('id', id);
	ajax.setVar('action', 'save_ticket_form');
	ajax.requestFile = "http://www.wilibox.com/ajax.actions.php";	
	ajax.method = 'post';
	ajax.element = 'edit_ticket'+id;


	ajax.onLoading = startLoading;
	ajax.onCompletion = stopLoading;

	ajax.runAJAX();
	return false;
}


function save_edit_form(id){
	var ajax = new sack();

	var comment_value	= document.getElementById('edit_reply_comment'+id).value;
	var el = document.getElementById('comment_status'+id);

	var status = el.options[el.selectedIndex].value;
	activeID = id;
	loadingDiv = 'com'+id;
	
	ajax.setVar('id', id);
	ajax.setVar('comment', comment_value);
	ajax.setVar('status', status);
	ajax.setVar('action', 'save_comment');

	ajax.requestFile = "http://www.wilibox.com/ajax.actions.php";
	ajax.method = 'post';
	ajax.element = 'com'+id;
	
	ajax.onLoading = startLoading;
	ajax.ononLoaded = stopLoading;
	
	clearElement('edit'+id);

	ajax.runAJAX();
	return false;
}

function ajax_search_user(result_div){
	var ajax = new sack();
	a = ajax;
	var needle = getValue('search_user');
	loadingDiv = result_div;
	ajax.setVar('needle', needle);
	ajax.setVar('action', 'search_user');
    ajax.setVar('outputMode', 2);
	ajax.requestFile = "http://www.wilibox.com/ajax.actions.php";
	ajax.method = 'post';
    ajax.element = result_div;
	ajax.onLoading = startLoading;
	ajax.onLoaded = stopLoading;
	ajax.runAJAX();
	return false;	
}

function search_user_rma(ticket){
	var ajax = new sack();
	a = ajax;
	activeID = ticket;
	var needle = getValue('search_user');
	loadingDiv = 'search_user_results';
	
	ajax.setVar('needle', needle);
	ajax.setVar('action', 'rma_search_user');	
	ajax.requestFile = "http://www.wilibox.com/ajax.actions.php";
	ajax.method = 'post';
	ajax.onLoading = startLoading;
	ajax.onLoaded = stopLoading;
	ajax.onCompletion = search_user_rma_completed;
	ajax.runAJAX();
	return false;		
}
function search_user_rma_completed(){
	var longstring = a.response;
	var arr = longstring.split('\n');
	var i;
	var user; var res;
	res = '';
	for (i=0; i<arr.length; i++){
		if (arr[i] != ''){
			user = arr[i].split(':');
			if (user != 0)
			res = res + "<br/><a href='?wid=admin-rma&ticket_id="+activeID+"&amp;new_user="+user[0]+"'>" +user[1] + " " + user[2] + "</a> ("+user[3]+")<br/>";
		}
		
	}
	if (res == '') res = 'No users found..';
	fillElement('search_user_results', res);
}
function search_user_rma_select(id){
	alert(id);
}
function new_support_product_form(id){
	var ajax = new sack();
	activeID = id;
	loadingDiv = 'form'+id;
	
	ajax.setVar('id', id);
	ajax.setVar('action', 'support_product_form');

	ajax.requestFile = "http://www.wilibox.com/ajax.actions.php";
	ajax.method = 'post';
	ajax.element = 'form'+id;
	
	ajax.onLoading = startLoading;
	ajax.ononLoaded = stopLoading;
	clearElement('addFormButton'+id);
	
	ajax.runAJAX();
	return false;	
}


	var product_name;
	var product_mac;
	var product_sn;
	var complete_set;
	var note;
	var ticket_status;

function save_ticket_edit_form(id){
	var ajax = new sack();
	a = ajax;

	product_name = document.getElementById('product_name_input').value;
	product_mac	 = document.getElementById('product_mac_input').value;
	manufacturer = document.getElementById('manufacturer_sn_input').value;
	product_sn	 = document.getElementById('product_sn_input').value;
	note_to_client = document.getElementById('note_to_client').value;
	warranty_off	=	document.getElementById('warranty_off').checked;
	ticket_status = getSelectValue('ticket_status_input');

	activeID = id;
	loadingDiv = 'edit_ticket'+id;
	
	ajax.setVar('id', id);
	ajax.setVar('ti_product_name', product_name);
	ajax.setVar('ti_product_mac', product_mac);
	ajax.setVar('ti_product_sn', product_sn);
	ajax.setVar('ti_manufacturer', manufacturer);
	ajax.setVar('ti_status', ticket_status);
	ajax.setVar('note_to_client', note_to_client);
	if (warranty_off){
		ajax.setVar('ti_warranty_expired', 1);
	} else {
		ajax.setVar('ti_warranty_expired', 0);
	}
	
	ajax.setVar('action', 'save_ticket');

	ajax.requestFile = "http://www.wilibox.com/ajax.actions.php";
	ajax.method = 'post';
    
        ajax.onLoading = startLoading;
	ajax.onLoaded = stopLoading;
	ajax.onCompletion = ticketSaved;

	ajax.runAJAX();
	return false;
}

function ticketSaved(){
	if (a.response == 1) fillElement(loadingDiv, 'Updated, but product was not found in database. Reloading page to update data..');
	if (a.response == 2) fillElement(loadingDiv, 'Updated. Reloading page to update data..');
	window.location.reload();
}

var saveNote = 0;

function noteNeedsSaving(){
	saveNote = 1;
}

function save_note(id){
	if (saveNote == 1){
		var ajax = new sack();
		note = document.getElementById('fast_ticket_note').value;
		ajax.setVar('id', id);
		ajax.setVar('note', note);
		ajax.setVar('action', 'save_ticket_note');
		ajax.requestFile = "http://www.wilibox.com/ajax.actions.php";
		ajax.method = 'post';
		ajax.onCompletion = noteSaved;
		ajax.runAJAX();
	}
	return false;
}

function noteSaved(){
	fillElement('note_saved', 'Note was saved');
}

var old_value = '';

function edit_note(id){
	activeID = id;
	old_value = getHTML("log_note_html"+id);
	var new_html = "<textarea id='log_note_area"+id+"' class='ticket_note_area' style='width:100%;'>"+old_value+"</textarea><br/>	<input type='button' value='Save' onclick='save_note_edit("+id+");'class='inputlogin'/> <input type='button' value='Delete' onclick='delete_note("+id+");' class='inputlogin'/> <input type='button' value='Hide' onclick='return hide_note_edit("+id+");' class='inputlogin'/>	";
	fillElement("log_note_html"+id, new_html);
	showSwitch("change_button"+id);
	return false;
}

function save_note_edit(id){
		var ajax = new sack();
		note = document.getElementById('log_note_area'+id).value;
		ajax.setVar('id', id);
		ajax.setVar('note', note);
		ajax.setVar('action', 'save_edited_note');
		ajax.requestFile = "http://www.wilibox.com/ajax.actions.php";
		ajax.method = 'post';
		old_value = note;
		activeID = id;
		ajax.onCompletion = hide_note_edit;
		ajax.runAJAX();
}

function delete_note(id){
		var conf = confirm('Really delete this note?');
		if (conf){
			var ajax = new sack();
			a = ajax;
			ajax.setVar('id', id);
			ajax.setVar('action', 'delete_note');
			ajax.requestFile = "http://www.wilibox.com/ajax.actions.php";
			ajax.method = 'post';
			activeID = id;
			ajax.onCompletion = hide_note;
			ajax.runAJAX();
		}
		return false;
}

function hide_note_edit(){
	var maybeID = hide_note_edit.arguments[0];
	if (maybeID != null) {
		activeID = maybeID;
		old_value = getValue("log_note_area"+maybeID);
	}
	clearElement("log_note_html"+activeID);
	fillElement("log_note_html"+activeID, old_value);
	showSwitch("change_button"+activeID);
	return false;
}

function hide_note(){
	clearElement('logtr'+activeID);
}


function alertResponse(){
	// debuggggg
	alert(a.response);
}

function startLoading(){
	var div = document.getElementById(loadingDiv);
	if (div != null)
	{
		div.innerHTML = "<div id='loading"+activeID+"'><p style='line-height:50px; text-align:center;'><img src='http://www.wilibox.com/css/loader.gif'/></p></div>"+div.innerHTML;
	} else {
		alert(loadingDiv + ' not found! Could not display cool loading image :(');
	}
}

function stopLoading() {
  var d = document.getElementById(loadingDiv);
  if (d != null)
  {
	  var olddiv = document.getElementById('loading'+activeID);
	  if (olddiv != null)
	  {
		  d.removeChild(olddiv);
	  }
  }
}

function hide_edit_form(id){
	clearElement('edit'+id);
}
function setValue(e_name, value){
	var e = document.getElementById(e_name);
	if (e != null)
	{
		e.value = value;
	}
}

function showSwitch(elem){
if (document.getElementById(elem).style.display == "none"){
	document.getElementById(elem).style.display = "block";
}else{
	document.getElementById(elem).style.display = "none";}
}

function showElement(elem){
	document.getElementById(elem).style.display = "block";
}

function hideElement(elem){
	document.getElementById(elem).style.display = "none";
}


function getValue(e_name){
	var e = document.getElementById(e_name);
	if (e != null)
	{
		return e.value;
	}
	return '';
}
function getHTML(e_name){
	var e = document.getElementById(e_name);
	if (e != null)
	{
		return e.innerHTML;
	}
	return '';
}
function fillElement(e_name, value){
	var e = document.getElementById(e_name);
	if (e != null)
	{
		e.innerHTML = value;
	}
}

function addHTML(e_name, value){
	var e = document.getElementById(e_name);
	if (e != null)
	{
		e.innerHTML = e.innerHTML + value;
	}
}

function clearElement(e_name){
	var e = document.getElementById(e_name);
	if (e != null)
	{
		e.innerHTML = '';
	}
}

function setFocus(el){
	var e = document.getElementById(el);
	if (e != null){
		e.focus();
	}
}

function switch_deposit_history(){
	var now = readCookie('deposit_history');
	if (now == 1){
		hideElement('deposit_history_table');
		createCookie('deposit_history', 0, 5);
		setValue('deposit_history_switch_button', '+');
	} else {
		showElement('deposit_history_table');
		createCookie('deposit_history', 1, 5);
		setValue('deposit_history_switch_button', '-');
	}
}

function switch_deposit_pay_history(){
	var now = readCookie('deposit_pay_history');
	if (now == 1){
		hideElement('deposit_pay_history_table');
		createCookie('deposit_pay_history', 0, 5);
		setValue('deposit_paid_switch_button', '+');
	} else {
		showElement('deposit_pay_history_table');
		createCookie('deposit_pay_history', 1, 5);
		setValue('deposit_paid_switch_button', '-');		
	}
}



function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}


function loadAttributeFields(id){
	var ajax = new sack();
	activeID = id;
	loadingDiv = 'prAttrHolder';
	clearElement(loadingDiv);
	ajax.setVar('id', id);
	ajax.setVar('action', 'get_pr_attributes');
	ajax.requestFile = "http://www.wilibox.com/ajax.actions.php";	
	ajax.method = 'post';
	ajax.element = 'prAttrHolder';

	ajax.onLoading = startLoading;
	ajax.onCompletion = stopLoading;

	ajax.runAJAX();
	return false;
}

var pap = 0;
function addAttrSelect(){
	var ajax = new sack();
	a = ajax;
	var product_select = document.getElementById('pr_code');
	var product_id = product_select.options[product_select.selectedIndex].value;
	activeID = getFreeId();
	ajax.setVar('id', activeID);
	ajax.setVar('prid', product_id);
	ajax.setVar('action', 'get_new_attr');
	ajax.requestFile = "http://www.wilibox.com/ajax.actions.php";	
	ajax.method = 'post';
	ajax.onCompletion = addAttrHtml;
	ajax.runAJAX();
	return false;
}

var disCount = 3; // default
function addDiscountSelect(){
	var ajax = new sack();
	a = ajax;
	ajax.setVar('id', disCount);
	ajax.setVar('action', 'add_discount');
	ajax.requestFile = "http://www.wilibox.com/ajax.actions.php";	
	ajax.method = 'post';
	ajax.onCompletion = incDisCount;
	ajax.runAJAX();
	return false;
}

function incDisCount(){
	var el = document.getElementById('new_dholder');
	if (el != null){
		var div = document.createElement("div");
		div.id = 'holder'+disCount;
		div.innerHTML = a.response;
		var newEl = el.appendChild(div);
		disCount++;
	}	
}

function getFreeId(){
	var div  = document.getElementById('prAttrHolder');
	var sels = div.getElementsByTagName("select");
	if (sels.length != null){
		return findFreeId(sels.length, 'holder');
	}
	return 0;
}


function findFreeId(offset, el){
	var found = document.getElementById(el+offset);
	if (found != null) {
		offset = findFreeId(offset+1, el);
	}
	return offset;
}

function addAttrHtml(){
	//addHTML('holder'+activeID, a.response);
	var el = document.getElementById('new_attrs_holder');
	if (el != null){
		var div = document.createElement("div");
		div.id = 'holder'+activeID;
		div.innerHTML = a.response;
		var newEl = el.appendChild(div);
	}
}

function attrSelectChange(pntr, id){
	ajaxAddCustomSelect(pntr.options[pntr.selectedIndex].value, id);
	if (id != ''){
		if (pntr.selectedIndex == 1){
			showSwitch('customAttr'+id);
		} else {
			hideElement('customAttr'+id);
		}
	}
}

function ajaxAddCustomSelect(aid, id){
	var ajax = new sack();
	a = ajax;
	ajax.setVar('aid', aid);
	ajax.setVar('id', id);
	ajax.setVar('action', 'load_common_value_select');
	ajax.requestFile = "http://www.wilibox.com/ajax.actions.php";	
	ajax.method = 'post';
	ajax.element = 'commonValueSelectHolder'+id;
	ajax.runAJAX();
	return false;
}




//
// calendar script
//


function DateCompare (value1, value2) {
   var date1, date2;
   var month1, month2;
   var year1, year2;

   year1 = value1.substring (0, value1.indexOf ("-"));
   month1 = value1.substring (value1.indexOf ("-")+1, value1.lastIndexOf ("-"));
   date1 = value1.substring (value1.lastIndexOf ("-")+1, value1.length);

   year2 = value2.substring (0, value2.indexOf ("-"));
   month2 = value2.substring (value2.indexOf ("-")+1, value2.lastIndexOf ("-"));
   date2 = value2.substring (value2.lastIndexOf ("-")+1, value2.length);

   if (year1 > year2) return 1;
   else if (year1 < year2) return -1;
   else if (month1 > month2) return 1;
   else if (month1 < month2) return -1;
   else if (date1 > date2) return 1;
   else if (date1 < date2) return -1;
   else return 0;
} 


/**
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
*/
var datePickerDivID = "datepicker";
var iFrameDivID = "datepickeriframe";

var dayArrayShort = new Array('Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'So');
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 = "ymd"    // valid values are "mdy", "dmy", and "ymd"
var dateSeparator = defaultDateSeparator;
var dateFormat = defaultDateFormat;

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
  fillTo = thisDay.getDay() -1;
  if (fillTo < 0)
	  fillTo = 6;
  for (i = 0; i < fillTo; 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() == 0)
      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 + "\");'>X</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 dabar = new Date();
	var targetDateField = document.getElementsByName (dateFieldName).item(0);
    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:
*/
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) {
  }
 
}
