var loadMonth = 0;
var loadYear  = 0;
var index = 0;
var newsDay = [];

for ( i=0; i<31; i++ ) {
  newsDay[i] = false;
}

function Calendar (cname, id, date)
{
	this.fallback_single = 0;
	this.fallback_multi = 1;
	this.fallback_both = 2;
	this.viewOnly = false;
	this.allowWeekends = true;
	this.allowWeekdays = true;
	this.minDate = "--";
	this.maxDate = "--";
	this.scrolling = true;
	this.name = cname;
	this.firstDayOfWeek = 0;
	this.fallback = this.fallback_both;
	this.calendarDate = date;
	this.calendarDate.setUTCHours(0);
	this.calendarDate.setUTCMinutes(0);
	this.calendarDate.setUTCSeconds(0);
	this.calendarDate.setUTCMilliseconds(0);
	this.attachedId = id;
	this.controlLeft = "&#171;";
	this.controlRight = "&#187;";
	this.controlLeftDisabled = "";
	this.controlRightDisabled = "";
	this.calendarStyle = "cal_calendar";
	this.headerStyle = "cal_header";
	this.headerCellStyle = "cal_cell";
  this.CellStyle = "header_cal_cell";
	this.headerCellStyleLabel = "cal_labelcell";
	this.weekStyle = "cal_week";
	this.evenWeekStyle = "cal_evenweek";
	this.oddWeekStyle = "cal_oddweek";
	this.dayStyle = "cal_day";
	this.disabledDayStyle = "cal_disabled";
	this.commonDayStyle = "cal_common";
	this.holidayDayStyle = "cal_holiday";
	this.eventDayStyle = "cal_event";
	this.todayDayStyle = "cal_today";
  if ( lang == 3 ) {
	  this.dayLabels = new Array( "Mo", "Tu", "We", "Th", "fr", "Sa", "Su" );
	  this.monthLabels = new Array(
		  "January", "February", "March", "April"
		  , "May", "June", "July", "August"
		  , "September", "October", "November", "December");
	} else {
    this.dayLabels = new Array( "пн", "вт", "ср", "чт", "пт", "сб", "нд" );
	  this.monthLabels = new Array(
		  "С╕чень", "Лютий", "Березень", "Кв╕тень"
		  , "Травень", "Червень", "Липень", "Серпень"
		  , "Вересень", "Жовтень", "Листопад", "Грудень");
  }
	this.eventDates = new Array();
	if (this.viewOnly == false) {
	
		setFieldValue(this.attachedId, this.calendarDate);
		
		if ((this.fallback = this.fallback_both) || (this.fallback = this.fallback_single)) {
			eval("document.getElementById(\"" + this.attachedId + "\").onchange = function () {updateFromSingle("+this.name+", this);}");
		}

		if ((this.fallback = this.fallback_both) || (this.fallback = this.fallback_multi)) {

			eval("document.getElementById(\"" + this.attachedId + "_day\").onchange = function () {updateFromMultiDay("+this.name+", this);}");
      if ( load == true ) {
			  eval("document.getElementById(\"" + this.attachedId + "_month\").onchange = function () {updateFromMultiMonth("+this.name+", this);}");
			  eval("document.getElementById(\"" + this.attachedId + "_year\").onchange = function () {updateFromMultiYear("+this.name+", this);}");
			}
   
		}
	} 
	
	selectEvent = new Function();
  
  
}

function updateFromSingle (sender, helper) {
	newDate = new Date (helper.value);
	newDate.setUTCDate(newDate.getUTCDate()+1);
	sender.calendarDate = newDate;

	renderCalendar (sender);
	setFieldValue(sender.attachedId, sender.calendarDate);
}

function updateFromMultiDay (sender, helper) {

	if (isNaN(helper.value)) {
		helper.value = sender.calendarDate.getUTCDate();
		return false;
	}

	sender.calendarDate.setUTCDate(helper.value);
	renderCalendar (sender);
	setFieldValue(sender.attachedId, sender.calendarDate);
}

function updateFromMultiMonth (sender, helper) {

	if (isNaN(helper.value)) {
		helper.value = sender.calendarDate.getUTCMonths() -1;
		return false;
	}
	
	sender.calendarDate.setUTCMonth(helper.value-1);
	renderCalendar (sender);
	setFieldValue(sender.attachedId, sender.calendarDate);
}

function updateFromMultiYear (sender, helper) {

	if (isNaN(helper.value)) {
		helper.value = sender.calendarDate.getUTCFullYear();
		return false;
	}
	
	sender.calendarDate.setUTCFullYear(helper.value);
	renderCalendar (sender);
	setFieldValue(sender.attachedId, sender.calendarDate);
}

function getFirstCalendarDate (calendar)
{
	return new Date (
		calendar.calendarDate.getUTCFullYear()
		, calendar.calendarDate.getUTCMonth()
		, 1
	);
}

function renderCalendar (calendar)
{ 
  for ( i=0; i<31; i++ ) {
    newsDay[i] = false;
  }
  req = new BGRequest();
  if ( calendar_ == true ) {
    req.open( "GET", "/rubric/rubric_list.xml?rubric=" + rubric + "&month=" + ( calendar.calendarDate.getUTCMonth() + 1 ) + "&year=" + calendar.calendarDate.getUTCFullYear() );
  } else {
    req.open( "GET", "/news/news_list.xml?month=" + ( calendar.calendarDate.getUTCMonth() + 1 ) + "&year=" + calendar.calendarDate.getUTCFullYear() + "&lang=" + lang );
  }  
    req.onComplete = function() {
      xmlText = req.responseText;
      xmlDoc = XMLDocument( xmlText );
      root = xmlDoc.getElementsByTagName( 'root' )[0];
      list = root.getElementsByTagName( 'day' );
      if ( list.length !=0 ) {
        for ( i = 0; i < list.length; i++ ) {
          newsDay[ ( list[i].firstChild.nodeValue - 1 ) ] = true;
        }
        calHtml1 =  ("<table id=\"cal_" + calendar.attachedId + "\" class=\"" + calendar.calendarStyle +"\">");
	      calHtml1 += ((calendar.scrolling)?buildHeader(calendar):buildStaticHeader(calendar));
	      calHtml1 += buildCalendarTable (calendar);
	      calHtml1 += ("</table>");
        document.getElementById("cal_" + calendar.attachedId + "_display").innerHTML = calHtml1;
      } else {
        calHtml1 =  ("<table id=\"cal_" + calendar.attachedId + "\" class=\"" + calendar.calendarStyle +"\">");
	      calHtml1 += ((calendar.scrolling)?buildHeader(calendar):buildStaticHeader(calendar));
	      calHtml1 += buildCalendarTable (calendar);
	      calHtml1 += ("</table>"); 
        document.getElementById("cal_" + calendar.attachedId + "_display").innerHTML = calHtml1;
      }
    }
  req.send();
  index = 0;
}

function scrollMonthBack (calendar)
{
	calendar.calendarDate.setUTCMonth(calendar.calendarDate.getUTCMonth() - 1);
	setFieldValue(calendar.attachedId, calendar.calendarDate);
	renderCalendar (calendar);
}

function selectDate (calendar, day)
{
  date = new Date();
  if ( ( date.getUTCDate() >= day && date.getUTCMonth() == calendar.calendarDate.getUTCMonth() ) || ( date.getUTCMonth() != calendar.calendarDate.getUTCMonth() ) ) {
	  if (!calendar.viewOnly) {
      if ( newsDay[( day - 1 )] == true ) {
        if ( calendar_ == true ) {
          location.replace( '/rubric' + rubric + '/date/' + day + '/' + ( calendar.calendarDate.getUTCMonth() + 1 ) + '/' + calendar.calendarDate.getUTCFullYear() + '/' );
        } else {
          str = '';
          if ( lang == 3 ) {
            str = '/en';
          }
          location.replace( str + '/news/' + day + '/' + ( calendar.calendarDate.getUTCMonth() + 1 ) + '/' + calendar.calendarDate.getUTCFullYear() + '/' );
        }   
	    }
    }
  }  
}

function scrollMonthForward (calendar)
{
  date = new Date();
  if ( ( calendar.calendarDate.getUTCMonth() < date.getUTCMonth() ) && 
     ( calendar.calendarDate.getUTCFullYear() == date.getUTCFullYear() ) || 
     ( calendar.calendarDate.getUTCFullYear() != date.getUTCFullYear() ) )  
  {
	      calendar.calendarDate.setUTCMonth(calendar.calendarDate.getUTCMonth() + 1);
	      setFieldValue(calendar.attachedId, calendar.calendarDate);
	      renderCalendar (calendar);
  }  
}

function selectMonth ( calendar, month )
{
  date = new Date();
  if (  ( month <= ( date.getUTCMonth() + 1 ) )  ||  ( calendar.calendarDate.getUTCFullYear() != date.getUTCFullYear() ) ) {
	  calendar.calendarDate.setUTCMonth( month - 1 );
	  setFieldValue(calendar.attachedId, calendar.calendarDate);
	  renderCalendar (calendar);
  } else {
    setFieldValue( calendar.attachedId, calendar.calendarDate )
  }  
}

function selectYear ( calendar, year )
{
	calendar.calendarDate.setYear( year  );
	setFieldValue(calendar.attachedId, calendar.calendarDate);
	renderCalendar (calendar);
}

function setFieldValue(fieldId, date) {
	document.getElementById(fieldId).value = date.getUTCFullYear() + "/" + (date.getUTCMonth()+1) + "/" + date.getUTCDate();
	if ( load == true ) {
    document.getElementById(fieldId + "_year").value = date.getUTCFullYear();
	  document.getElementById(fieldId + "_month").selectedIndex = date.getUTCMonth();
  } else {
    loadMonth = date.getUTCMonth();
    loadYear  = date.getUTCFullYear();
  }
	document.getElementById(fieldId + "_day").value = date.getUTCDate();
}
function buildHeader (calendar)
{

	enableLeft = true;
	enableRight = true;
	
	if (calendar.minDate != "--") 
	{
		if (calendar.calendarDate.getUTCFullYear() <= calendar.minDate.getUTCFullYear())
		{
			if (calendar.calendarDate.getUTCMonth() <= calendar.minDate.getUTCMonth())
			{
				enableLeft = false;
			}
		}
	}

	if (calendar.maxDate != "--") 
	{
		if (calendar.calendarDate.getUTCFullYear() >= calendar.maxDate.getUTCFullYear())
		{
			if (calendar.calendarDate.getUTCMonth() >= calendar.maxDate.getUTCMonth())
			{
				enableRight = false;
			}
		}
	}

	calHtml2 = "";
	
	calHtml2 +=  (
		"<tr class=\""
		+ calendar.headerStyle
		+ "\">");
	calHtml2 +=  (
		"<td class=\""
		+ calendar.CellStyle
		+ ((enableLeft)?("\" onclick=\"scrollMonthBack(" + calendar.name + ")"):"")
		+ "\"><img src='/img/calendar_arr2.gif' width='6' height='10' alt='' border='0'>"
		+ "</td>");
	calHtml2 +=  (
		"<td colspan=\"5\" class=\""
		+ calendar.headerStyle
		+ "\">"
		+ calendar.monthLabels[calendar.calendarDate.getUTCMonth()] 
		+ "</td>");
	calHtml2 +=  (
		"<td class=\""
		+ calendar.CellStyle
		+ ((enableRight)?("\" onclick=\"scrollMonthForward(" + calendar.name + ")"):"")
		+ "\"><img src='/img/calendar_arr1.gif' width='6' height='10' alt='' border='0'>&nbsp;&nbsp;&nbsp;"
		+ "</td>");
	
	calHtml2 += ("</tr>");

	calHtml2 +=  (
		"<tr class=\""
		+ calendar.headerStyle
		+ "\">")

	for (i = 0; i < 7; i++) {
		showDay = i + calendar.firstDayOfWeek;
		if (showDay > 6) showDay = showDay - 7;
		calHtml2 +=  (
			"<td class=\""
			+ calendar.headerCellStyle
			+ "\">"
			+ calendar.dayLabels[showDay]
			+ "</td>");
	}
	calHtml2 += ("</tr>");
	return calHtml2
}

function buildStaticHeader (calendar)
{
	calHtml2 = "";
  
	calHtml2 +=  (
		"<tr class=\""
		+ calendar.headerStyle
		+ "\">");
	calHtml2 +=  (
		"<td colspan=\"7\" class=\""
		+ calendar.headerCellStyleLabel
		+ "\">"
		+ calendar.monthLabels[calendar.calendarDate.getUTCMonth()] 
		+ ", " + calendar.calendarDate.getUTCFullYear()
		+ "</td>");	
	calHtml2 += ("</tr>");
	
	calHtml2 +=  (
		"<tr class=\""
		+ calendar.headerStyle
		+ "\">")
    
	for (i = 0; i < 7; i++) {
		showDay = i + calendar.firstDayOfWeek;
		if (showDay > 6) showDay = showDay - 7;
		calHtml2 +=  (
			"<td class=\""
			+ calendar.headerCellStyle
			+ "\">"
			+ calendar.dayLabels[showDay]
			+ "</td>");
	}

	calHtml2 += ("</tr>");
	return calHtml2
}



function RenderDayDisabled (calendar, currentDate)
{
	calHtml += ('<td></td>');
}

function RenderDayEnabled (calendar, currentDate, dayStyle)
{
  date = new Date();
	currentDayStyle = dayStyle;
	calHtml += ('<td class="day">');
  if ( newsDay[index] == true ) {
    if ( dayStyle == 'cal_today' )
      style = 'cal_today_pointer';
    else   
      style = 'cal_common_pointer';
	} else {
    if ( dayStyle == 'cal_today' && date.getUTCMonth() ==  calendar.calendarDate.getUTCMonth() ) {
      style = dayStyle;
    }  
    else {
       if ( currentDate.getUTCDay() == 0 || currentDate.getUTCDay() == 6 )
         style = 'cal_holiday';
       else style = 'cal_common';
    }
    if ( date.getUTCDate() ==  currentDate.getUTCDate() && newsDay[index] != true ) {
      style = 'cal_today';
    }   
  }
  calHtml += ("<span class=\"" + style + "\" onclick=\"selectDate(" + calendar.name + ", " + currentDate.getUTCDate() + ")\">");
  calHtml += (currentDate.getUTCDate());
	calHtml += ("</span>");
	calHtml += ("</td>");
  index ++;
}

function RenderDayEvent (calendar, currentDate, dayStyle, eventId)
{
	currentDayStyle = dayStyle;
	calHtml += ('<td class="day">');
	calHtml += ("<span class=\"" + dayStyle + "\" onclick=\"selectDate(" + calendar.name + ", " + currentDate.getUTCDate() + "); " + calendar.name + ".selectEvent('" + eventId + "')\">");
	calHtml += (currentDate.getUTCDate());
	calHtml += ("</span>");
	calHtml += ("</td>");
}

function buildCalendarTable (calendar)
{
	currentDate = getFirstCalendarDate(calendar);
	odd = 0;
	while (( currentDate.getUTCDay() -1 ) != calendar.firstDayOfWeek)
	{
		currentDate.setUTCDate(currentDate.getUTCDate()- 1);
	}

	calHtml = "";
	do
	{
		odd += 1;

		calHtml +=  (
			"<tr class=\"" + (((odd%2)==0) ? calendar.evenWeekStyle : calendar.oddWeekStyle) + "\">")

		for (i = 0;i < 7;i++)
		{
			currentDayStyle = calendar.dayStyle;
			currentEventStyle = calendar.commonDayStyle;
    
			currentDateString = currentDate.getUTCFullYear() + "/" + (currentDate.getUTCMonth()+1) + "/" + ( currentDate.getUTCDate() + 1 );
			if (currentDate < calendar.minDate) 
			{
				RenderDayDisabled (calendar, currentDate);
			} 
			else if (currentDate > calendar.maxDate) 
			{
				RenderDayDisabled (calendar, currentDate);
			} 
			else if (currentDate.getUTCMonth() != calendar.calendarDate.getUTCMonth())
			{
				RenderDayDisabled (calendar, currentDate);
			}
			else if (currentDate.getUTCDate() == calendar.calendarDate.getUTCDate())
			{
				if ((currentDate.getUTCDay() == 0) || (currentDate.getUTCDay() == 6))
				{
					if ( calendar.allowWeekends == true )
					{
						RenderDayEnabled (calendar, currentDate, calendar.todayDayStyle);
					} 
					else 
					{
						RenderDayDisabled (calendar, currentDate);	
						month = calendar.calendarDate.getUTCMonth();
						calendar.calendarDate.setUTCDate(calendar.calendarDate.getUTCDate()+1);
						if (month != calendar.calendarDate.getUTCMonth())
						{
							renderCalendar(calendar);
						}
						setFieldValue(calendar.attachedId, calendar.calendarDate);
					}
				} else {
					if (calendar.allowWeekdays == true)
					{
						RenderDayEnabled (calendar, currentDate, calendar.todayDayStyle);
					} 
					else 
					{
						RenderDayDisabled (calendar, currentDate);	
						month = calendar.calendarDate.getUTCMonth();
						calendar.calendarDate.setUTCDate(calendar.calendarDate.getUTCDate()+1);
						if (month != calendar.calendarDate.getUTCMonth())
						{
							renderCalendar(calendar);
						}
						setFieldValue(calendar.attachedId, calendar.calendarDate);
					}
				}
			}
			else if ((currentDate.getUTCDay() == 0) || (currentDate.getUTCDay() == 6))
			{
				if (calendar.allowWeekends == true)
				{
				
					style = calendar.holidayDayStyle
					
					for (j=0; j < calendar.eventDates.length; j++)
					{
						if (calendar.eventDates[j][0] == currentDateString) 
						{
							style = calendar.eventDayStyle;
							RenderDayEvent (calendar, currentDate, style, calendar.eventDates[j][0]);
						}
					}
					if (style == calendar.holidayDayStyle)
					{
						RenderDayEnabled (calendar, currentDate, style);
					}
				} 
				else 
				{
					RenderDayDisabled (calendar, currentDate);	
				}
			} else {
				if (calendar.allowWeekdays == true)
				{
					style = calendar.commonDayStyle

					for (j=0; j < calendar.eventDates.length; j++)
					{
						if (calendar.eventDates[j][0] == currentDateString) 
						{
							style = calendar.eventDayStyle;
							RenderDayEvent (calendar, currentDate, style, calendar.eventDates[j][0]);
						}
					}

					if (style == calendar.commonDayStyle)
					{
						RenderDayEnabled (calendar, currentDate, style);
					}
				} 
				else 
				{
					RenderDayDisabled (calendar, currentDate);	
				}
			}

			currentDate.setUTCDate(currentDate.getUTCDate() + 1);	
		}
		
		calHtml += ("</tr>");
		

	} while (currentDate.getUTCMonth() == calendar.calendarDate.getUTCMonth());
	return calHtml;
}
