var gNow = new Date();
var ggWinCal;

var dates_array = new Array (14);
var codes_array = new Array (14);
var yearMonthsCode = new Array('00','01','02','03','04','05','06','07','08','09','10','11');
var yearMonthsText = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var yearText = new Array("2005", "2006", "2007", "2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016");

var gDaysOfWeekFirstLetterDefault = ["Mo","Tu","We","Th","Fr","Sa","Su"];
var DERE;

Calendar.Months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
DOMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
lDOMonth = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

var gIndexValidFlightFirstDay;
var gIndexValidFlightFirstMonth;
var gIndexValidFlightFirstYear;
var gIndexValidFlightLastDay;
var gIndexValidFlightLastMonth;
var gIndexValidFlightLastYear;	

var gDaysOfWeekFirstLetter;
var gPopUpSelectText;
var gPopUpSelectTextDefault = "Select month";

var gPopUpTitleText;
var gPopUpTitleTextDefault = "calendar";

function Calendar(dayTargetSelect, monthTargetSelect, yearTargetSelect, monthSelect, yearSelect, p_WinCal, selIndex,DERE) {

	if (p_WinCal == null)
		this.gWinCal = ggWinCal;
	else
		this.gWinCal = p_WinCal;

	var d = new Date();
	
	if (monthSelect != -1)
		this.gMonth = monthSelect;
	else
		this.gMonth = d.getMonth();
	
	if (yearSelect != -1)
		this.gYear = 2005 + parseInt(yearSelect);
	else
		this.gYear = d.getYear();
	if (DERE=='De') 
	{	
	  this.gReturnDay 	= 'selectDayIn'   // dayTargetSelect; 
  	  this.gReturnMonth 	= 'selectMonthIn'	 // monthTargetSelect;
	}
	if (DERE=='Re')
	{	
	  this.gReturnDay 	= 'selectDayOut'   // dayTargetSelect; 
	  this.gReturnMonth 	= 'selectMonthOut'	 // monthTargetSelect;
	}
	this.gReturnYear 	= yearTargetSelect;
	this.selIndex = selIndex;
}

Calendar.get_daysofmonth = Get_MonthDays;

function Get_MonthDays(monthNo, yearToShow)
{
	if ((yearToShow % 4) == 0)
	{
		if ((yearToShow % 100) == 0 && (yearToShow % 400) != 0)
			return DOMonth[monthNo];
		
		return lDOMonth[monthNo];
	}
	else
		return DOMonth[monthNo];
}

new Calendar();

Calendar.prototype.getMonthlyCalendarCode = function() {
			
	var vCode 			= "";
	var vHeader_Code 	= "";
	var vData_Code 		= "";

	vHeader_Code = this.cal_header();
	
	vData_Code = this.cal_data();	
		
	vCode = vCode + vHeader_Code + vData_Code;
	
	vCode = vCode + "</TABLE>";
	
	return vCode;
}

Calendar.prototype.show = function()
{
	var vCode = "";

	this.wwrite("<html>");
	this.wwrite("<head><title>Calendar</title>");
	this.wwrite("<meta http-equiv='Content-Type' content='text/html; charset=ISO-8859-1'>");
	this.wwrite("<meta http-equiv='Content-Style-Type' content='text/css'>");
	this.wwrite("<link rel='STYLESHEET' type='text/css' href='calendar.css'>");
	this.wwrite("</head>");
	
	this.wwrite("<body class='bground_color' leftmargin='0' topmargin='0' rightmargin='0' marginwidth='0'\">");
	this.wwrite("<form NAME='CalendarForm'>");

	this.wwrite("<table width='166' border='0' cellspacing='0' cellpadding='0'>");
	this.wwrite("  <tr><td align='center'>");	
	this.wwrite("	 <table width='162' cellpadding='0' cellspacing='1' border='0'>");
	this.wwrite("	   <tr><td colspan='3' align='right' valign='middle'><b><font class='common_font'>Month:&nbsp;</font></b></td>");
	this.wwrite("		  <td colspan='4' align='right'>");											
	this.wwrite("			<select class='textfield' name='year' onchange='changeForm(this)'>");
		for (var i = 0; i < 15; i ++ )
		{
			if (i == this.selIndex)
				this.wwrite("					<option value =\" " + codes_array[i] + " \" selected>" + dates_array[i] + " </option>");
			else
				this.wwrite("					<option value =\" " +codes_array[i] + " \" >" + dates_array[i] + " </option>");
		}
	this.wwrite("						</select>");
	this.wwrite("					</td>");
	this.wwrite("				</tr>");		// document.CalendarForm.year.selectedIndex

	vCode = this.getMonthlyCalendarCode();
	this.wwrite(vCode);
	this.wwrite("	</tr>");
	this.wwrite("</table>");	
	this.wwrite("</form>");
	this.wwrite("</body></html>");		
}


Calendar.prototype.wwrite = function(wtext)
{
	document.writeln(wtext);
}

Calendar.prototype.wwriteA = function(wtext)
{
	document.write(wtext);
}

Calendar.prototype.cal_header = function() {

	var vCode = "";
	
	vCode = vCode + "<tr align='center' bgcolor='#000066'>";

	//-------------------------------------------
	//COMMENT: Iterate through the days in the week to get the first letter
	//-------------------------------------------
	for(i = 0; i <= 6; i++){	
		vCode = vCode + "<td width='22' height='20' align='center' class='week_day'><b>" + gDaysOfWeekFirstLetter[i] + "</b></td>";
	}
	vCode = vCode + "</tr>";
	return vCode;
}


Calendar.prototype.cal_data = function() {
	//Create a data object
	var vDate = new Date();
	var cur_day = vDate.getDate();
	var cur_month = vDate.getMonth();
	var cur_year = vDate.getYear();

	vDate.setDate(1);
	vDate.setMonth(this.gMonth);
	vDate.setFullYear(this.gYear);

	var vFirstDay= vDate.getDay();
	var tempDate = new Date();

	tempDate.setMonth(this.gMonth);
	tempDate.setFullYear(this.gYear);
	
	if (vFirstDay ==0){
		vFirstDay = 6
	}else{
		vFirstDay = (vFirstDay-1)
	}

	var vDay=1;
	var vLastDay=Get_MonthDays(parseInt(this.gMonth), this.gYear);
	var vOnLastDay=0;
	var vCode = "";
	
	currentMonth = this.gMonth;
	currentYear = this.gYear;
	
	if (currentMonth == 0){
		prevMonth = 11;	
		yearOfPrevMonth = (this.gYear - 1)
	}else{
		prevMonth = currentMonth - 1;
		yearOfPrevMonth = this.gYear;
	}
	
	
	numberOfDaysInPreviousMonth = Get_MonthDays(prevMonth, yearOfPrevMonth)
	
	vCode = vCode + "<tr>";
		
			for (i=0; i<vFirstDay; i++) {
					vCode = vCode + "<td width='22' height='20' align='center' class='day_other'>&nbsp;</td>";
			}
				
	
	for (j=vFirstDay; j<7; j++) {
	
		//check if current day is a day that the user may fly on				  
		if (	(this.gYear < cur_year)
			 || 
			(	(this.gYear == cur_year) && 
				(this.gMonth < cur_month)
			) 
			||
			(	(this.gYear == cur_year) && 
				(this.gMonth == cur_month) && 
				(this.format_day(vDay) < cur_day)
			)
		) {
			vCode = vCode + "<td width='22' height='20' align='center' class='day_prev'>" + this.format_day(vDay)  +"</td>";			
	
		}  //else allow the day to be selectable
	
		else {
				if (this.gReturnDay == 'selectDayOut')
					tempDate.setDate (vDay+1);
				else
					tempDate.setDate (vDay);
			
			vCode = vCode + "<td width='22' height='20' align='center' class='day_select'>" + 
			
			"<A HREF='#' " + 
					"onClick=\"" + 
						"var day_field = opener.document.getElementById('" + this.gReturnDay + "');" +
						"var month_field = opener.document.getElementById('" + this.gReturnMonth + "');" +
						"var time_field = null;" +
						"if ('" + this.gReturnDay + "' == 'selectDayIn')"+
						"	time_field = opener.document.getElementById('SecIn');" +
						"else if ('" + this.gReturnDay + "' == 'selectDayOut')" +
						"	time_field = opener.document.getElementById('SecOut');" +
						"day_field.selectedIndex='" + ((this.format_day(vDay))-1) + "';" +
						"month_field.selectedIndex='" + document.CalendarForm.year.selectedIndex + "';" +		
						"if (time_field != null) time_field.value = '" + tempDate.getTime() + "';" +
					"window.close();\">" + 							
					this.format_day(vDay) + 
				"</A>" + 					
				"</TD>";
		}
		vDay=vDay + 1;
	}
	vCode = vCode + "</TR>";
	
	for (k=2; k<7; k++) {
		vCode = vCode + "<TR>";
	
		for (j=0; j<7; j++) {
		
			if (	(this.gYear < cur_year)
				|| 
				(	(this.gYear == cur_year) &&
					(this.gMonth < cur_month)
				) 
				||
				(	(this.gYear == cur_year) && 
					(this.gMonth == cur_month) && 
					(this.format_day(vDay) < cur_day)
				)
			) {
				vCode = vCode + "<td width='22' height='20' align='center' class='day_prev'>" + this.format_day(vDay)  +"</td>";
	
			} //else allow the day to be selectable		
			else {
				if (this.gReturnDay == 'selectDayOut')
					tempDate.setDate (vDay+1);
				else
					tempDate.setDate (vDay);
				
			vCode = vCode + "<td width='22' height='20' align='center' class='day_select'>" + 			
			"<A HREF='#' " + 
					"onClick=\"" + 
						"var day_field = opener.document.getElementById('" + this.gReturnDay + "');" +
						"var month_field = opener.document.getElementById('" + this.gReturnMonth + "');" +
						"var time_field = null;" +
						"if ('" + this.gReturnDay + "' == 'selectDayIn')"+
						"	time_field = opener.document.getElementById('SecIn');" +
						"else if ('" + this.gReturnDay + "' == 'selectDayOut')" +
						"	time_field = opener.document.getElementById('SecOut');" +
						"day_field.selectedIndex='" + ((this.format_day(vDay))-1) + "';" +
						"month_field.selectedIndex='" + document.CalendarForm.year.selectedIndex + "';" +
						"if (time_field != null) time_field.value = '" + tempDate.getTime() + "';" +
					"window.close();\">" + 							
					this.format_day(vDay) + 
				"</A>" + 					
				"</TD>";
			}
			vDay=vDay + 1;
	
			if (vDay > vLastDay) {
				vOnLastDay = 1;
				break;
			}
		}
	
		if (j == 6)
			vCode = vCode + "</TR>";
		if (vOnLastDay == 1)
			break;
	}
	
	for (m=1; m<(7-j); m++) {
		/*if (this.gYearly)
			vCode = vCode + "<td width='22' height='20' align='center' class='day_other'>&nbsp;</TD>";
		else*/
			vCode = vCode + "<td width='22' height='20' align='center' class='day_other'>&nbsp;</TD>";
	}
	return vCode;
}


Calendar.prototype.format_day = function(vday) {
	
	var vNowDay 	= gNow.getDate();
	var vNowMonth 	= gNow.getMonth();
	var vNowYear 	= gNow.getFullYear();

	if ((vday == vNowDay && this.gMonth == vNowMonth && this.gYear == vNowYear) && (vday < gIndexValidFlightFirstDay))
		//return ("<FONT COLOR=\"RED\"><B>" + vday + "</B></FONT>");
		return (vday);
	else
		//return ("<FONT COLOR=\"GREEN\"><B>" + vday + "</B></FONT>");
		return (vday);
}

function Build(dayTargetSelect, monthTargetSelect, yearTargetSelect, monthSelect, yearSelect, selIndex,DERE)
{
	var p_WinCal = this;	

	gCal = new Calendar(dayTargetSelect, monthTargetSelect, yearTargetSelect, monthSelect, yearSelect, p_WinCal, selIndex,DERE);
	gCal.show();
}


//--------------------------------------------------------------------------------------------------------------
// COMMENT:
// show_calendar
// =============
//
// The function that is called in the jsp page. This function initiates the pop up calendar variables 
// and calls the function to invoke the displaying and building.
//
// @param	0	dayTargetSelect		: The target for the 1st return item: i.e. the day drop down Menu/Select
// @param	1	monthTargetSelect		: The target for 2nd return item. i.e. the month Drop Down Menu/Select
// @param	2	yearTargetSelect		: The target for 3rd return item. i.e. the year Drop Down Menu/Select
//-------------------------------------------------------
function show_calendar() 
{
	dayTargetSelect = arguments[0];
	monthTargetSelect = arguments[1];
	yearTargetSelect = arguments[2];
	DERE = arguments[6];
// alert (dayTargetSelect+' '+monthTargetSelect+' '+yearTargetSelect);
	yearSelect = -1;
	if (arguments[3] != null)
		yearSelect = arguments[3];
	
	monthSelect = -1;
	if (arguments[4] != null)
		monthSelect = arguments[4];
	
	selIndex = 0;
	if (arguments[5] != null)
		selIndex = arguments[5];

	gDaysOfWeekFirstLetter = gDaysOfWeekFirstLetterDefault;
	
	var mon_i = gNow.getMonth()
	var yea_i = gNow.getFullYear()

// alert (dayTargetSelect+' '+monthTargetSelect+' '+yearTargetSelect+' '+mon_i+' '+yea_i);	
	for (i = 0; i < 15; i++)  // для списка
	{
		dates_array[i] = (yearMonthsText[mon_i]).slice(0,3) + " " + yea_i;
		codes_array[i] = yea_i + yearMonthsCode[mon_i];
		if (mon_i == 11)
		{
			mon_i = 0
			yea_i ++
		}
		else
			mon_i++
	}

	Build(dayTargetSelect, monthTargetSelect, yearTargetSelect, monthSelect, yearSelect, selIndex,DERE);
}

function changeForm()
{
	var index = document.CalendarForm.year.selectedIndex;
	var year = ((document.CalendarForm.year.options[index].value).slice(1,5)) - 2005;
	var month = (document.CalendarForm.year.options[index].value).slice(5,7);
// alert ('changeForm '+index +' '+year+' '+month);
	document.location.href = "calendar.php?arg0='" + dayTargetSelect + "'&arg1='" + 
		monthTargetSelect + "'&arg2='" + yearTargetSelect + "'&arg3='" + year + "'&arg4='" + month + "'&arg5='"+ index  + "'&arg6='"+ DERE +"'";	
}

function calendar_popup(){
	var x = event.x+20;
	var y = event.y+20;
//	alert ('calendar_popup ' + x + ' ' + y);
	popupWin = window.open("calendar.php?arg0='" + arguments[0] + "'&arg1='" + arguments[1] + "'&arg2='" + arguments[2] + "'&arg2='" + arguments[2] + "'&arg6='" + arguments[3] + "'", 'contacts', 'resizable=yes,width=175,height=200,top=' + y + ',left=' + x);
	popupWin.opener = self;
	ggWinCal = popupWin;
}


// ************************************
function fixReturnDate()
{
	var selectDayIn_=document.getElementById ('selectDayIn').value;
	var selectMonthIn_=document.getElementById ('selectMonthIn').value;
	var selectDayOut_=document.getElementById ('selectDayOut').value;
	var selectMonthOut_=document.getElementById ('selectMonthOut').value;
	var de=parseInt(selectMonthIn_+selectDayIn_);
	var re=parseInt(selectMonthOut_+selectDayOut_);
	if (de>re)	{ 
		document.send.selectDayOut.selectedIndex=document.send.selectDayIn.selectedIndex;
		document.send.selectMonthOut.selectedIndex=document.send.selectMonthIn.selectedIndex;
	}
}

function reDate(field,mo_ye,RD) {
	var vCode='<select name='
	var sd = parseInt(field)
	var vMonth=parseInt((mo_ye).slice(4,6))-1
	var vYear=parseInt((mo_ye).slice(0,4))
	var oneDay = 1000 * 60 * 60 * 24	
	var thisMonth = new Date(vYear, vMonth, 1)
	var nextMonth = new Date(vYear, vMonth + 1, 1)
	var len = Math.round((nextMonth.getTime() - thisMonth.getTime())/oneDay)
	var today = new Date()
	var thisYear  = today.getFullYear()
	var thisMonth = today.getMonth()
	var thisDay   = today.getDate()
//	alert(thisDay+' '+thisMonth+' '+thisYear);
//	var startDay = (vMonth==thisMonth && thisYear==vYear)?(thisDay):(1)
	startDay=1		// для любого месяца
	var vCode1 = vCode + '"selectDayIn" id="selectDayIn"' 
	var vCode3 = vCode + '"selectDayOut" id="selectDayOut"' 
	vCode=' class="textfield" style="width:40px;height:12px" onChange="javascript:fixReturnDate();">'
	vCode1+=vCode
	vCode3+=vCode
	vCode=''
	for (i=startDay; i<=len; i++) {
	    t=(i<10)?('0'+i):(i)
		s=(i==sd)?(" selected"):("")
		vCode += "<option value='" + t + "'" + s + ">" + i + "</option>"
	}
	vCode+='</select>'; 
//	alert(' vMonth '+vMonth+' vYear '+vYear+' len '+len+'\n');
if (RD=='De')	{ document.send.selectDayIn.outerHTML = vCode1+vCode; 
				  document.send.selectDayOut.outerHTML = vCode3+vCode; 
  		  		  document.send.selectMonthOut.selectedIndex=document.send.selectMonthIn.selectedIndex;
				  }
if (RD=='Re')	  document.send.selectDayOut.outerHTML = vCode3+vCode;
}

function ValidateDate() {
	// document.getElementById ('stateField');
	var selectDayIn_=document.getElementById ('selectDayIn').value;
	var selectMonthIn_=document.getElementById ('selectMonthIn').value;
	var selectDayOut_=document.getElementById ('selectDayOut').value;
	var selectMonthOut_=document.getElementById ('selectMonthOut').value;
	var de=parseInt(selectMonthIn_+selectDayIn_);
	var re=parseInt(selectMonthOut_+selectDayOut_);
	if (de<re)	{ 
		document.send.submit();
		return true; } else {
		alert("Your check out date is on the same day \n as the check in date, please correct");
		return false;} 
}
