var dDate = new Date();
var dCurMonth = dDate.getMonth();
var dCurDayOfMonth = dDate.getDate();
var dCurYear = dDate.getFullYear();
var objPrevElement = new Object();
var bgcolor;
var webgcolor;
var wecolor;
var nwecolor;
var tbgcolor;
var ntbgcolor;
var sbgcolor;
var click;
var mouseover;
var mouseout;
var present;
//var presentClick = 0;

function _onloadCalendar()
{
  var dCurDate = new Date();

  var month_value = "";
  var year_value = "";
  if(document.getElementById('month_value') != null)
    month_value= document.getElementById('month_value').value;
  if(document.getElementById('year_value') != null)
    year_value= document.getElementById('year_value').value;

  if((document.getElementById('tbSelMonth') != null) && (dCurDate.getMonth() == (month_value - 1) ||  month_value == "")) // тот же месяц
    document.getElementById('tbSelMonth').options[dCurDate.getMonth()].selected = true;
  else if(document.getElementById('tbSelMonth') != null) // другой месяц
    document.getElementById('tbSelMonth').options[(month_value - 1)].selected = true;

  if((document.getElementById('tbSelYear') != null) && (dCurDate.getFullYear() == year_value ||  year_value == "")) // тот же год
  {
    for (i = 0; i < document.getElementById('tbSelYear').length; i++)
      if (document.getElementById('tbSelYear').options[i].value == dCurDate.getFullYear())
        document.getElementById('tbSelYear').options[i].selected = true;
  }
  else if(document.getElementById('tbSelYear') != null)// другой год
  {
    for (i = 0; i < document.getElementById('tbSelYear').length; i++)
      if (document.getElementById('tbSelYear').options[i].value == year_value)
        document.getElementById('tbSelYear').options[i].selected = true;
  }
//  document.all.calSelectedDate.value = "";
  if(month_value  && year_value ) // не первая загрузка
    fUpdateCal(year_value, month_value, 1);
  if(document.getElementById('date_value') != null && document.getElementById('date_value').value) // если даты нет(начальная загрузка) - подставим текущую
    document.getElementById('date').value = document.getElementById('date_value').value;
  else if(document.getElementById('date_value') != null && document.getElementById('tbSelMonth') != null && document.getElementById('tbSelYear') != null)
    document.getElementById('date').value = dCurDate.getDate() + " " +
        document.getElementById('tbSelMonth').options[document.getElementById('tbSelMonth').selectedIndex].text +
        " " + document.getElementById('tbSelYear').value;
}

function fGetDaysInMonth(iMonth, iYear)
{
  var dPrevDate = new Date(iYear, iMonth, 0);
  return dPrevDate.getDate();
}

function fBuildCal(iYear, iMonth, iDayStyle)
{
  var aMonth = new Array();
  aMonth[0] = new Array(7);
  aMonth[1] = new Array(7);
  aMonth[2] = new Array(7);
  aMonth[3] = new Array(7);
  aMonth[4] = new Array(7);
  aMonth[5] = new Array(7);
  aMonth[6] = new Array(7);
  var dCalDate = new Date(iYear, iMonth-1, 1);
  var iDayOfFirst = dCalDate.getDay();
  var iDaysInMonth = fGetDaysInMonth(iMonth, iYear);
  var iVarDate = 1;
  var i, d, w;
  if (iDayOfFirst==0)
  {
    iDayOfFirst=6
  }
  else
  {
    iDayOfFirst=iDayOfFirst-1
  }
  if (iDayStyle == null)
  {
    aMonth[0][0] = "Пн";
    aMonth[0][1] = "Вт";
    aMonth[0][2] = "Ср";
    aMonth[0][3] = "Чт";
    aMonth[0][4] = "Пт";
    aMonth[0][5] = "Сб";
    aMonth[0][6] = "Вс";
  }
   else
   {
      aMonth[0][0] = iDayStyle[0].value;
      aMonth[0][1] = iDayStyle[1].value;
      aMonth[0][2] = iDayStyle[2].value;
      aMonth[0][3] = iDayStyle[3].value;
      aMonth[0][4] = iDayStyle[4].value;
      aMonth[0][5] = iDayStyle[5].value;
      aMonth[0][6] = iDayStyle[6].value;
   }

  for (d = iDayOfFirst; d < 7; d++)
  {
    aMonth[1][d] = iVarDate;
    iVarDate++;
  }
  for (w = 2; w < 7; w++)
  {
    for (d = 0; d < 7; d++)
    {
      if (iVarDate <= iDaysInMonth)
      {
        aMonth[w][d] = iVarDate;
        iVarDate++;
      }
    }
  }
  return aMonth;
}

function fDrawCal(iYear, iMonth, iCellWidth, iCellHeight, sDateTextSize, sDateTextWeight, iDayStyle, ibgcolor, iwebgcolor, inwecolor, iwecolor, itbgcolor, intbgcolor, isbgcolor)
{

//  bgcolor = '#4682B4';
  bgcolor = 'rgb(70,130,180)';// фон ячейки с заголовками таблицы

  webgcolor = iwebgcolor;
  wecolor = iwecolor;
  nwecolor = inwecolor;

  tbgcolor1 = '#00FFFF';
  tbgcolor = 'rgb(0,255,255)';// фон ячеки с текущей датой

//  ntbgcolor = '#F1F1F1';
  ntbgcolor = 'rgb(241,241,241)'; // фон ячеек с числами

//  sbgcolor = '#B0C4DE';
  sbgcolor = 'rgb(176,196,222)'; // фон ячейки когда на ней кликнули

  iCellWidth = '23px';
  iCellHeight = '10px';
  sDateTextWeight = 'normal';
  sDateTextSize = '11px';

  var myMonth;
  myMonth = fBuildCal(iYear, iMonth, iDayStyle);
  //var clicked = document.getElementById('calSelectedDate').value;

  document.write("<table id='calendar' cellspacing='1px' style='border: thin solid #4682B4;background-color: Silver;'>")
  document.write("<tr>");
  document.write("<td align='center' style='BACKGROUND-COLOR:"+ bgcolor +";FONT-FAMILY:Arial;FONT-SIZE:12px;FONT-WEIGHT:bold;COLOR:"+ nwecolor +"'>" + myMonth[0][0] + "</td>");
  document.write("<td align='center' style='BACKGROUND-COLOR:"+ bgcolor +";FONT-FAMILY:Arial;FONT-SIZE:12px;FONT-WEIGHT:bold;COLOR:"+ nwecolor +"'>" + myMonth[0][1] + "</td>");
  document.write("<td align='center' style='BACKGROUND-COLOR:"+ bgcolor +";FONT-FAMILY:Arial;FONT-SIZE:12px;FONT-WEIGHT:bold;COLOR:"+ nwecolor +"'>" + myMonth[0][2] + "</td>");
  document.write("<td align='center' style='BACKGROUND-COLOR:"+ bgcolor +";FONT-FAMILY:Arial;FONT-SIZE:12px;FONT-WEIGHT:bold;COLOR:"+ nwecolor +"'>" + myMonth[0][3] + "</td>");
  document.write("<td align='center' style='BACKGROUND-COLOR:"+ bgcolor +";FONT-FAMILY:Arial;FONT-SIZE:12px;FONT-WEIGHT:bold;COLOR:"+ nwecolor +"'>" + myMonth[0][4] + "</td>");
  document.write("<td align='center' style='BACKGROUND-COLOR:"+ bgcolor +";FONT-FAMILY:Arial;FONT-SIZE:12px;FONT-WEIGHT:bold;COLOR:"+ wecolor +"'>" + myMonth[0][5] + "</td>");
  document.write("<td align='center' style='BACKGROUND-COLOR:"+ bgcolor +";FONT-FAMILY:Arial;FONT-SIZE:12px;FONT-WEIGHT:bold;COLOR:"+ wecolor +"'>" + myMonth[0][6] + "</td>");
  document.write("</tr>");
  for (w = 1; w < 7; w++)
  {
    document.write("<tr>")
    for (d = 0; d < 7; d++)
    {
      if (myMonth[w][d] == dCurDayOfMonth && !isNaN(myMonth[w][d])) /// текущая дата
      {
        document.write("<td id='calCell' align='center' valign='center' width='" + iCellWidth +
        "' height='" + iCellHeight + "' style='cursor:pointer;FONT-FAMILY:Arial;FONT-SIZE:" + sDateTextSize + ";FONT-WEIGHT:" +
        sDateTextWeight + ";background:" + ntbgcolor + "' >"
        + "<div style='background-color:" + tbgcolor + "; color:black; width:100%; cursor:pointer'  " +
        "onMouseOver='fToggleColor(event)' onMouseOut='fToggleColor(event)' onclick='fSetSelectedDay(event)'>" + myMonth[w][d] + " </div>");
      }
      else if (!isNaN(myMonth[w][d])) // даты календаря
      {
        var numbers;
        if(d == 5 || d == 6 )
          numbers = "<div style='background-color:" + ntbgcolor + "; color:red; width:100%; cursor:pointer' onMouseOver='fToggleColor(event)' onMouseOut='fToggleColor(event)' onclick='fSetSelectedDay(event)'>" + myMonth[w][d] + " </div>"; // подсветим красным субботу и воскресенье
        else
          numbers = "<div style='background-color:" + ntbgcolor + "; color:black; width:100%; cursor:pointer' onMouseOver='fToggleColor(event)' onMouseOut='fToggleColor(event)' onclick='fSetSelectedDay(event)'>" + myMonth[w][d] + " </div>";
        document.write("<td id='calCell' align='center' valign='center' width='" + iCellWidth +
        "' height='" + iCellHeight + "' style='cursor:pointer;FONT-FAMILY:Arial;FONT-SIZE:" + sDateTextSize + ";FONT-WEIGHT:" +
        sDateTextWeight + ";background:" + ntbgcolor + "'>"
        + numbers);
      }
      else // пустые ячейки
      {
        document.write("<td id='calCell' align='center' valign='center' width='" + iCellWidth + "' height='" +
        iCellHeight + "' style='FONT-FAMILY:Arial; FONT-SIZE:" + sDateTextSize + ";FONT-WEIGHT:" +
        sDateTextWeight + ";background:White'>" + "<div style='background-color:White; width:100%; cursor:default'></div>");
      }
      document.write("</td>")
    }
    document.write("</tr>");
  }
  document.write("</table>");
}

function fToggleColor(evt)
{
  evt = (evt) ? evt : ((window.event) ? window.event : null);
  if(evt)
  {
    var myElement = (evt.target) ? evt.target : evt.srcElement;
    if(evt.type.toUpperCase() == 'MOUSEOVER')
    {
      bkground = myElement.style.backgroundColor.toUpperCase();
      if(bkground.indexOf('#') == -1) // ie, firefox
      {
        var colors_new = bkground.substring(4, bkground.length - 1).split(','); // выделим цвета
        var colors_old = tbgcolor.toUpperCase().substring(4, tbgcolor.length - 1).split(','); // выделим цвета
        if(colors_new[0] == colors_old[0] && colors_new[1].replace(' ', '') == colors_old[1] && colors_new[2].replace(' ', '') == colors_old[2] )
          present = 1; // текущее число
        else
          present = 0; // не текущее число
      }
      else // opera
      {
        if(bkground == tbgcolor1)
          present = 1; // текущее число
        else
          present = 0; // не текущее число
      }
      myElement.style.background = 'Lime';
    }
    else if (evt.type.toUpperCase() == 'MOUSEOUT')
    {
      if(present == 0)
        myElement.style.background = ntbgcolor;
      else
        myElement.style.background = tbgcolor; // текущее число
    }
//    evt.cancelBubble = true;
  }
}

function fSetSelectedDay(evt)
{
  evt = (evt) ? evt : ((window.event) ? window.event : null);
  if(evt)
  {
    var myElement = (evt.target) ? evt.target : evt.srcElement; // div элемент
    if (myElement.parentNode.id == "calCell")
    {
      if (!isNaN(parseInt(myElement.childNodes[0].nodeValue)) ) // ячейка со значением
      {
        myElement.style.background = sbgcolor;
        myElement.onmouseover = function(){return false}; // если кликнули на элементе, эти события уже не нужны
        myElement.onmouseout = function(){return false};
        myElement.onclick = function(){return false};
        myElement.style.cursor = 'default';
        myElement.parentNode.style.cursor = 'default';
        if( typeof objPrevElement.id != 'undefined' )
        {
          if(objPrevElement.present == 0)
            objPrevElement.style.background = ntbgcolor;
          else
            // был щелчек на элементе сегодняшнего дня
            objPrevElement.style.background = tbgcolor;

          objPrevElement.present = 0;
          objPrevElement.onmouseover = fToggleColor; // вернем все как было на елементе, на котором кликнули раньше
          objPrevElement.onmouseout = fToggleColor;
          objPrevElement.onclick = fSetSelectedDay;
          objPrevElement.style.cursor = 'pointer';
          objPrevElement.parentNode.style.cursor = 'pointer';
        }
        if(document.getElementById('calSelectedDate') != null)
          document.getElementById('calSelectedDate').value = myElement.childNodes[0].nodeValue;
        if(present == 1)
        {
          myElement.present = 1;// кликнули по текущему числу
          if (document.getElementById('cur_day_clicked') != null)
            document.getElementById('cur_day_clicked').value = 1;
        }
        else
        {
          myElement.present = 0;
          if (document.getElementById('cur_day_clicked') != null)
            document.getElementById('cur_day_clicked').value = 0;
        }

        objPrevElement = myElement;
      }
      // в выпадающем календаре подставим дату в поле
      document.getElementById('date').value = myElement.childNodes[0].nodeValue + " " +
        document.getElementById('tbSelMonth').options[document.getElementById('tbSelMonth').selectedIndex].text +
        " " + document.getElementById('tbSelYear').value;
      //document.getElementById('checked').checked = 'checked';
      _drawHidden('cal');
    }
  }
}

function fUpdateCal(iYear, iMonth, param)
{
  myMonth = fBuildCal(iYear, iMonth);
  var selectedDate = '';
  if (document.getElementById('calSelectedDate') != null)
    selectedDate = document.getElementById('calSelectedDate').value;
  objPrevElement = new Object(); // обнулим знчения объекта
  if(param == 0 || selectedDate == "")
  {
    if (document.getElementById('calSelectedDate') != null)
      document.getElementById('calSelectedDate').value = "";
    selectedDate = "";
    presentClick = 0;
  }
  var tRows = document.getElementById('calendar').rows;
  var calCells = new Array(42);
  var z = 0;

  for(var i = 0; i < tRows.length; i++)
  {
    var tCells = tRows[i].cells;
    for(var y = 0; y < tCells.length; y++)
    {
      if(i > 0)
      {
        calCells[z] = tCells[y];
        z++;
      }
    }
  }

  for (w = 1; w < 7; w++)
  {
    for (d = 0; d < 7; d++)
    {
      if (!isNaN(myMonth[w][d])) // число
      {
        var newDiv = document.createElement("div");
        if(d == 5 || d == 6 )
          newDiv.style.color = 'red';
        else
          newDiv.style.color = 'black';
        newDiv.style.width = '100%';
        newDiv.appendChild(document.createTextNode(myMonth[w][d]));

        if(myMonth[w][d] == selectedDate) // выделим там где кликнули
        {
          newDiv.style.background = sbgcolor; // ячейка где кликнули
          newDiv.style.cursor = 'default';
          calCells[((7*w)+d)-7].style.background = ntbgcolor;
          calCells[((7*w)+d)-7].style.cursor = 'default';
          var oldDiv = calCells[((7*w)+d)-7].childNodes[0];
          if(oldDiv != null)
            calCells[((7*w)+d)-7].replaceChild(newDiv, oldDiv);
          else
            calCells[((7*w)+d)-7].appendChild(newDiv);
          if(document.getElementById('cur_day_clicked').value == 1)
          {
            present = 1;
            newDiv.present = 1;
          }
          else
          {
            present = 0;
            newDiv.present = 0;
          }
          objPrevElement = newDiv;
          continue;
        }
        else if (((iMonth-1)==dCurMonth) && (iYear==dCurYear) && (myMonth[w][d] == dCurDayOfMonth)) // выделим выходные
          newDiv.style.background = tbgcolor;// фон ячеки с текущей датой
        else
          newDiv.style.background = ntbgcolor;// фон ячеки с датами календаря

        newDiv.style.cursor = 'pointer';
        calCells[((7*w)+d)-7].style.cursor = 'pointer';
        newDiv.onmouseover = fToggleColor;
        newDiv.onmouseout = fToggleColor;
        newDiv.onclick = fSetSelectedDay;
        calCells[((7*w)+d)-7].style.background = ntbgcolor;
        var oldDiv = calCells[((7*w)+d)-7].childNodes[0];
        if(oldDiv != null)
          calCells[((7*w)+d)-7].replaceChild(newDiv, oldDiv);
        else
          calCells[((7*w)+d)-7].appendChild(newDiv);
      }
      else if( typeof calCells[((7*w)+d)-7] != 'undefined' && calCells[((7*w)+d)-7] != null )
      {
        var oldDiv = calCells[((7*w)+d)-7].childNodes[0];
        if (oldDiv != null)
        {
          oldDiv.style.background = 'White';
          oldDiv.style.cursor = 'default';
          oldDiv.onmouseover = function(){return false};
          oldDiv.onmouseout = function(){return false};
          oldDiv.onclick = function(){return false};
          if(typeof oldDiv.childNodes[0] != 'undefined')
            oldDiv.childNodes[0].nodeValue = "";
        }

        calCells[((7*w)+d)-7].style.background = 'White';
        calCells[((7*w)+d)-7].style.cursor = 'default';
      }
    }
  }
  // в выпадающем календаре подставим дату в поле
    document.getElementById('date').value = "1 " +
        document.getElementById('tbSelMonth').options[document.getElementById('tbSelMonth').selectedIndex].text +
        " " + document.getElementById('tbSelYear').value;

}

