/** EmotionUS DatePicker */

function DatePicker(obj, dtFormat, dtSep, use_button, use_thismonth, use_close) {
	var datePickerTableID = "datepicker";
	var iFrameDivID = "datepickeriframe";

	var dapi_mouse_on_list = 0;
	var dapi_toid;
	var do_now_show_popup=false;

	this.dayArrayShort = new Array('S', 'M', 'T', 'W', 'T', 'F', 'S'); //Array('Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa');
	this.dayArrayMed = new Array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
	this.dayArrayLong = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');

	this.monthArrayShort = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
	this.monthArrayMed = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec');
	this.monthArrayLong = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
	 
	this.dateSeparator = "/";       // common values would be "/" or "."
	this.dateFormat = "mdy";		// valid values are "mdy", "dmy", and "ymd"

	this.dapi_style_dropdownbutton = 'dapi_dropdownbutton';
	this.dapi_style_button = 'dapi_button';
	this.dapi_style_button_prev = 'dapi_button_prev';
	this.dapi_style_button_next = 'dapi_button_next';
	this.dapi_style_button_close = 'dapi_button_close';
	this.dapi_style_table = 'dapi_table';
	this.dapi_style_header = 'dapi_header';
	this.dapi_style_footer = 'dapi_footer';
	this.dapi_style_daynameheader = 'dapi_daynameheader';
	this.dapi_style_dayname = 'dapi_dayname';
	this.dapi_style_title = 'dapi_title';
	this.dapi_style_row = 'dapi_row';
	this.dapi_style_today = 'dapi_today';
	this.dapi_style_selected = 'dapi_selected';
	this.dapi_style_day = 'dapi_day';

	this.dapi_timeOut = -1; // Autocomplete Timeout in ms (-1: autocomplete never time out)
	this.dapi_curr = null;

	var use_button = use_button || false;
	var use_thismonth = use_thismonth || false;
	var use_close = use_close || true;
	this.use_button = use_button;
	this.use_thismonth = use_thismonth;
	this.use_close = use_close;


	this.attach_object = function(attach_obj, use_button) {
		var attach_obj = isObject(attach_obj) ? attach_obj : document.getElementById(attach_obj);

		attach_obj.controller = dapi_self;

		if(use_button) dapi_create_dropdown_button(attach_obj);

		addEvent(attach_obj,"focus",dapi_setup);

		return attach_obj;
	}

	var dapi_self = this;
	dapi_curr = this.attach_object(obj, use_button);

	if (dtSep)    dapi_self.dateSeparator = dtSep;
	if (dtFormat) dapi_self.dateFormat = dtFormat;

	function dapi_create_dropdown_button(rel_obj){
		var a = document.createElement('a');
		a.href = "javascript:void(0);";
		a.tabIndex = -1;
		a.onclick = function() { dapi_show(); }
		a.innerHTML = '&#X25BC;';
		a.className = dapi_self.dapi_style_dropdownbutton;
		a.style.display = "inline";
		a.style.height = (rel_obj.offsetHeight-2) + 'px';
		
		var op = rel_obj.parentNode;
		if(rel_obj.nextSibling)
			op.insertBefore(a,rel_obj.nextSibling);
		else
			op.appendChild(a);
	}

	function dapi_setup(evt){
		if (!evt) evt = event;
		
		dapi_curr = evt.target || evt.srcElement;

		//addEvent(document,"keydown",dapi_checkkey);
		addEvent(dapi_curr,"blur",dapi_clear);
		addEvent(dapi_curr,"mousedown",dapi_mousedown);
		//addEvent(document,"keypress",dapi_keypress);

		if(!dapi_display()){
			if (!do_now_show_popup) dapi_show();
		}
		dapi_curr.select();
		do_now_show_popup = false;
	}

	function dapi_clear(evt){
		if (!evt) evt = event;
		//removeEvent(document,"keydown",dapi_checkkey);
		removeEvent(dapi_curr,"mousedown",dapi_mousedown);
		removeEvent(dapi_curr,"blur",dapi_clear);
		//removeEvent(document,"keypress",dapi_keypress);
		dapi_removedisp();
	}

	function dapi_mousedown() {
		if(!dapi_display()) dapi_show();
	}

	function dapi_display() {
		var tobj = document.getElementById(datePickerTableID);
		return (tobj && tobj.style.display != 'none');
	}

	function dapi_show(year, month, day) {
		var dt = getFieldDate(dapi_curr.value);
		if(year){
			if(year==dt.getFullYear() && month==dt.getMonth())
				dapi_generate(year, month, dt.getDate());
			else
				dapi_generate(year, month, day);
		} else {
			dapi_generate(dt.getFullYear(), dt.getMonth(), dt.getDate());
		}
		with(document.getElementById(datePickerTableID)){
			//style.top = eval(curTop(dapi_curr) + dapi_curr.offsetHeight) + "px";
			style.top = getPopupTop(dapi_curr, offsetHeight);
			style.display = 'block';
		}
		dapi_curr.select();
	}

	function dapi_generate(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);
		}

		var tobj = document.getElementById(datePickerTableID);
		if (tobj){ document.body.removeChild(tobj); } 

		var a, r, c, b;

		a = document.createElement('table');
		a.cellSpacing='0px';
		a.cellPadding='0px';
		a.style.position='absolute';
		a.style.zIndex = 1000;
		//a.style.top = eval(curTop(dapi_curr) + dapi_curr.offsetHeight) + "px";
		a.style.left = curLeft(dapi_curr) + "px";
		a.id = datePickerTableID;
		a.className = dapi_self.dapi_style_table;
		document.body.appendChild(a);

		a.onmouseout = dapi_table_unfocus;
		a.onmouseover = dapi_table_focus;

		// make header
		r = a.insertRow(-1);
		r.className = dapi_self.dapi_style_header;

		c = r.insertCell(-1);
		c.align = "left";
		b = dapi_create_button("", thisDay, -1);
		b.className = dapi_self.dapi_style_button_prev;
		c.appendChild(b);

		c = r.insertCell(-1);
		c.colSpan = 5;
		c.className = dapi_self.dapi_style_title;
		c.innerHTML = dapi_self.monthArrayLong[ thisDay.getMonth()] + " " + thisDay.getFullYear();

		c = r.insertCell(-1);
		c.align = "right";
		b = dapi_create_button("", thisDay, 1);
		b.className = dapi_self.dapi_style_button_next;
		c.appendChild(b);

		// make dayname header
		r = a.insertRow(-1);
		r.className = dapi_self.dapi_style_daynameheader;

		for(i = 0; i < dapi_self.dayArrayShort.length; i++){
			c = r.insertCell(-1);
			c.className = dapi_self.dapi_style_dayname;
			c.innerHTML = dapi_self.dayArrayShort[i];
		}

		// first, the leading blanks
		if(thisDay.getDay()){
			r = a.insertRow(-1);
			r.className = dapi_self.dapi_style_row;
			for (i = 0; i < thisDay.getDay(); i++){
				c = r.insertCell(-1);
				c.innerHTML = "&nbsp;";
			}
		}

		// now, the days of the month
		do {
			// if this is a Saturday, start a new row
			if (thisDay.getDay() == 0){
				r = a.insertRow(-1);
				r.className = dapi_self.dapi_style_row;
			}

			dayNum = thisDay.getDate();
			c = r.insertCell(-1);
			c.appendChild(dapi_create_day(thisDay, (dayNum==day)));

			// increment the day
			thisDay.setDate(thisDay.getDate() + 1);
		} while (thisDay.getDate() > 1)

		// fill in any trailing blanks
		if (thisDay.getDay()) {
			for (i = 7; i > thisDay.getDay(); i--) {
				c = r.insertCell(-1);
				c.innerHTML = "&nbsp;";
			}
		}

		while(a.rows.length < 8){
			r = a.insertRow(-1);
			r.className = dapi_self.dapi_style_row;
			c = r.insertCell(-1);
			c.colSpan = 7;
			c.innerHTML = "&nbsp;";
		}

		// add a button to allow the user to easily return to today, or close the calendar
		r = a.insertRow(-1);
		r.className = dapi_self.dapi_style_footer;
		c = r.insertCell(-1);
		c.colSpan = 7;
		if (dapi_self.use_close){
			var tobj = dapi_create_link('Close', 'javascript:void(0);', dapi_hide);
			tobj.className = dapi_self.dapi_style_button_close;
			c.appendChild(tobj);
		}
		if (dapi_self.use_thismonth){
			var today = new Date();
			c.appendChild(dapi_create_button('this month', today));
		}

		// add an "iFrame shim" to allow the datepicker to display above selection lists
		adjustiFrame();
	}

	function dapi_create_link(caption, href, obj_function){
		var a = document.createElement('a');
		a.href = href;  //"javascript:void(0);";
		a.onclick = obj_function;
		a.innerHTML = caption;
		a.tabIndex = -1;
		return a;
	}

	function dapi_create_day(thisDay, IsSelected){
		var a = document.createElement('a');
		var newDate = new Date(thisDay);
		var today = new Date();
		a.href = "javascript:void(0);";
		a.onclick = function() { updateDateField(getDateString(newDate)); }
		a.innerHTML = newDate.getDate();
		a.tabIndex = -1;
		today.setHours(0,0,0,0);
		a.className = ((thisDay-today)? '': dapi_self.dapi_style_today + ' ') + (IsSelected? dapi_self.dapi_style_selected + ' ':'') + dapi_self.dapi_style_day + '_' + thisDay.getDay() + ' ' + dapi_self.dapi_style_day;
		return a;
	}

	/**  Convenience function for writing the code for the buttons that bring us back or forward a month. */
	function dapi_create_button(label, dateVal, adjust){
		var newMonth, newYear;
		adjust = adjust || 0;

		if (dateVal){
			newMonth = (dateVal.getMonth() + adjust) % 12;
			newYear = dateVal.getFullYear() + parseInt((dateVal.getMonth() + adjust) / 12);
			if (newMonth < 0) {
				newMonth += 12;
				newYear += -1;
			}
		}

		var a = document.createElement('button');
		a.tabIndex = -1;
		a.onclick = function() { dapi_show(newYear, newMonth);  }
		a.value = label;
		a.className = dapi_self.dapi_style_button;
		return a;
	}
	
	/** 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 (dapi_self.dateFormat) {
			case "dmy" :
				return dayString + dapi_self.dateSeparator + monthString + dapi_self.dateSeparator + dateVal.getFullYear();
			case "ymd" :
				return dateVal.getFullYear() + dapi_self.dateSeparator + monthString + dapi_self.dateSeparator + dayString;
			case "mdy" :
			default :
				return monthString + dapi_self.dateSeparator + dayString + dapi_self.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 (dapi_self.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);
				}
				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;
	}

	/** Validate Date */
	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.display = "block";
				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(dateString) {
		if (dateString)
			dapi_curr.value = dateString;

		var pickerTable = document.getElementById(datePickerTableID);
		pickerTable.style.display = "none";

		adjustiFrame();
		do_now_show_popup = true;
		dapi_curr.focus();

		if ((dateString) && (typeof(datePickerClosed) == "function"))
			datePickerClosed(dapi_curr);
	}


	/** "iFrame shim"
	http://dotnetjunkies.com/WebLog/jking/archive/2003/07/21/488.aspx
	http://dotnetjunkies.com/WebLog/jking/archive/2003/10/30/2975.aspx */
	function adjustiFrame(pickerTable, 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.style.position = "absolute";
				newNode.setAttribute("id", iFrameDivID);
				newNode.setAttribute("src", "");
				newNode.setAttribute("scrolling", "no");
				newNode.setAttribute ("FRAMEBORDER", "0");
				document.body.appendChild(newNode);
			}

			var pickerTable = document.getElementById(datePickerTableID);
			var iFrameDiv = document.getElementById(iFrameDivID);

			try {
				iFrameDiv.style.width = pickerTable.offsetWidth;
				iFrameDiv.style.height = pickerTable.offsetHeight ;
				iFrameDiv.style.top = pickerTable.style.top;
				iFrameDiv.style.left = pickerTable.style.left;
				iFrameDiv.style.zIndex = pickerTable.style.zIndex - 1;
				iFrameDiv.style.display = pickerTable.style.display;
			} catch(e) {
			}
		} catch (ee) {
		}
	}

	function dapi_table_focus(){
		dapi_mouse_on_list = 1;
	}

	function dapi_table_unfocus(){
		dapi_mouse_on_list = 0;
		if (dapi_toid) clearTimeout(dapi_toid);
		if (dapi_self.dapi_timeOut > 0) dapi_toid = setTimeout(function(){dapi_mouse_on_list = 0;dapi_removedisp();},dapi_self.dapi_timeOut);
	}

	function dapi_hide(){
		dapi_mouse_on_list=0;
		dapi_removedisp();
	}

	function dapi_removedisp(){
		if (dapi_mouse_on_list==0){
			var tobj = document.getElementById(datePickerTableID);
			if (tobj){ document.body.removeChild(tobj); }
			var tobj = document.getElementById(iFrameDivID);
			if (tobj){ document.body.removeChild(tobj); }

			if (dapi_toid) clearTimeout(dapi_toid);
		}
	}

	function actb_keypress(e){
		/*
		if (actb_caretmove) stopEvent(e);
		return !actb_caretmove; */
	}

	function actb_checkkey(evt){
		if (!evt) evt = event;
		a = evt.keyCode;
		/*
		switch (a){
			case 33:   //page up
				actb_goup(true);
				return false;
				break;
			case 34:   //page down
				actb_godown(true);
				return false;
				break;
			case 38: //up
				actb_goup();
				return false;
				break;
			case 40: //down
				if (actb_display){
					actb_godown();
				} else {
					actb_self.showlist();
				}
				return false;
				break;
			case 13: case 9:  //return, tab
				if (actb_display){
					actb_caretmove = 1;
					actb_penter();
					return false;
				}else{
					return true;
				}
				break;
			case 16: case 17: case 18: 
				break;
			default:
		} */
	}

}
