var obj;
var pageXpos;
var pageYpos;


if (document.layers) document.captureEvents(Event.MOUSEMOVE);
document.onMouseDown=mtrack;

function mtrack(e) {
    if (document.layers) {
        // When the page scrolls in Netscape, the event's mouse position
        // reflects the absolute position on the screen. innerHight/Width
        // is the position from the top/left of the screen that the user is
        // looking at. pageX/YOffset is the amount that the user has 
        // scrolled into the page. So the values will be in relation to
        // each other as the total offsets into the page, no matter if
        // the user has scrolled or not.
        pageXpos = e.pageX;
        pageYpos = e.pageY;
        pageXposMax = window.innerWidth+window.pageXOffset;
        pageYposMax = window.innerHeight+window.pageYOffset;
    } else if (document.all) {
        // When the page scrolls in IE, the event's mouse position 
        // reflects the position from the top/left of the screen the 
        // user is looking at. scrollLeft/Top is the amount the user
        // has scrolled into the page. clientWidth/Height is the height/
        // width of the current page the user is looking at. So, to be
        // consistent with Netscape (above), add the scroll offsets to
        // both so we end up with an absolute value on the page, no 
        // matter if the user has scrolled or not.
        pageXpos = window.event.x+document.body.scrollLeft;
        pageYpos = window.event.y+document.body.scrollTop;
        pageXposMax = document.body.clientWidth+document.body.scrollLeft;
        pageYposMax = document.body.clientHeight+document.body.scrollTop;
    } else if (document.getElementById) {
        // Netscape 6 behaves the same as Netscape 4 in this regard 
        pageXpos = e.pageX;
        pageYpos = e.pageY;
        pageXposMax = window.innerWidth+window.pageXOffset;
        pageYposMax = window.innerHeight+window.pageYOffset;
    }
}
/**
 * calendar variables/functions
 */
var PopupWindow = null;
var calendarColors = new Array();
calendarColors['dateBgColor'] = '#FFFFFF';
calendarColors['dateTextColor'] = '#000000';
calendarColors['dateHoverBgColor'] = '#0C1757';
calendarColors['dateHoverTextColor'] = '#FFFFFF';
calendarColors['dateSelectedBgColor'] = '#B8C9E5';
calendarColors['dateSelectedTextColor'] = '#FFFFFF';

var calendarFormat = 'm/d/y';

// if you want the calendar to start on Monday, set below statement to true;
var calendarStartMonday = false;

function openDatePopup(formField) {

  if(document.all){
      fieldobjname = formField;
      mtrack();
      showCal();
  }
  else if (document.layers) {
    calendarTarget = formField;
    PopupWindow = window.open('puFinderDate.html', 'Popup','width=214,height=215,top=150,left=150,screenX=150,screenY=150,resizable=0,scrollbars=0');
    PopupWindow.focus();
    PopupWindow.resizeTo('214','215');
    return false;
    }
    else if (document.getElementById){
    //***** This is used to show the calendar in Firefox ******
    calendarTarget = formField;
    PopupWindow = window.open('puFinderDate.html', 'Popup','width=214,height=290,top=150,left=150,screenX=150,screenY=150,resizable=0,scrollbars=0');
    PopupWindow.focus();
    PopupWindow.resizeTo('214','290');
    return false;
    }
}

function showCal() {
var browserName=navigator.appName;
if (browserName=="Microsoft Internet Explorer")
{
     document.getElementById("calback").style.visibility="visible";
     document.getElementById("LayerCal").style.visibility="visible";

     //int posx = document.all.fieldobjname.Xpos;
     //alert("position = " + posx);
     if (currentRowNo > 5)
     {
	 document.getElementById("LayerCal").style.top = pageYpos - 133 ;
	 document.getElementById("LayerCal").style.left = pageXpos - 103;
	 document.getElementById("calback").style.top = pageYpos - 140 ;
	 document.getElementById("calback").style.left = pageXpos -111;     
     }
     else
     {
	 document.getElementById("LayerCal").style.top = pageYpos - 23 ;
	 document.getElementById("LayerCal").style.left = pageXpos - 103;
	 document.getElementById("calback").style.top = pageYpos - 30 ;
	 document.getElementById("calback").style.left = pageXpos -111;
     }	 



	if (!document.styleSheets) return;
	var theRules = new Array();
	if (document.styleSheets[0].cssRules)
		theRules = document.styleSheets[1].cssRules
	else if (document.styleSheets[0].rules)
		theRules = document.styleSheets[1].rules
	else return

	//alert("current color = " + theRules[4].style.color);
	theRules[4].style.border = '1px solid #000000';
	//alert("current border = " + theRules[4].style.border);
	//if (confirm('Also try setProperty?'))
	//document.styleSheets[1].cssRules[4].style.setProperty('border','0px solid #000000',null);

}
else
{
if (browserName=="Netscape") {
    document.getElementById("calback").visibility="visible";
    document.getElementById("LayerCal").visibility="visible";
}
else
  {
   }
   }
}
function hideCal() {
  var browserName=navigator.appName;
  if (browserName=="Microsoft Internet Explorer")
  {
     document.getElementById("calback").style.visibility="hidden";
     document.getElementById("LayerCal").style.visibility="hidden";
  }
  else
  {
    if (browserName=="Netscape") {
      document.getElementById("calback").visibility="hidden";
      document.getElementById("LayerCal").visibility="hidden";
      }
    else
      {
      }
   }
}

var targetDate = new Date();
var fieldobjname ;

/**
 * Current Row.
 */
var currentRowNo = 0;

/**
 * Allow insert flag
 */ 
var allowInsert = 1;

/**
 * Validate Date Ranges
 */

function days_between(date1,date2) {
  var ONE_DAY = 1000 * 60 * 60 * 24
  var date1_ms = date1.getTime();
  var date2_ms = date2.getTime();

  var difference_ms = Math.abs(date1_ms - date2_ms)

  return Math.round(difference_ms/ONE_DAY)
}

function storeRowNo(rowNumber)
{
currentRowNo = rowNumber;

}


function validateDateRangesRates(rowNumber,saveFlag)
{
  var targetForm = document.forms["fwForm"] ;
  var testVar = 0 ;
  var testVar2 = 0 ;
  var rowNo = 0;
  var validRow = 0;
  var validPrior = 0;
  var currentRowDateTo;
  var currentRowDateFrom;
  var currentRowDateToElement = 0;
  var currentRowDateFromElement = 0;
  var priorDateElement = 0;
  var currentDateElement = 0;
  var weeklyFieldElement = 0;
  var monthlyFieldElement = 0;
  var daysBetweenDates = 0;
   //alert("validating date range");
 if (currentRowNo < 1) {
   rowNo = parseInt(document.fwForm.elements["fwRowCount"].value);
   currentRowNo = rowNo;
   }

  //check current rows date range.
  //alert("row no = " + currentRowNo + " new calendar4");
  currentRowDateFromElement = (currentRowNo * 10) + 3;
  currentRowDateToElement = (currentRowNo * 10) + 4;
  currentRowDateFrom = new Date(targetForm.elements[currentRowDateFromElement].value);
  currentRowDateTo = new Date(targetForm.elements[currentRowDateToElement].value);
    //alert("form value = " + currentRowDateFrom + " form value 2 = " + currentRowDateTo);
    if (currentRowDateFrom > currentRowDateTo) {
       alert("The Start date cannot be greater than the End date. Please correct.");
       allowInsert = 0;
       return;
    }  
    else {
      validRow = 1;
      }
 
  
  if (currentRowNo > 1) {
  /* Get the prior date element.*/
    priorDateElement = ((currentRowNo - 1) * 10) + 4;
    currentDateElement = (currentRowNo * 10) + 3;
    testVar = new Date(targetForm.elements[priorDateElement].value);
    testVar2 = new Date(targetForm.elements[currentDateElement].value);
    if (testVar >= testVar2) {
       alert("You have entered a date range that is prior to the previous date range entered. Please correct.");
       allowInsert = 0;
       return;
    }
    else {
      validPrior = 1;
      }
    if (saveFlag == true)
     {
       //alert("save = true");
       saveUpdatedRatesAndDates(rowNumber);
     }      
    if ( validPrior == 1 && validRow == 1 && saveFlag != true) {
         //set allowInsert back to 1
         allowInsert = 1;
         //alert("going to insert record");
         doTableEditNewOnClick('dsRatesDetail');
         }
  //alert("form value = " + testVar + " form value 2 = " + testVar2);
  }
  else
  {
    if (saveFlag == true)
    {
       //alert("save = true");
       saveUpdatedRatesAndDates(rowNumber);
     }  
    if (validRow == 1) {
      //alert("- going to insert record");
      doTableEditNewOnClick('dsRatesDetail');
      }
  }
  

}//function validateDateRangesRates()

// Initialize the calendar display once the page loads.

//window.onload = setCalendar;

//----------------------------------------------------------------------------
// This function updates the calendar display to reflect the current target
// date.
//----------------------------------------------------------------------------

function setCalendar(event) {

  var el, tableEl, rowEl, cellEl, linkEl;
  var tmpDate, tmpDate2;
  var i, j;
  //alert("setting calendar " );

  // Update month name.

  el = document.getElementById("calendarHeader").firstChild;
  el.nodeValue = targetDate.getMonthName() + "\u00a0" + targetDate.getFullYear();

  // Start with the first day of the month and go back if necessary to
  // the previous Sunday.

  tmpDate = new Date(Date.parse(targetDate));
  tmpDate.setDate(1);
  while (tmpDate.getDay() != 0) {
    tmpDate.addDays(-1);
  }

  // Go through each calendar day cell in the table and update it.

  tableEl = document.getElementById("calendar");
  for (i = 2; i <= 7; i++) {
    rowEl = tableEl.rows[i];

    // Hide row if it contains no dates in the current month.

    tmpDate2 = new Date(Date.parse(tmpDate));
    tmpDate2.addDays(6);
    if (tmpDate.getMonth()  != targetDate.getMonth() &&
        tmpDate2.getMonth() != targetDate.getMonth()) {
      rowEl.style.visibility = "hidden";
      if (document.all)
        for (j = 0; j < rowEl.cells.length; j++)
          rowEl.cells[j].style.borderStyle = "none";
    }
    else {
      rowEl.style.visibility = "";
      if (document.all)
        for (j = 0; j < rowEl.cells.length; j++)
          rowEl.cells[j].style.borderStyle = "";
    }

    // Loop through a week.

    for (j = 0; j < rowEl.cells.length; j++) {
      cellEl = rowEl.cells[j];
      linkEl = cellEl.firstChild;

      if (tmpDate.getMonth() == targetDate.getMonth()) {
        linkEl.date = new Date(Date.parse(tmpDate));
        s = tmpDate.toString().split(" ");
        linkEl.title = s[0] + " " + s[1] + " " + s[2] + ", " + s[s.length - 1];
        linkEl.firstChild.nodeValue = tmpDate.getDate();
        linkEl.style.visibility = "";
      }
      else
        linkEl.style.visibility = "hidden";

      // Highlight the current date.

      if (cellEl.oldClass == null)
        cellEl.oldClass = cellEl.className;
      if (Date.parse(tmpDate) == Date.parse(targetDate))
        cellEl.className = cellEl.oldClass + " target";
      else
        cellEl.className = cellEl.oldClass;

        //datefield2.value = formatDate(targetDate);


      // Go to the next day.

      tmpDate.addDays(1);
    }
  }
}

//----------------------------------------------------------------------------
// Event handlers for the calendar elements.
//----------------------------------------------------------------------------

function addMonths(event, n) {

  // Advance the calendar month and update the display.

  targetDate.addMonths(n);
  setCalendar(event);
}

function addYears(event, n) {

  // Advance the calendar year and update the display.

  targetDate.addYears(n);
  setCalendar(event);
}

function setTargetDate(event, link) {

  // Change the target date and update the calendar.

  if (link.date != null) {
    targetDate = new Date(Date.parse(link.date));
    setCalendar(event);
    //window.close();
    fieldobjname.value = formatDate(targetDate);
    doFWInputOnChange(fieldobjname);
    hideCal();
    //disableFields();
  }
}

function displayDate(event) {

  // Display the current target date as a formatted string.

  //alert(formatDate(targetDate));CHAD
    setCalendar(event);
    //window.close();
    fieldobjname.value = formatDate(targetDate);
    doFWInputOnChange(fieldobjname);
    hideCal();  

}
function popupcalendar(fieldobj) {

  // Display the current target date as a formatted string.
  // window.open('testcalendar2.htm','newWin','width=400,height=400');
  //alert("test");
  fieldobjname = fieldobj;
  mtrack();
  showCal();

}

function formatDate() {

  var mm, dd, yyyy;

  // Return the target date in "mm/dd/yyyy" format.

  mm = String(targetDate.getMonth() + 1);
  while (mm.length < 2)
    mm = "0" + mm;
  dd = String(targetDate.getDate());
  while (dd.length < 2)
    dd = "0" + dd;
  yyyy = String(targetDate.getFullYear());
  while (yyyy.length < 4)
    yyyy = "0" + yyyy;

  return mm + "/" + dd + "/" + yyyy;
  //return yyyy+"-"+mm+"-"+dd;
}

//============================================================================
// Add new properties and methods to the Date object.
//============================================================================

// Properties

Date.prototype.monthNames = new Array("January", "February", "March", "April",
  "May", "June", "July", "August", "September", "October", "November",
  "December");
Date.prototype.savedDate  = null;

// Methods

Date.prototype.getMonthName = dateGetMonthName;
Date.prototype.getDays      = dateGetDays;
Date.prototype.addDays      = dateAddDays;
Date.prototype.addMonths    = dateAddMonths;
Date.prototype.addYears     = dateAddYears;

//----------------------------------------------------------------------------
// getMonthName(): Returns the name of the date's month.
//----------------------------------------------------------------------------

function dateGetMonthName() {

  return this.monthNames[this.getMonth()];
}

//----------------------------------------------------------------------------
// getDays(): Returns the number of days in the date's month.
//----------------------------------------------------------------------------

function dateGetDays() {

  var tmpDate, d, m;

  tmpDate = new Date(Date.parse(this));
  m = tmpDate.getMonth();
  d = 28;
  do {
    d++;
    tmpDate.setDate(d);
  } while (tmpDate.getMonth() == m);

  return d - 1;
}

//----------------------------------------------------------------------------
// addDays(n): Adds the specified number of days to the date.
//----------------------------------------------------------------------------

function dateAddDays(n) {

  // Add the specified number of days.

  this.setDate(this.getDate() + n);

  // Reset the new day of month.

  this.savedDate = this.getDate();
}
function test() {

  alert("test");
}

//----------------------------------------------------------------------------
// addMonths(n): Adds the specified number of months to the date, adjusting
// the day of the month if necessary.
//----------------------------------------------------------------------------

function dateAddMonths(n) {

  // Save the day of month if not already set.

  if (this.savedDate == null)
    this.savedDate = this.getDate();

  // Set the day of month to the first to avoid rolling.

  this.setDate(1);

  // Add the specified number of months.

  this.setMonth(this.getMonth() + n);

  // Restore the saved day of month, if possible.

  this.setDate(Math.min(this.savedDate, this.getDays()));
}

//----------------------------------------------------------------------------
// addYears(n): Adds the specified number of years to the date, adjusting the
// day of the month for leap years.
//----------------------------------------------------------------------------

function dateAddYears(n) {

  // Save the day of month if not already set.

  if (this.savedDate == null)
    this.savedDate = this.getDate();

  // Set the day of month to the first to avoid rolling.

  this.setDate(1);

  // Add the specified number of years.

  this.setFullYear(this.getFullYear() + n);

  // Restore the saved day of month, if possible.

  this.setDate(Math.min(this.savedDate, this.getDays()));
}


