var showCalendarTime = false;

function positionInfo(object) {

  var p_elm = object;

  this.getElementLeft = getElementLeft;
  function getElementLeft() {
    var x = 0;
    
    
    	var ele = p_elm;
         var scwTargetEle=ele;

         var offsetTop =parseInt(ele.offsetTop ,10) + parseInt(ele.offsetHeight,10),
             offsetLeft=parseInt(ele.offsetLeft,10);

         if (!window.opera)
             {while (ele.tagName!='BODY' && ele.tagName!='HTML')
                 {offsetTop -=parseInt(ele.scrollTop, 10);
                  offsetLeft-=parseInt(ele.scrollLeft,10);
                  ele=ele.parentNode;
                 }
              ele=scwTargetEle;
             }

         do {ele=ele.offsetParent;
             offsetTop +=parseInt(ele.offsetTop, 10);
             offsetLeft+=parseInt(ele.offsetLeft,10);
            }
         while (ele.tagName!='BODY' && ele.tagName!='HTML');    
	x = offsetLeft;    
	return parseInt(x);
  }

  this.getElementWidth = getElementWidth;
  function getElementWidth(){
    var elm;
    if(typeof(p_elm) == "object"){
      elm = p_elm;
    } else {
      elm = document.getElementById(p_elm);
    }
    return parseInt(elm.offsetWidth);
  }

  this.getElementRight = getElementRight;
  function getElementRight(){
    return getElementLeft(p_elm) + getElementWidth(p_elm);
  }

  this.getElementTop = getElementTop;
  function getElementTop() {
    var y = 0;
    var elm;
    if(typeof(p_elm) == "object"){
      elm = p_elm;
    } else {
      elm = document.getElementById(p_elm);
    }
    while (elm != null) {
      y+= elm.offsetTop;
      elm = elm.offsetParent;
    }
    return parseInt(y);
  }

  this.getElementHeight = getElementHeight;
  function getElementHeight(){
    var elm;
    if(typeof(p_elm) == "object"){
      elm = p_elm;
    } else {
      elm = document.getElementById(p_elm);
    }
    return parseInt(elm.offsetHeight);
  }

  this.getElementBottom = getElementBottom;
  function getElementBottom(){
    return getElementTop(p_elm) + getElementHeight(p_elm);
  }
}

function CalendarControl() {

  var calendarId = 'CalendarControl';
  var currentYear = 0;
  var currentMonth = 0;
  var currentDay = 0;

  var selectedYear = 0;
  var selectedMonth = 0;
  var selectedDay = 0;

  var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
  var dateField = null;
  var timeField = null;
  
  function getProperty(p_property){
    var p_elm = calendarId;
    var elm = null;

    if(typeof(p_elm) == "object"){
      elm = p_elm;
    } else {
      elm = document.getElementById(p_elm);
    }
    if (elm != null){
      if(elm.style){
        elm = elm.style;
        if(elm[p_property]){
          return elm[p_property];
        } else {
          return null;
        }
      } else {
        return null;
      }
    }
  }

  function setElementProperty(p_property, p_value, p_elmId){
    var p_elm = p_elmId;
    var elm = null;

    if(typeof(p_elm) == "object"){
      elm = p_elm;
    } else {
      elm = document.getElementById(p_elm);
    }
    if((elm != null) && (elm.style != null)){
      elm = elm.style;
      elm[ p_property ] = p_value;
    }
  }

  function setProperty(p_property, p_value) {
    setElementProperty(p_property, p_value, calendarId);
  }

  function getDaysInMonth(year, month) {
    return [31,((!(year % 4 ) && ( (year % 100 ) || !( year % 400 ) ))?29:28),31,30,31,30,31,31,30,31,30,31][month-1];
  }

  function getDayOfWeek(year, month, day) {
    var date = new Date(year,month-1,day)
    return date.getDay();
  }

  this.clearDate = clearDate;
  function clearDate() {
      dateField.value = '';

      if (timeField != null && timeField != undefined) {
          timeField = '';
      }
    
    hide();
  }

  this.setDate = setDate;
  function setDate(year, month, day) {
    //alert(dateField);
    if (dateField) {
      if (month < 10) {month = "0" + month;}
      if (day < 10) {day = "0" + day;}

      var dateString = month+"/"+day+"/"+year;
      dateField.value = dateString;

      if (timeField != null && timeField != undefined) {
          var ddlHour = document.getElementById('ddlCalendarHour');
          var ddlMinute = document.getElementById('ddlCalendarMinute');
          var ddlAMPM = document.getElementById('ddlCalendarAMPM');
          timeField.value = ddlHour.options[ddlHour.selectedIndex].value + ':' + ddlMinute.options[ddlMinute.selectedIndex].value + ' ' + ddlAMPM.options[ddlAMPM.selectedIndex].value;
      }
      
      hide();
    }
    return;
  }

  this.changeMonth = changeMonth;
  function changeMonth(change) {
    currentMonth += change;
    currentDay = 0;
    if(currentMonth > 12) {
      currentMonth = 1;
      currentYear++;
    } else if(currentMonth < 1) {
      currentMonth = 12;
      currentYear--;
    }

    calendar = document.getElementById(calendarId);
    calendar.innerHTML = calendarDrawTable();
  }

  this.changeYear = changeYear;
  function changeYear(change) {
    currentYear += change;
    currentDay = 0;
    calendar = document.getElementById(calendarId);
    calendar.innerHTML = calendarDrawTable();
  }

  function getCurrentYear() {
    var year = new Date().getFullYear();
    if(year < 1900) year += 1900;
    return year;
  }

  function getCurrentMonth() {
    return new Date().getMonth() + 1;
  } 

  function getCurrentDay() {
    return new Date().getDate();
  }
  
 
  

  function calendarDrawTable() {

    var dayOfMonth = 1;
    var validDay = 0;
    var startDayOfWeek = getDayOfWeek(currentYear, currentMonth, dayOfMonth);
    var daysInMonth = getDaysInMonth(currentYear, currentMonth);
    var css_class = null; //CSS class for each day

    var table = "<table cellspacing='0' cellpadding='0' border='0' style='border:groove 2pt #000099;'>";
    table = table + "<tr class='header'>";
    table = table + "<td colspan='2' class='previous'><a href='javascript:changeCalendarControlYear(-1);'>&lt;</a></td>";
    table = table + "<td colspan='3' class='title'>" + currentYear + "</td>";
    table = table + "<td colspan='2' class='next'><a href='javascript:changeCalendarControlYear(1);'>&gt;</a>";
    table = table + "</td></tr>";
    table = table + "<tr class='header'><td colspan='2' class='previous'><a href='javascript:changeCalendarControlMonth(-1);'>&lt;</a></td>";
    table = table + "<td colspan='3' class='title'>" + months[currentMonth-1] + "</td>";
    table = table + "<td colspan='2' class='next'><a href='javascript:changeCalendarControlMonth(1);'>&gt;</a></td>";
    table = table + "</tr>";
    table = table + "<tr class='header'><td colspan='7' class='previous'><div align='center'><a href='javascript:changeToday();'>Select Today</a></div></td></tr> ";    
    table = table + "<tr><th>S</th><th>M</th><th>T</th><th>W</th><th>T</th><th>F</th><th>S</th></tr>";
    
    for(var week=0; week < 6; week++) {
      table = table + "<tr>";
      for(var dayOfWeek=0; dayOfWeek < 7; dayOfWeek++) {
        if(week == 0 && startDayOfWeek == dayOfWeek) {
          validDay = 1;
        } else if (validDay == 1 && dayOfMonth > daysInMonth) {
          validDay = 0;
        }

        if(validDay) {
          if (dayOfMonth == selectedDay && currentYear == selectedYear && currentMonth == selectedMonth) {
            css_class = 'current';
          } else if (dayOfWeek == 0 || dayOfWeek == 6) {
            css_class = 'weekend';
          } else {
            css_class = 'weekday';
          }

          table = table + "<td><a class='"+css_class+"' href=\"javascript:setCalendarControlDate("+currentYear+","+currentMonth+","+dayOfMonth+")\">"+dayOfMonth+"</a></td>";
          dayOfMonth++;
        } else {
          table = table + "<td class='empty'>&nbsp;</td>";
        }
      }
      table = table + "</tr>";
  }

  if (showCalendarTime == true) {
      table = table + "<tr><td colspan='7'>";
      table += "<div id='divCalendarTime' style='text-align:center;'>";
      table += "<table>";
      table += "<tr>";
      table += "<td>" + getHourDropDown() + "</td>";
      table += "<td>" + getMinuteDropDown() + "</td>";
      table += "<td>" + getAMPMDropDown() + "</td>";
      table += "</tr>";
      table += "</table>";
      table += "</div>";
      table = table + "</td></tr>";
  }
     
    table = table + "<tr class='header'><th colspan='7' style='padding: 3px;'><a href='javascript:clearCalendarControl();'>Clear Date</a> | <a href='javascript:hideCalendarControl();'>Close</a></th></tr>";
    table = table + "</table>";

    return table;
}
function getAMPMDropDown() {

    var AMPM = '';
    if (timeField != null && timeField != undefined) {
        var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?document.getElementById/;
        var matchArray = timeField.value.match(timePat);
        if (matchArray != null) {
            if (matchArray[6] != null) {
                AMPM = matchArray[6];
            }
        }
    }
    if (AMPM != null) {
        AMPM = AMPM.toUpperCase();
    }

    var ddlAMPM = "<select id='ddlCalendarAMPM'>";
    if (AMPM == 'PM') {
        ddlAMPM += "<option value='AM'>AM</option>";
        ddlAMPM += "<option SELECTED='selected' value='PM'>PM</option>";
    }
    else {
        ddlAMPM += "<option SELECTED='selected' value='AM'>AM</option>";
        ddlAMPM += "<option value='PM'>PM</option>";
    }
    
    ddlAMPM += "</select>";
    return ddlAMPM;
}

function getHourDropDown() {

    var h = '';
    var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?document.getElementById/;
    if (timeField != null && timeField != undefined) {
        var matchArray = timeField.value.match(timePat);
        if (matchArray != null) {
            if (matchArray[1] != null) {
                h = matchArray[1];
            }
        }
    }
    if (h != '') {
        h = leadingZeros(h, 2, '0');
    }
    
    var ddlHour = "<select  id='ddlCalendarHour'>";
    for (var j = 1; j < 13; j++) {
        var hour = leadingZeros(j.toString(), 2, '0');

        if (h != '') {
            if (h == hour) {
                ddlHour += "<option selected='selected' value='" + hour + "'>" + hour + "</option>";
            }
            else {
                ddlHour += "<option value='" + hour + "'>" + hour + "</option>";
            } 
        }
        else {
            ddlHour += "<option value='" + hour + "'>" + hour + "</option>";
        }
    }
    ddlHour += "</select>";
    return ddlHour;
}

function getMinuteDropDown() {

    var m = '';
    var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?document.getElementById/;
    if (timeField != null && timeField != undefined) {
        var matchArray = timeField.value.match(timePat);
        if (matchArray != null) {
            if (matchArray[2] != null) {
                m = matchArray[2];
            }
        }
    }
    if (m != '') {
        m = leadingZeros(m, 2, '0');
    }

    var ddlMinute = "<select  id='ddlCalendarMinute'>";
    for (var i = 0; i < 60; i++) {
        var minute = leadingZeros(i, 2, '0');

        if (m != '') {
            if (m == minute) {
                ddlMinute += "<option selected='selected' value='" + minute + "'>" + minute + "</option>";
            }
            else {
                ddlMinute += "<option value='" + minute + "'>" + minute + "</option>";
            }
        }
        else {
            ddlMinute += "<option value='" + minute + "'>" + minute + "</option>";
        }
    }
    ddlMinute += "</select>";
    return ddlMinute;
}

function leadingZeros(num, totalChars, padWith) {
    num = num + "";
    padWith = (padWith) ? padWith : "0";
    if (num.length < totalChars) {
        while (num.length < totalChars) {
            num = padWith + num;
        }
    } else { }

    if (num.length > totalChars) { //if padWith was a multiple character string and num was overpadded
        num = num.substring((num.length - totalChars), totalChars);
    } else { }

    return num;
}

  this.show = show;
  function show(field, tmField) {
    can_hide = 0;
  
    // If the calendar is visible and associated with
    // this field do not do anything.
    if (dateField == field) {
      return;
    } else {
      dateField = field;
  }
  timeField = tmField;

    if(dateField) {
      try {
        var dateString = new String(dateField.value);
        var dateParts = dateString.split("/");
        
        selectedMonth = parseInt(dateParts[0],10);
        selectedDay = parseInt(dateParts[1],10);
        selectedYear = parseInt(dateParts[2],10);
      } catch(e) {}
    }

    if (!(selectedYear && selectedMonth && selectedDay)) {
      selectedMonth = getCurrentMonth();
      selectedDay = getCurrentDay();
      selectedYear = getCurrentYear();
    }

    currentMonth = selectedMonth;
    currentDay = selectedDay;
    currentYear = selectedYear;

    if(document.getElementById){

      calendar = document.getElementById(calendarId);
      calendar.innerHTML = calendarDrawTable(currentYear, currentMonth);

      setProperty('display', 'block');

      var fieldPos = new positionInfo(dateField);
      var calendarPos = new positionInfo(calendarId);

      var x = fieldPos.getElementLeft();
      var y = fieldPos.getElementBottom();
      
       //Fix Display issue on IE
       var browser=navigator.appName;
	/* if(browser == 'Microsoft Internet Explorer')
            x += 190 ;*/

      setProperty('left', x + "px");
      setProperty('top', y + "px");
 
      if (document.all) {
        setElementProperty('display', 'block', 'CalendarControlIFrame');
        setElementProperty('left', x + "px", 'CalendarControlIFrame');
        setElementProperty('top', y + "px", 'CalendarControlIFrame');
        setElementProperty('width', calendarPos.getElementWidth() + "px", 'CalendarControlIFrame');
        setElementProperty('height', calendarPos.getElementHeight() + "px", 'CalendarControlIFrame');
      }
    }
  }

  this.hide = hide;
  function hide() {
    if(dateField) {
    
      dateField.focus();
		
      setProperty('display', 'none');
      setElementProperty('display', 'none', 'CalendarControlIFrame');
      dateField = null;
    }
  }

  this.visible = visible;
  function visible() {
    return dateField
  }

  this.can_hide = can_hide;
  var can_hide = 0;
}

var calendarControl = new CalendarControl();

function showCalendarControl(textField, tmField) {

    if (tmField != null && tmField != undefined) {
        showCalendarTime = true;
    }
    else {
        showCalendarTime = false;
    }
    calendarControl.show(textField, tmField);
}

function clearCalendarControl() {
  calendarControl.clearDate();
}

function hideCalendarControl() {
  if (calendarControl.visible()) {
    calendarControl.hide();
  }
}

function setCalendarControlDate(year, month, day) {
  calendarControl.setDate(year, month, day);
}

function changeCalendarControlYear(change) {
  calendarControl.changeYear(change);
}

function changeCalendarControlMonth(change) {
  calendarControl.changeMonth(change);
}

 function changeToday(){
  year = new Date().getFullYear();
  month = new Date().getMonth() + 1;
  day = new Date().getDate();
  calendarControl.setDate(year, month, day);
  }
  

document.write("<iframe id='CalendarControlIFrame' src='javascript:false;' frameBorder='0' scrolling='no'></iframe>");
document.write("<div id='CalendarControl'></div>");


//---------- DATE/TIME VALIDATION ---------------//
function isDateOK(input) {
    var validformat = /^\d{1,2}\/\d{1,2}\/\d{4}$/ //Basic check for format validity
    var returnval = false
    if (!validformat.test(input)) {
        //alert("Invalid Date Format. Please correct and submit again.")
        return false;
    }
    else {
        //Detailed check for valid date ranges
        var monthfield = input.split("/")[0]
        var dayfield = input.split("/")[1]
        var yearfield = input.split("/")[2]
        var dayobj = new Date(yearfield, monthfield - 1, dayfield)
        if ((dayobj.getMonth() + 1 != monthfield) || (dayobj.getDate() != dayfield) || (dayobj.getFullYear() != yearfield)) {
            //alert("Invalid Day, Month, or Year range detected. Please correct and submit again.")
            return false;
        }
        else {
            return true;
        }
    }
}

function isTimeOK(timeStr) {
    // Checks if time is in HH:MM:SS AM/PM format.
    // The seconds and AM/PM are optional.
    var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?document.getElementById/;

    var matchArray = timeStr.match(timePat);
    if (matchArray == null) {
        return false;
    }
    hour = matchArray[1];
    minute = matchArray[2];
    second = matchArray[4];
    ampm = matchArray[6];

    if (second == "") { second = null; }
    if (ampm == "") { ampm = null }

    if (hour < 0 || hour > 23) {
        return false;
    }
    if (hour <= 12 && ampm == null) {
        return false;
        //if (confirm("Please indicate which time format you are using.  OK = Standard Time, CANCEL = Military Time")) {
        //    alert("You must specify AM or PM.");
        //    return false;
        //}
    }
    if (hour > 12 && ampm != null) {
        alert("You can't specify AM or PM for military time.");
        return false;
    }
    if (minute < 0 || minute > 59) {
        //alert("Minute must be between 0 and 59.");
        return false;
    }
    if (second != null && (second < 0 || second > 59)) {
        return false;
    }
    return true;
}
