if (window.attachEvent) {
	window.attachEvent("onload", replaceInputs);
} else if (window.addEventListener) {
	window.addEventListener("load", replaceInputs, false);
}

function getWhispSpecialElements(obj) {
	var elements = obj.childNodes;
	var elmLength = elements.length;
	
	var elmList = [];

	for (var i = 0; i < elmLength; ++i) {
		var element = elements[i];

		if (element.nodeType != 3 && element.nodeType != 8) {
			try {
				if (element.getAttribute("w:type")) {
					elmList.push(elements[i]);
				}
			} catch (ex) {
			}

			var children = getWhispSpecialElements(elements[i]);

			for (var j = 0; j < children.length; ++j) {
				elmList.push(children[j]);
			}
		}
	}

	return(elmList);
}


function replaceInputs() {
  var inputs = getWhispSpecialElements(document.body);

  for (var i = 0; i < inputs.length; ++i) {
    var input = inputs[i];
    var inputType = input.getAttribute("w:type");

    if (inputType == "time") {
      var w = new WhispTimeInputBox(input);
    }

    if (inputType == "calendar") {
      var w = new WhispCalendarInputBox(input);
    }
  }
}

/*************************************************/

var WhispInputBox = function() { };

/*************************************************/

var WhispTimeInputBox = function(inputDiv) {
  var that = this;

  var id = inputDiv.getAttribute("w:id");
  
  if (!id) {
    alert('Missing ID on Time Input Box');
    return;
  }
  
  var name = inputDiv.getAttribute("w:name");

  if (!name) {
    name = id;
  }
  
  var defaultHour = -1;
  var defaultMin = -1;
  var defaultAMPM = "AM";
  
  if(inputDiv.getAttribute("w:defaultHour")) {
  	defaultHour = parseFloat(inputDiv.getAttribute("w:defaultHour"));
  }
  if(inputDiv.getAttribute("w:defaultMin")) {
  	defaultMin = parseFloat(inputDiv.getAttribute("w:defaultMin"));
  }
  if(inputDiv.getAttribute("w:defaultAMPM")) {
  	defaultAMPM = inputDiv.getAttribute("w:defaultAMPM");
  }
  
  var hiddenInput = document.createElement('input'); 
  hiddenInput.type = "hidden";
  hiddenInput.id = id;
  hiddenInput.name = name;

  this.m_Input = hiddenInput;
  inputDiv.appendChild(this.m_Input);

  // Hour Box.
  var hourSelector = document.createElement('select');

  var h = 1;

  var option = new Option("12", 0);
  if (defaultHour == 12)
    	option.selected = true;
  hourSelector.options.add(option);

  for (var i = 1; i < 12; ++i) {
    var option = new Option(i, h);
    if (defaultHour == i)
    	option.selected = true;
    hourSelector.options.add(option);
    ++h;
  }

  hourSelector.onchange = function() {
    that.update();
  };

  this.m_Hour = hourSelector;
  inputDiv.appendChild(this.m_Hour);

  // Minute Box.
  var minSelector = document.createElement('select');

  for (var i = 0; i < 60; i += 5) {
    var t = i;

    if (i < 10) {
       t = '0' + t;
    }

    var option = new Option(t, i);
	if (defaultMin == i)
    	option.selected = true;
    minSelector.options.add(option);
  }

  minSelector.onchange = function() {
    that.update();
  };

  this.m_Minute = minSelector;
  inputDiv.appendChild(document.createTextNode(" : "));
  inputDiv.appendChild(this.m_Minute);

  // APM Box.
  var apmSelector = document.createElement('select');

  if (defaultAMPM == "AM")
  {
    apmSelector.options.add(new Option("AM", "AM", true)); 
    apmSelector.options.add(new Option("PM", "PM", false)); 
  }
  else
  {
    apmSelector.options.add(new Option("AM", "AM", false)); 
    apmSelector.options.add(new Option("PM", "PM", true)); 
  }

  this.m_APM = apmSelector;

  inputDiv.appendChild(document.createTextNode(" "));
  inputDiv.appendChild(this.m_APM); 
  
  apmSelector.onchange = function() {
    that.update();
  }; 
  
  that.update();
};

WhispTimeInputBox.prototype = new WhispInputBox();

WhispTimeInputBox.prototype.update = function() {
  var hour = this.m_Hour.options[this.m_Hour.selectedIndex].value * 1;
  var minute = this.m_Minute.options[this.m_Minute.selectedIndex].value * 1;

  var apm = this.m_APM.options[this.m_APM.selectedIndex].value;

  var time = minute * 60 + (hour * 60 * 60);

  if (apm == "PM") {
	time += (12 * 60 * 60);
  }

  this.m_Input.value = time;
};

/*************************************************/

var WhispCalendarInputBox = function(inputDiv) {
  var that = this;

  var id = inputDiv.getAttribute("w:id");
  
  if (!id) {
    alert('Missing ID on Calendar Input Box');
    return;
  }

  var name = inputDiv.getAttribute("w:name");

  if (!name) {
    name = id;
  }

  var hiddenInput = document.createElement('input'); 
  hiddenInput.type = "hidden";
  hiddenInput.id = id;
  hiddenInput.name = name;

  this.m_Input = hiddenInput;
  inputDiv.appendChild(this.m_Input);

  // Find the starting month and year.
  var m = inputDiv.getAttribute("w:month");
  var y = inputDiv.getAttribute("w:year");

  var dt = new Date();

  if (!m) {
    m = dt.getMonth() + 1;
    y = dt.getFullYear();
  }

  var wDays = ['S', 'M', 'T', 'W', 'R', 'F', 'S'];

  // Build the DOM.

  inputDiv.className = "whispCalendar";

  var backButton = C('input', null, { type: "button", value: "<" });
  var forwardButton = C('input', null, { type: "button", value: ">" });
  var headerDiv = C('div', null, { style: "text-align: center;" });

  backButton.onclick = function() {
	that.moveMonth(-1);
  };

  forwardButton.onclick = function() {
	that.moveMonth(1);
  };

  var weekHeaders = [];

  for (var i = 0; i < 7; ++i) {
	weekHeaders.push(C('td', T(wDays[i]), { className: "weekday" }));
  }

  var dayCol = C('td', null, { colSpan: 7 });

  var todayButton = C('input', null, { type: "button", value: "Today" });

  todayButton.onclick = function() {
	var todayDate = new Date();
	that.setDate(todayDate.getMonth() + 1, todayDate.getDate(), todayDate.getFullYear());
  };

  var todayCol = C('td', 
 		   todayButton,
		   { colSpan: 9, style: "text-align: center;" });

  var header = C('table',
		 C('tbody',
		   C('tr',
		       [ C('td', backButton),
		         C('td', headerDiv, { colSpan: 5 }),
		         C('td', forwardButton) ])));

  var dom = 
   C('table',
     C('tbody', 
       [ C('tr', 
	   C('td', header, { colSpan: 7 })),
	 C('tr', weekHeaders),
	 C('tr', dayCol),
	 C('tr', todayCol)
       ]
     ),
     { style: "width: 200px; border: 1px solid gray;" }
   );

   inputDiv.appendChild(dom);

   // Save references needed later.
   this.m_HeaderDiv = headerDiv;
   this.m_DayColumn = dayCol;

   // Set the current month.
   this.setDate(m, 1, y);
};

WhispCalendarInputBox.prototype = new WhispInputBox();

WhispCalendarInputBox.prototype.moveMonth = function(delta) {
  this.setDate(this.m_CurrentDate.getMonth() + 1 + delta,
	       this.m_CurrentDate.getDate(),
	       this.m_CurrentDate.getFullYear());
};

WhispCalendarInputBox.prototype.getDate = function() {
	return this.m_CurrentDate;
}

WhispCalendarInputBox.prototype.setDate = function(m, d, y) {
  var that = this;

  if (m > 12) {
    m = 1;
    y++;
  }

  if (m == 0) {
    m = 12;
    y--;
  }

  // Clear the day column.
  this.m_DayColumn.innerHTML = "";

  // Create the new table with the proper month.
  var firstDay = new Date(y, m - 1, 1);

  var table = C('table');
  var tbody = C('tbody');

  var cRow = C('tr');
  var hasDays = false;

  // Add the non-days.
  for (var i = 0; i < firstDay.getDay(); ++i) {
        hasDays = true;
	cRow.appendChild(C('td', null, { className: "nonDay" }));
  }

  // Add the days themselves.
  var cd = 1;
  var date = new Date(y, m - 1, 1);
  var today = new Date();

  while (date.getMonth() == m - 1) {
    hasDays = true;

    var cName = "day";

    if (date.getMonth() == today.getMonth() 
	&& date.getDate() == today.getDate()
	&& date.getFullYear() == today.getFullYear()) {
	cName = "today";
    }

    if (cd == d) {
	cName = "currentday";
    }    

    var dayTD = C('td', T(cd), { className: cName });

    dayTD.onclick = function(cYear, cMonth, cDay) {
	return(function() {
		that.setDate(cMonth, cDay, cYear);
	});
    }(y, m, cd);

    cRow.appendChild(dayTD);    

    if (date.getDay() == 6) {
        tbody.appendChild(cRow);
 	cRow = C('tr');
        hasDays = false;
    }        

    cd++;
    date = new Date(y, m - 1, cd);
  }

  var daysInMonth = cd - 1;

  if (d > daysInMonth) {
	this.setDate(m, daysInMonth, y);
	return;
  }

  if (hasDays) {
        tbody.appendChild(cRow);
  }

  table.appendChild(tbody);
  this.m_DayColumn.appendChild(table);

  var monthNames = ["January", "February", "March", "April",
    "May", "June", "July", "August", "September", "October",
    "November", "December"];

  this.m_HeaderDiv.innerHTML = monthNames[m-1] + ", " + y;

  this.m_CurrentDate = new Date(y, m - 1, d);
  this.update();
};

WhispCalendarInputBox.prototype.update = function() {
  this.m_Input.value = this.m_CurrentDate.getTime();
};