/*$Id: ds.js 6466 2007-01-28 12:15:09Z naimdjon $*/
var selectorDivID = "datepicker";
var iFrameDivID = "datepickeriframe";
var defaultSeparator = "/";
var defaultFormat = "dmy" 
var dateSeparator = defaultSeparator;
var dateFormat = defaultFormat;
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=2005;
var maxYear=2010;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   }
   return this
}

function isDate(dtStr){
    var daysInMonth = DaysArray(12)
    var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		//alert("The date format should be : mm/dd/yyyy")
        alert(document.getElementById("errorDateFormat").value);
        return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		//alert("Please enter a valid month")
        alert(document.getElementById("errorEnterValidMonth").value);
        return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		//alert("Please enter a valid day")
        alert(document.getElementById("errorDateDay").value);
        return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		//alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
        alert(document.getElementById("errorDateYear").value);
        return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		//alert("Please enter a valid date")
        alert(document.getElementById("errorDateIncorrectFormat").value);
        return false
	}
return true
}

function validDate(theForm,inputName){
	var dt=theForm.elements[inputName];
	if (isDate(dt.value)==false){
		dt.focus()
        return false
	}
    return true
 }

function isValidDate(dt){
	if (isDate(dt.value)==false){
		dt.focus()
        return false
	}
    return true
 }

function stringToDate(theStr){
    var date = theStr.substr(0,2);
    var month = theStr.substr(3,2)-1;
    var year = theStr.substr(6,4);
    d= new Date();
    d.setFullYear(year,month, date);
    return d;
}

function displayDateSelector(dateFieldName, displayBelowThisObject, dtFormat, dtSep,from){
  var targetDateField = document.getElementsByName (dateFieldName).item(0);
  if (!displayBelowThisObject)
    displayBelowThisObject = targetDateField;
  if (dtSep)
    dateSeparator = dtSep;
  else
    dateSeparator = defaultSeparator;
  if (dtFormat)
    dateFormat = dtFormat;
  else
    dateFormat = defaultFormat;
    var fromdate;
    if(from){
        fromdate=from;
    }else  {
        from =document.getElementById(from);
    }
    if(!fromdate)
        fromdate=targetDateField;
    //get the x and y
  var x = displayBelowThisObject.offsetLeft;
  var y = displayBelowThisObject.offsetTop + displayBelowThisObject.offsetHeight ;
  var parent = displayBelowThisObject;
  while (parent.offsetParent) {
    parent = parent.offsetParent;
    x += parent.offsetLeft;
    y += parent.offsetTop ;
  }
  drawSelectDate(targetDateField, x, y,fromdate);
}


function drawSelectDate(targetDateField, x, y,fromdate){
   var dt;
  if(fromdate)
	if(fromdate.value) dt = getFieldDate(fromdate.value );
	else dt = getFieldDate(fromdate);
  else
    dt = getFieldDate(targetDateField.value );

  if (!document.getElementById(selectorDivID)) {
    var newNode = document.createElement("div");
    newNode.setAttribute("id", selectorDivID);
    newNode.setAttribute("class", "dpDiv");
    newNode.setAttribute("style", "visibility: hidden;");
    document.body.appendChild(newNode);
  }
  var pickerDiv = document.getElementById(selectorDivID);
  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;
  refreshTable(targetDateField.name, dt.getFullYear(), dt.getMonth(), dt.getDate());
}

function refreshTable(dateFieldName, year, month, day, chosenFromDate){
    var dt = new Date();
  var chosenDate = document.getElementsByName(dateFieldName)[0].value;
	//if (chosenDate) dt = stringToDate(chosenDate);
	if (chosenFromDate) dt = stringToDate(chosenFromDate);
	else dt = new Date(year,month,day);
  var thisDay = new Date();
  if ((month >= 0) && (year > 0)) {
    thisDay = new Date(year, month, 1);
  } else {
    day = thisDay.getDate();
    thisDay.setDate(1);
  }
  //alert(dateFieldName);
  //if (isDate(targetDateField.value)) day = targetDateField.value.substr(0,2);
  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\";' ";
  var TDWrong = "<td class='dpTD' style='text-decoration: line-through;color:gray;'>";
  var TD_title = "<td colspan=4 class='dpTitleTD'>";
  var TD_buttons = "<td class='dpButtonTD'>";
  var TD_todaybutton = "<td colspan=7 class='dpTodayButtonTD'>";
  var TD_days = "<td align=center class='dpDayTD'>";
  var TD_selected = "<td class='dpDayHighlightTD' onMouseOut='this.className=\"dpDayHighlightTD\";' onMouseOver='this.className=\"dpTDHover\";' ";    
  var xTD = "</td>" + crlf;
  var DIV_title = "<div class='dpTitleText'>";
  var DIV_selected = "<div class='dpDayHighlight'>";
  var xDIV = "</div>";

  var html = TABLE;
  html += TR_title;
  html += TD_buttons + getButtonCode(dateFieldName, thisDay, -1, "&lt;", dt) + xTD;
  html += TD_title + DIV_title + monthArrayLong[ thisDay.getMonth()] + " " + thisDay.getFullYear() + xDIV + xTD;
  html += TD_buttons + getButtonCode(dateFieldName, thisDay, 1, "&gt;", dt) + xTD;
  html += TD_buttons + getCloseBtn(dateFieldName ) + xTD;
  html += xTR;
  html += TR_days;
  //html += "<tr><td colspan=7><table bgcolor=#cccccc width=100%><tr>";
  for(i = 0; i < dayArrayShort.length; i++)
    html += TD_days + dayArrayShort[i] + xTD;
  //html += "</tr></table></td></tr>";
  html += xTR;

  html += TR;
    //had problems arranging dates saturday, sunday at the end, because the sunday is 0 in javascript
    //for (i = 0; i < thisDay.getDay()-1; i++)
    var iter=thisDay.getDay();
    if(iter==0)iter=7;
  for (i = 0; i < iter-1; i++)
    html += TD + "&nbsp;" + xTD;

  do {
    dayNum = thisDay.getDate();
    TD_onclick = " onclick=\"updateDateField('" + dateFieldName + "', '" + getDateString(thisDay) + "');\">";
	//alert('dayNum: '+dayNum+'\nday: '+day+'\nthisDay: '+thisDay+'\ndt: '+dt+'\nnewDate: '+new Date()+'\nchosenDate: '+chosenDate);
	//alert('thisDay: '+getDateString(thisDay)+'\nchosenDate: '+chosenDate);
	/* if ((dayNum == day) && (!(chosenDate) || (chosenDate == "dd/mm/yyyy")))
		html += TD_selected + TD_onclick + DIV_selected + dayNum + xDIV + xTD;
    else if (getDateString(thisDay) == chosenDate) */
	if (dayNum == day)
		html += TD_selected + TD_onclick + DIV_selected + dayNum + xDIV + xTD;
    else if( thisDay < dt)
        html += TDWrong  + dayNum + xTD;
    else if( thisDay < new Date())
        html += TDWrong  + dayNum + xTD;
/* 	else if( thisDay < chosenFromDate )
        html += TDWrong  + dayNum + xTD; */
    else
		html += TD + TD_onclick + dayNum + xTD;

    if (thisDay.getDay()==0)
    {
      html += xTR + TR;
    }

    thisDay.setDate(thisDay.getDate() + 1);
  } while (thisDay.getDate() > 1)

  if (thisDay.getDay() > 0) {
    for (i = 8; i > thisDay.getDay(); i--)
      html += TD + "&nbsp; " + xTD;
  }
  html += xTR;

  var today = new Date();
  html += TR_todaybutton + TD_todaybutton;
  html += "<button class='dpTodayButton' onClick='refreshTable(\"" + dateFieldName + "\");'>"+thisMonth+"</button> ";
  html += xTD + xTR;

  html += xTABLE;
  document.getElementById(selectorDivID).innerHTML = html;
  adjustiFrame();
  
}

function getButtonCode(dateFieldName, dateVal, adjust, label, chosenFromDate){
  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='refreshTable(\"" + dateFieldName + "\", " + newYear + ", " + newMonth + ", " + null + ", \"" + getDateString(chosenFromDate) + "\");'>" + label + "</button>";
}

function getCloseBtn(dateFieldName){
  return "<button class='dpButtonClose' onClick='updateDateField(\"" + dateFieldName + "\");'>x</button>";
}


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

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;
}


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;
}

function updateDateField(dateFieldName, dateString)
{
  var targetDateField = document.getElementsByName (dateFieldName).item(0);
  if (dateString)
    targetDateField.value = dateString;

  var pickerDiv = document.getElementById(selectorDivID);
  pickerDiv.style.visibility = "hidden";
  pickerDiv.style.display = "none";

  adjustiFrame();
  targetDateField.focus();

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

function adjustiFrame(pickerDiv, iFrameDiv)
{
    // not possible for opera.
  var is_opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
  if (is_opera)
    return;

  try {
    if (!document.getElementById(iFrameDivID)) {
      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(selectorDivID);
    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) {
  }

}
