var hasCookies = false;

//tests whether the user accepts cookies, and sets a flag.
//тестируем на поддержку куков, если "ДА", то в true
if(document.cookie == '') {
	document.cookie = 'hasCookies=yes';
	if (document.cookie.indexOf('hasCookies=yes') != -1) hasCookies = true;
}
else hasCookies = true;

// sets a cookie to the browser
function setCookie(name, value, hours, path) {
	if (hasCookies) {
		if(hours) {
			if ( (typeof(hours) == 'string') && Date.parse(hours) ) var numHours = hours;
			else if (typeof(hours) == 'number') var numHours = (new Date((new Date()).getTime() + hours*3600000)).toGMTString();
		}
		document.cookie = name + '=' + escape(value) + ((numHours)?(';expires=' + numHours):'') + ((path)?';path=' + path:'');
	}
}

// reads a cookie from the browser
function readCookie(name) {
	if (document.cookie == '') return '';
	else {
		var firstChar, lastChar;
		var theBigCookie = document.cookie;
		firstChar = theBigCookie.indexOf(name);
		if (firstChar != -1) {
			firstChar += name.length;
			lastChar = theBigCookie.indexOf(';', firstChar);
			if (lastChar == -1) lastChar = theBigCookie.length;
			result = unescape(theBigCookie.substring(firstChar+1, lastChar));
			if (result == ';') return '';
			else return result;
		}
		else return '';
	}
}

calDateFormat    = "mm/dd/yyyy";

// FORMATTING PREFERENCES
bottomBorder  = false;        // TRUE/FALSE (WHETHER TO DISPLAY BOTTOM CALENDAR BORDER)
tableBorder   = 0;            // SIZE OF CALENDAR TABLE BORDER (BOTTOM FRAME) 0=none
// END USER-EDITABLE SECTION -------------------------------------------------------



// DETERMINE BROWSER BRAND
var isNav = false;
var isIE  = false;

// ASSUME IT'S EITHER NETSCAPE OR MSIE
if (navigator.appName == "Netscape") {
    isNav = true;
}
else {
    isIE = true;
}
// PRE-BUILD PORTIONS OF THE CALENDAR WHEN THIS JS LIBRARY LOADS INTO THE BROWSER
buildCalParts();

// SET THE INITIAL VALUE OF THE GLOBAL DATE FIELD
function setDateField(dateField) {
    calDateField = dateField;
    inDate = dateField.value;
    setInitialDate();

    // THE CALENDAR FRAMESET DOCUMENTS ARE CREATED BY JAVASCRIPT FUNCTIONS
    calDocTop    = getNavigationPartCalendar();
    calDocBottom = getMainPartCalendar();
}


// SET THE INITIAL CALENDAR DATE TO TODAY OR TO THE EXISTING VALUE IN dateField
function setInitialDate() {

	if (scriptName == '/booked.php' || scriptName == '/staging/booked.php'  || scriptName == '/date.php') {
		year = readCookie("yearClient");
		month = readCookie("monthClient");

	} else {
		year = readCookie("yearAdmin");
		month = readCookie("monthAdmin");
	}

//	times = readCookie("month");
	if (month != '' && year != '') {
	    calDate = new Date(year, month, 1);
        /**
    * added to prevent month loosing bug after clicking 'back to calendar' button
    *
    * @author Alexander Kaplun
    * @since 2005.06.23
    *
    */

		/**
        if (scriptName == '/booked.php') {
			setCookie("yearClient", "");
			setCookie("monthClient", "");
		} else {
			setCookie("yearAdmin", "");
			setCookie("monthAdmin", "");
		}**/
    }
    else if (month != '') {
        NowDate = new Date();
        curYear = NowDate.getYear() + 1900;
        curYear = NowDate.getFullYear();

		year = document.getElementById('year');
		if (year) {
			curYear = document.calendar.year.value;
		}
        calDate = new Date(curYear, month, 1);

//		setCookie("yearClient", curYear);

        /**
        if (scriptName == '/booked.php') {
			setCookie("yearClient", "");
			setCookie("monthClient", "");
		} else {
			setCookie("yearAdmin", "");
			setCookie("monthAdmin", "");
		}*/
    /**
    * 2005.06.23 END
    */
	} else {
		month = document.getElementById('month');
		year = document.getElementById('year');
		if (month && year) {
		    calDate = new Date(document.calendar.year.value, document.calendar.month.options[document.calendar.month.selectedIndex].value, 1);
		} else {
			calDate = new Date();
		}
	}
    calDay  = calDate.getDate();
    calDate.setDate(1);
}

//навигационная панель
function getNavigationPartCalendar() {
    var result =
		"<table>" +
		"<tr><td><div align=\"right\">" + getMonthName() + " / " + calDate.getFullYear() + "&nbsp;</div>" +
		"<center><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\">" +
		"<tr><td colspan=\"2\" background=\"images/calendar/dot.gif\"><img src=\"images/calendar/pixel.gif\" width=\"1\" height=\"3\"></td></tr>" +
		"<tr><td colspan=\"2\"><img src=\"images/calendar/pixel.gif\" width=\"1\" height=\"3\"></td></tr>" +
		"<tr><td class=\"navigation\" colspan=\"2\"><form name=\"calendar\" action=\"" + scriptName + "\" onsubmit=\"return false;\"><input type=\"hidden\" name=\"do\" value=\""+ action +"\"><input type=\"hidden\" name=\"day\"><input type=\"hidden\" name=\"reservationsId\" value=\""+ reservationsId +"\">" +
        getMonthSelect();

    if (scriptName == '/date.php' && showHiddenYear == 'yes'){
        result = result +
			"<input id=\"year\" name=\"year\" value=\"" + calDate.getFullYear() + "\" type=\"text\" size=\"20\" mxlength=\"4\" onkeyup=\"setYear();\"> " +
    	    "<input type=\"image\" src=\"images/calendar/leftArrow.gif\" width=\"15\" height=\"15\" vspace=\"0\" align=\"middle\" onmouseup='setPreviousYear()'> " +
			"<input type=\"image\" src=\"images/calendar/rightArrow.gif\" width=\"15\" height=\"15\" vspace=\"0\" align=\"middle\" onmouseup='setNextYear()'>";

    } else if (scriptName == '/booked.php' || scriptName == '/staging/booked.php' || showHiddenYear == 'yes') {
		result = result + "<input id=\"year\" name=\"year\" value=\"" + calDate.getFullYear() + "\" type=\"hidden\"> " +
						  "<input type=\"button\" value=\"Show Times for Selected Dates\" onClick=\"javascript: location.href=\'" + scriptName + "?do=searchReservationsByDate\'\"> " +
						  "<input type=\"button\" value=\"Reset\" onClick=\"javascript: location.href=\'" + scriptName + "?do=clearCookie'\">";

	} else {
		result = result +
			"<input id=\"year\" name=\"year\" value=\"" + calDate.getFullYear() + "\" type=\"text\" size=\"20\" mxlength=\"4\" onkeyup=\"setYear();\"> " +
    	    "<input type=\"image\" src=\"images/calendar/leftArrow.gif\" width=\"15\" height=\"15\" vspace=\"0\" align=\"middle\" onmouseup='setPreviousYear()'> " +
			"<input type=\"image\" src=\"images/calendar/rightArrow.gif\" width=\"15\" height=\"15\" vspace=\"0\" align=\"middle\" onmouseup='setNextYear()'>";
	}

    result = result +
	 	"</form></td></tr>" +
		"<form name=\"send\" action=\"" + scriptName + "\" onsubmit=\"return false;\"><input type=\"hidden\" name=\"do\" value=\""+ action +"\"><input type=\"hidden\" name=\"reservationsId\" value=\""+ reservationsId +"\"><input type=\"hidden\" name=\"day\"><input type=\"hidden\" name=\"month\"><input name=\"year\" type=\"hidden\"></form>";
    return result;
//        "</td><td class=\"navigation\" align=\"right\"><input id=\"year\" name=\"year\" value=\"" + calDate.getFullYear() + "\" type=\"text\" size=\"20\" mxlength=\"4\" onkeyup=\"setYear();\"> " +
//        "<input type=\"image\" src=\"images/calendar/leftArrow.gif\" width=\"15\" height=\"15\" vspace=\"0\" align=\"middle\" onmouseup='setPreviousYear()'> " +
//		"<input type=\"image\" src=\"images/calendar/rightArrow.gif\" width=\"15\" height=\"15\" vspace=\"0\" align=\"middle\" onmouseup='setNextYear()'><br>" +

}

function updateCookie(name) {
	if (readCookie('date['+ name +']') == '') {
		setCookie('date['+ name +']', name);
	} else {
		setCookie('date['+ name +']', '');
	}
}

//вывод самого календаря
function getMainPartCalendar() {
    var calDoc = calendarBegin;

    // GET MONTH, AND YEAR FROM GLOBAL CALENDAR DATE
    month   = calDate.getMonth();
    year    = calDate.getFullYear();

    // GET GLOBALLY-TRACKED DAY VALUE (PREVENTS JAVASCRIPT DATE ANOMALIES)
    day     = calDay;

    var i   = 0;

    // DETERMINE THE NUMBER OF DAYS IN THE CURRENT MONTH
    var days = getDaysInMonth();

    // IF GLOBAL DAY VALUE IS > THAN DAYS IN MONTH, HIGHLIGHT LAST DAY IN MONTH
    if (day > days) {
        day = days;
    }

    // DETERMINE WHAT DAY OF THE WEEK THE CALENDAR STARTS ON
    var firstOfMonth = new Date (year, month, 1);

    // GET THE DAY OF THE WEEK THE FIRST DAY OF THE MONTH FALLS ON
    var startingPos = firstOfMonth.getDay();
    days += startingPos;

    // KEEP TRACK OF THE COLUMNS, START A NEW ROW AFTER EVERY 7 COLUMNS
    var columnCount = 0;

    // MAKE BEGINNING NON-DATE CELLS BLANK
    for (i = 0; i < startingPos; i++) {
        calDoc += blankCell;
		columnCount++;
    }

    // SET VALUES FOR DAYS OF THE MONTH
    var outputDay = 0;
    var dayType    = "weekday";

    // DATE CELLS CONTAIN A NUMBER
    for (i = startingPos; i < days; i++) {

	var paddingChar = "&nbsp;";

        // GET THE DAY CURRENTLY BEING WRITTEN
        outputDay = i-startingPos+1;

        // SET THE TYPE OF DAY, THE focusDay GENERALLY APPEARS AS A DIFFERENT COLOR
//        if (currentDay == day) {
//            dayType = "focusDay";
//        }
//        else {
//            dayType = "weekDay";
//        }

		var temp_outputday = parseInt(outputDay);
		if (temp_outputday<10) {
			outputDay='0'+outputDay;
		}
		var temp_month=(parseInt(month) + 1);
		if (temp_month<10) {
			index = year + '0' + (parseInt(month) + 1) + '' + outputDay;
		} else {
			index = year + ''+(parseInt(month) + 1) + '' + outputDay;
		}

		test = eval('Days[index]');
		//if (year == '2003' && month == '11' && outputDay == '06') alert(index);
		//if (test==null) test = 1;


		if (scriptName == '/booked.php' || showHiddenYear == 'yes') {
			if (currentMonth == month && currentDay > outputDay) {
				dayType = "dateType1";
			} else {
				if (test >0 && test<5) {
					dayType = "dateType" + test;
				} else {
//			        if (columnCount % 7 == 0 || columnCount % 7 == 5 || columnCount % 7 == 6) {
//						dayType = "dateType4";
//					} else {
						dayType = "dateType1";
//					}
				}
			}
		} else {
			if (test >0 && test<5) {
				dayType = "dateType" + test;
			} else {
//		        if (columnCount % 7 == 0 || columnCount % 7 == 5 || columnCount % 7 == 6) {
//					dayType = "dateType4";
//				} else {
					dayType = "dateType1";
//				}
			}
		}

//		if ((scriptName == '/booked.php' && (test == 3 || test == 4)) || scriptName != '/booked.php' || columnCount % 7 == 0 || columnCount % 7 == 5 || columnCount % 7 == 6) {
		if ((scriptName == '/booked.php' && (test == 3 || test == 4)) || scriptName != '/booked.php') {
			if (scriptName != '/booked.php') {
				dayLink = "<a href='javascript: returnDate(" + outputDay + ")' style=\"font-size:10pt;\">" + outputDay + "</a>&nbsp;";
			} else {
				if (currentMonth == month && currentDay > outputDay) {
					dayLink = outputDay;
				} else {
					if (readCookie("date[" + year + '-' + (parseInt(month) + 1) + '-' + outputDay + "]") != '') {
						dayLink = "<a href='javascript: returnDate(" + outputDay + ")' style=\"font-size:10pt;\">" + outputDay + "</a> <input type=\"checkbox\" onClick=\"javascript: updateCookie('" + year + '-' + (parseInt(month) + 1) + '-' + outputDay + "')\" checked>&nbsp;";
					} else {
						dayLink = "<a href='javascript: returnDate(" + outputDay + ")' style=\"font-size:10pt;\">" + outputDay + "</a> <input type=\"checkbox\" onClick=\"javascript: updateCookie('" + year + '-' + (parseInt(month) + 1) + '-' + outputDay + "')\">&nbsp;";
					}
				}
			}
		} else {
			dayLink = outputDay;
		}

        // ADD THE DAY TO THE CALENDAR STRING
        calDoc += "<td class=\"" + dayType + "\" valign=\"middle\" align=\"right\" style=\"font-size:10pt;\">" + dayLink + "</td>";

        columnCount++;

        // START A NEW ROW WHEN NECESSARY
        if (columnCount % 7 == 0) {
            calDoc += "</tr><tr>";
        }
    }

    // MAKE REMAINING NON-DATE CELLS BLANK
    for (i=days; i<42; i++)  {
        calDoc += blankCell;
		columnCount++;

        // START A NEW ROW WHEN NECESSARY
        if (columnCount % 7 == 0) {
            calDoc += "</tr>";
			break;
//            if (i<41) {
//                calDoc += "<tr>";
//            }
        }
    }

    // FINISH THE NEW CALENDAR PAGE
    calDoc += calendarEnd;

    // RETURN THE COMPLETED CALENDAR PAGE
    return calDoc;
}


//запись календаря во фрейм
function writeCalendar() {
	setInitialDate();
    // CREATE THE NEW CALENDAR FOR THE SELECTED MONTH & YEAR

	navigation = getNavigationPartCalendar();
    mainPart = getMainPartCalendar();

	var theObj = document.getElementById('calendar');
	if (theObj) theObj.innerHTML = navigation + mainPart;
}
/*
//утановка календаря в текущую дату и прорисовка нового календаря
function setToday() {
    calDate = new Date();
    var month = calDate.getMonth();
    var year  = calDate.getFullYear();

	document.calendar.month.selectedIndex = month;
    document.calendar.year.value = year;

    writeCalendar();
}
*/

// SET THE GLOBAL DATE TO THE NEWLY ENTERED YEAR AND REDRAW THE CALENDAR
function setYear() {
    var year  = document.calendar.year.value;
	if (event.keyCode == 13) {
		if (isFourDigitYear(year)) {
        	calDate.setFullYear(year);
	        writeCalendar();
	    } else {
    	    document.calendar.year.focus();
        	document.calendar.year.select();
	    }
	}
}

// SET THE GLOBAL DATE TO THE PREVIOUS YEAR AND REDRAW THE CALENDAR
function setPreviousYear() {
    var year  = document.calendar.year.value;
    if (isFourDigitYear(year) && year > 1000) {
		year--;
		calDate.setFullYear(year);
		document.calendar.year.value = year;
		setCookie('yearClient', document.calendar.year.value);
		writeCalendar();
    }
}

// SET THE GLOBAL DATE TO THE NEXT YEAR AND REDRAW THE CALENDAR
function setNextYear() {
    var year  = document.calendar.year.value;
    if (isFourDigitYear(year)) {
        year++;
		calDate.setFullYear(year);
		document.calendar.year.value = year;
		setCookie('yearClient', document.calendar.year.value);
        writeCalendar();
    }
}

// SET THE GLOBAL DATE TO THE SELECTED MONTH AND REDRAW THE CALENDAR
function setCurrentMonth() {
    var month = document.calendar.month.selectedIndex;
    /**
    * To prevent month loosing in popup calendar
    *
    * @since 2005.06.23
    * @author Alexander Kaplun
    */
    setCookie('monthClient', document.calendar.month.value);
    /**
    * 2005.06.23 END
    */
    calDate.setMonth(document.calendar.month.value);
    writeCalendar();
}

//получить количество дней в месяце
function getDaysInMonth()  {

    var days;
    var month = calDate.getMonth()+1;
    var year  = calDate.getFullYear();

    if (month==1 || month==3 || month==5 || month==7 || month==8 ||
        month==10 || month==12)  {
        days=31;
    } else if (month==4 || month==6 || month==9 || month==11) {
        days=30;
    } else if (month==2)  {
        if (isLeapYear(year)) {
            days=29;
        }
        // RETURN 28 DAYS
        else {
            days=28;
        }
    }
    return (days);
}

//является ли год высокосным
function isLeapYear (Year) {
    if (((Year % 4)==0) && ((Year % 100)!=0) || ((Year % 400)==0)) {
        return (true);
    }
    else {
        return (false);
    }
}

// ENSURE THAT THE YEAR IS FOUR DIGITS IN LENGTH
function isFourDigitYear(year) {

    if (year.length != 4) {
        document.calendar.year.value = calDate.getFullYear();
        document.calendar.year.select();
        document.calendar.year.focus();
    }
    else {
        return true;
    }
}

//получение названия месяца
function getMonthName() {
	var monthArray = new Array('JANUARY', 'FEBRUARY', 'MARCH', 'APRIL', 'MAY', 'JUNE', 'JULY', 'AUGUST', 'SEPTEMBER', 'OCTOBER', 'NOVEMBER', 'DECEMBER');
    var activeMonth = calDate.getMonth();
	return monthArray[activeMonth];
}

// BUILD THE MONTH SELECT LIST
function getMonthSelect() {
	monthArray = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');

    // DETERMINE MONTH TO SET AS DEFAULT
    var activeMonth = calDate.getMonth();

    // START HTML SELECT LIST ELEMENT
    monthSelect = "<select id=\"month\" name=\"month\" onChange=\"setCurrentMonth()\" class=\"monthSelect\">";

    // LOOP THROUGH MONTH ARRAY
	if (scriptName == '/booked.php') i = currentMonth;
	else i=0;

    while (i<12) {
        // SHOW THE CORRECT MONTH IN THE SELECT LIST
        if (i == activeMonth) {
            monthSelect += "<option value=\"" + i + "\" selected>" + monthArray[i] + "\n";
        }
        else {
            monthSelect += "<option value=\"" + i + "\">" + monthArray[i] + "\n";
        }
		i++;
    }
    monthSelect += "</select>";

    // RETURN A STRING VALUE WHICH CONTAINS A SELECT LIST OF ALL 12 MONTHS
    return monthSelect;
}


// SET DAYS OF THE WEEK DEPENDING ON LANGUAGE
function createWeekdayList() {
	weekdayList  = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
    weekdayArray = new Array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');

    // START HTML TO HOLD WEEKDAY NAMES IN TABLE FORMAT
    var weekdays = "<tr>";

    // LOOP THROUGH WEEKDAY ARRAY
    for (i in weekdayArray) {
        weekdays += "<td class=\"dayOfWeek\">" + weekdayArray[i] + "</td>";
    }
    weekdays += "</tr>";

    // RETURN TABLE ROW OF WEEKDAY ABBREVIATIONS TO DISPLAY ABOVE THE CALENDAR
    return weekdays;
}


// PRE-BUILD PORTIONS OF THE CALENDAR (FOR PERFORMANCE REASONS)
function buildCalParts() {

    // GENERATE WEEKDAY HEADERS FOR THE CALENDAR
    weekdays = createWeekdayList();

    // BUILD THE BLANK CELL ROWS
    blankCell = "<td align=\"center\">&nbsp;&nbsp;&nbsp;</td>";

    // BUILD THE TOP PORTION OF THE CALENDAR PAGE USING CSS TO CONTROL SOME DISPLAY ELEMENTS
    calendarBegin = "<tr><td colspan=\"2\">";

        // NAVIGATOR NEEDS A TABLE CONTAINER TO DISPLAY THE TABLE OUTLINES PROPERLY
        if (isNav) {
            calendarBegin +=
                "<table cellpadding=\"0\" cellspacing=\"1\" align=\"center\"><tr><td>";
        }

        // BUILD WEEKDAY HEADINGS
        calendarBegin +=
            "<table cellpadding=\"0\" cellspacing=\"1\" align=\"center\">" +
            weekdays +
            "<tr>";


    // BUILD THE BOTTOM PORTION OF THE CALENDAR PAGE
    calendarEnd = "";

        // WHETHER OR NOT TO DISPLAY A THICK LINE BELOW THE CALENDAR
        if (bottomBorder) {
            calendarEnd += "<tr></tr>";
        }

        // NAVIGATOR NEEDS A TABLE CONTAINER TO DISPLAY THE BORDERS PROPERLY
        if (isNav) {
            calendarEnd += "</td></tr></table>";
        }

        // END THE TABLE AND HTML DOCUMENT
        calendarEnd +=
			"</table></td></tr>" +
			"<tr><td colspan=\"2\" class=\"navigation\"><img src=\"images/calendar/pixel.gif\" width=\"1\" height=\"3\"></td></tr>" +
			"<tr><td colspan=\"2\" align=\"center\"><img src=\"images/calendar/legenda.gif\" width=\"308\" height=\"11\" vspace=\"5\"></td></tr>" +
			"<tr><td colspan=\"2\" background=\"dot.gif\"><img src=\"images/calendar/pixel.gif\" width=\"1\" height=\"3\"></td></tr>" +
			"</table></td></tr></table>";
}


// REPLACE ALL INSTANCES OF find WITH replace
// inString: the string you want to convert
// find:     the value to search for
// replace:  the value to substitute
//
// usage:    jsReplace(inString, find, replace);
// example:  jsReplace("To be or not to be", "be", "ski");
//           result: "To ski or not to ski"
//
function jsReplace(inString, find, replace) {

    var outString = "";

    if (!inString) {
        return "";
    }

    // REPLACE ALL INSTANCES OF find WITH replace
    if (inString.indexOf(find) != -1) {
        // SEPARATE THE STRING INTO AN ARRAY OF STRINGS USING THE VALUE IN find
        t = inString.split(find);

        // JOIN ALL ELEMENTS OF THE ARRAY, SEPARATED BY THE VALUE IN replace
        return (t.join(replace));
    }
    else {
        return inString;
    }
}


// JAVASCRIPT FUNCTION -- DOES NOTHING (USED FOR THE HREF IN THE CALENDAR CALL)
function doNothing() {
}


// ENSURE THAT VALUE IS TWO DIGITS IN LENGTH
function makeTwoDigit(inValue) {

    var numVal = parseInt(inValue, 10);

    // VALUE IS LESS THAN TWO DIGITS IN LENGTH
    if (numVal < 10) {

        // ADD A LEADING ZERO TO THE VALUE AND RETURN IT
        return("0" + numVal);
    }
    else {
        return numVal;
    }
}

// SET FIELD VALUE TO THE DATE SELECTED AND CLOSE THE CALENDAR WINDOW
function returnDate(day)
{
//	document.calendar.day.value = day;
//	document.send.month.value = parseInt(document.calendar.month.value) + 1;

	if (scriptName == '/booked.php') {
		setCookie("yearClient", document.calendar.year.value);
		setCookie("monthClient", document.calendar.month.value);
	} else {
		setCookie("yearAdmin", document.calendar.year.value);
		setCookie("monthAdmin", document.calendar.month.value);
	}

	if (action != "getDate") {
		document.send.day.value = day;
		document.send.month.value = parseInt(document.calendar.month.value) + 1;
		document.send.year.value = parseInt(document.calendar.year.value);
		document.send.reservationsId.value = parseInt(document.calendar.reservationsId.value);
		document.send.submit();
	} else {
		month = parseInt(document.calendar.month.value) + 1;

		if (month < 10) month = "0" + month;
		if (day < 10) day = "0" + day;

		element = window.opener.document.getElementById(field);
		element.value = month + "/" + day + "/" + document.calendar.year.value;
		window.close();
	}
}

function changeLocation(message, section) {
	setCookie('message', message);
	setCookie('section', section);
    var staging = location.href.indexOf('/staging') != -1 ? '/staging' : '';
	location.href = 'http://'+location.host+staging+'/hayrides.php';
}