//calDateFormat    = "DD/MM/YY";
//calDateFormat    = "MM-DD-YY";
calDateFormat    = "YY-MM-DD";
// 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    = buildTopCalFrame();
    calDocBottom = buildBottomCalFrame();
}

// SET THE INITIAL CALENDAR DATE TO TODAY OR TO THE EXISTING VALUE IN dateField
function setInitialDate() {
    // CREATE A NEW DATE OBJECT (WILL GENERALLY PARSE CORRECT DATE EXCEPT WHEN "." IS USED AS A DELIMITER)
    // (THIS ROUTINE DOES *NOT* CATCH ALL DATE FORMATS, IF YOU NEED TO PARSE A CUSTOM DATE FORMAT, DO IT HERE)
    calDate = new Date(inDate);

//	if(inDate != "") {
//		var arr = inDate.split("-");
//		calDate = new Date(arr[2], arr[1]-1, arr[0]);
//  }

    // IF THE INCOMING DATE IS INVALID, USE THE CURRENT DATE
    if (isNaN(calDate)) {
        // ADD CUSTOM DATE PARSING HERE
        // IF IT FAILS, SIMPLY CREATE A NEW DATE OBJECT WHICH DEFAULTS TO THE CURRENT DATE
        calDate = new Date();
    }

    // KEEP TRACK OF THE CURRENT DAY VALUE
    calDay  = calDate.getDate();
    // SET DAY VALUE TO 1... TO AVOID JAVASCRIPT DATE CALCULATION ANOMALIES
    // (IF THE MONTH CHANGES TO FEB AND THE DAY IS 30, THE MONTH WOULD CHANGE TO MARCH
    //  AND THE DAY WOULD CHANGE TO 2.  SETTING THE DAY TO 1 WILL PREVENT THAT)
    calDate.setDate(1);
}

// POPUP A WINDOW WITH THE CALENDAR IN IT
function showCalendar(dateField) {
    // SET INITIAL VALUE OF THE DATE FIELD AND CREATE TOP AND BOTTOM FRAMES
    setDateField(dateField);
	calDocFrameset = parent.opener.calDocTop + parent.opener.calDocBottom;
    // DISPLAY THE CALENDAR IN A NEW POPUP WINDOW
    top.newWin = window.open("javascript:parent.opener.calDocFrameset", "calWin", winPrefs);
    top.newWin.focus();
}

//навигационная панель
function buildTopCalFrame() {
    var calDoc =
        "<html><head><title>Calendar</title><link href=\"style.css\" rel=\"stylesheet\" type=\"text/css\"></head><body marginheight=\"0\" topmargin=\"0\" marginheight=\"0\" leftmargin=\"0\">" +
		"<div align=\"right\">" + getMonthName() + " / " + calDate.getFullYear() + "&nbsp;</div>" +
		"<center><table border=\"0\" cellpadding=\"1\" cellspacing=\"0\">" +
		"<tr><td colspan=\"2\" background=\"dot.gif\"><img src=\"pixel.gif\" width=\"1\" height=\"3\"></td></tr>" +
		"<tr><td colspan=\"2\"><img src=\"pixel.gif\" width=\"1\" height=\"3\"></td></tr>" +
		"<tr><td class=\"navigation\">" +
        getMonthSelect() +
        "</td><form onsubmit=\"return false;\"><td class=\"navigation\" align=\"right\"><input name=\"year\" value=\"" + calDate.getFullYear() + "\" type=\"text\" size=\"8\" maxlength=\"4\" onkeyup=\"parent.opener.setYear();\"> " +
        "<input type=\"image\" src=\"leftArrow.gif\" width=\"15\" height=\"15\" vspace=\"0\" align=\"middle\" onmouseup='parent.opener.setPreviousYear()'> " +
		"<input type=\"image\" src=\"rightArrow.gif\" width=\"15\" height=\"15\" vspace=\"0\" align=\"middle\" onmouseup='parent.opener.setNextYear()'><br>" +
        "</td></form></tr>";
    return calDoc;
}

//вывод самого календаря
function buildBottomCalFrame() {
    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();
//	if(startingPos == 0) startingPos = 7;
//    else startingPos = startingPos - 1;
    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 currentDay = 0;
    var dayType    = "weekday";

    // DATE CELLS CONTAIN A NUMBER
    for (i = startingPos; i < days; i++) {

	var paddingChar = "&nbsp;";

        // GET THE DAY CURRENTLY BEING WRITTEN
        currentDay = i-startingPos+1;

        // SET THE TYPE OF DAY, THE focusDay GENERALLY APPEARS AS A DIFFERENT COLOR
        if (currentDay == day) {
            dayType = "focusDay";
        }
        else {
            if (startingPos == 0)
                dayType = "weekDay";
            else
            	dayType = "weekDay";
        }

        // ADD THE DAY TO THE CALENDAR STRING
        calDoc += "<td class=\"" + dayType + "\" valign=\"middle\">" +
                  "<a class=\"" + dayType + "\" href='javascript:parent.opener.returnDate(" +
                  currentDay + ")'>" + currentDay + "</a></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() {
    // CREATE THE NEW CALENDAR FOR THE SELECTED MONTH & YEAR
	calDoc = buildTopCalFrame();
    calDocBottom = buildBottomCalFrame();
    // WRITE THE NEW CALENDAR TO THE BOTTOM FRAME
	top.newWin.document.close();
	top.newWin.document.open();
	top.newWin.document.write(calDoc + calDocBottom);
	top.newWin.document.close();
}

//утановка календаря в текущую дату и прорисовка нового календаря
function setToday() {
    calDate = new Date();
    var month = calDate.getMonth();
    var year  = calDate.getFullYear();
	top.newWin.document.all.month.selectedIndex = month;
    top.newWin.document.all.year.value = year;
    writeCalendar();
}


// SET THE GLOBAL DATE TO THE NEWLY ENTERED YEAR AND REDRAW THE CALENDAR
function setYear() {
    var year  = top.newWin.document.all.year.value;
	if (top.newWin.event.keyCode == 13) {
		if (isFourDigitYear(year)) {
        	calDate.setFullYear(year);
	        writeCalendar();
	    } else {
    	    top.newWin.document.all.year.focus();
        	top.newWin.document.all.year.select();
	    }
	}
}

// SET THE GLOBAL DATE TO THE SELECTED MONTH AND REDRAW THE CALENDAR
function setCurrentMonth() {
    var month = top.newWin.document.all.month.selectedIndex;
    calDate.setMonth(month);
    writeCalendar();
}

// SET THE GLOBAL DATE TO THE PREVIOUS YEAR AND REDRAW THE CALENDAR
function setPreviousYear() {
    var year  = top.newWin.document.all.year.value;
    if (isFourDigitYear(year) && year > 1000) {
        year--;
        calDate.setFullYear(year);
        top.newWin.document.all.year.value = year;
        writeCalendar();
    }
}

// SET THE GLOBAL DATE TO THE PREVIOUS MONTH AND REDRAW THE CALENDAR
function setPreviousMonth() {
    var year  = top.newWin.document.all.year.value;
    if (isFourDigitYear(year)) {
        var month = top.newWin.document.all.month.selectedIndex;
        // IF MONTH IS JANUARY, SET MONTH TO DECEMBER AND DECREMENT THE YEAR
        if (month == 0) {
            month = 11;
            if (year > 1000) {
                year--;
                calDate.setFullYear(year);
                top.newWin.document.all.year.value = year;
            }
        }
        else {
            month--;
        }
        calDate.setMonth(month);
        top.newWin.document.all.month.selectedIndex = month;
        writeCalendar();
    }
}

// SET THE GLOBAL DATE TO THE NEXT MONTH AND REDRAW THE CALENDAR
function setNextMonth() {
    var year = top.newWin.document.all.year.value;
    if (isFourDigitYear(year)) {
        var month = top.newWin.document.all.month.selectedIndex;
        // IF MONTH IS DECEMBER, SET MONTH TO JANUARY AND INCREMENT THE YEAR
        if (month == 11) {
            month = 0;
            year++;
            calDate.setFullYear(year);
            top.newWin.document.all.year.value = year;
        }
        else {
            month++;
        }
        calDate.setMonth(month);
        top.newWin.document.all.month.selectedIndex = month;
        writeCalendar();
    }
}

// SET THE GLOBAL DATE TO THE NEXT YEAR AND REDRAW THE CALENDAR
function setNextYear() {
    var year  = top.newWin.document.all.year.value;
    if (isFourDigitYear(year)) {
        year++;
        calDate.setFullYear(year);
        top.newWin.document.all.year.value = year;
        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) {
        top.newWin.document.all.year.value = calDate.getFullYear();
        top.newWin.document.all.year.select();
        top.newWin.document.all.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 name=\"month\" onChange=\"parent.opener.setCurrentMonth()\" class=\"monthSelect\">";

    // LOOP THROUGH MONTH ARRAY
    for (i in monthArray) {
        // SHOW THE CORRECT MONTH IN THE SELECT LIST
        if (i == activeMonth) {
            monthSelect += "<option selected>" + monthArray[i] + "\n";
        }
        else {
            monthSelect += "<option>" + monthArray[i] + "\n";
        }
    }
    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','Wen','The','Fri','Sat');
    // START HTML TO HOLD WEEKDAY NAMES IN TABLE FORMAT
    var weekdays = "<tr>";
    // LOOP THROUGH WEEKDAY ARRAY
    for (i in weekdayArray) {
        if (i == 0)
          weekdays += "<td class=\"dayOfWeeksun\">" + weekdayArray[i] + "</td>";
        else
          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=\"pixel.gif\" width=\"1\" height=\"3\"></td></tr>" +
			"<tr><td colspan=\"2\" background=\"dot.gif\"><img src=\"pixel.gif\" width=\"1\" height=\"3\"></td></tr>" +
			"</table></center></body></html>";
}


// 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(inDay)
{
    // inDay = THE DAY THE USER CLICKED ON
    calDate.setDate(inDay);
    // SET THE DATE RETURNED TO THE USER
    var day           = calDate.getDate();
    var month         = calDate.getMonth()+1;
    var year          = calDate.getFullYear();
    var monthString   = monthArray[calDate.getMonth()];
    var monthAbbrev   = monthString.substring(0,3);
    var weekday       = weekdayList[calDate.getDay()];
    var weekdayAbbrev = weekday.substring(0,3);

    outDate = calDateFormat;

    // RETURN TWO DIGIT DAY
    if (calDateFormat.indexOf("DD") != -1) {
        day = makeTwoDigit(day);
        outDate = jsReplace(outDate, "DD", day);
    }
    // RETURN ONE OR TWO DIGIT DAY
    else if (calDateFormat.indexOf("dd") != -1) {
        outDate = jsReplace(outDate, "dd", day);
    }

    // RETURN TWO DIGIT MONTH
    if (calDateFormat.indexOf("MM") != -1) {
        month = makeTwoDigit(month);
        outDate = jsReplace(outDate, "MM", month);
    }
    // RETURN ONE OR TWO DIGIT MONTH
    else if (calDateFormat.indexOf("mm") != -1) {
        outDate = jsReplace(outDate, "mm", month);
    }

    // RETURN FOUR-DIGIT YEAR
    if (calDateFormat.indexOf("yyyy") != -1) {
        outDate = jsReplace(outDate, "yyyy", year);
    }
    // RETURN TWO-DIGIT YEAR
    else if (calDateFormat.indexOf("yy") != -1) {
        var yearString = "" + year;
        var yearString = yearString.substring(2,4);
        outDate = jsReplace(outDate, "yy", yearString);
    }
    // RETURN FOUR-DIGIT YEAR
    else if (calDateFormat.indexOf("YY") != -1) {
        outDate = jsReplace(outDate, "YY", year);
    }

    // RETURN DAY OF MONTH (Initial Caps)
    if (calDateFormat.indexOf("Month") != -1) {
        outDate = jsReplace(outDate, "Month", monthString);
    }
    // RETURN DAY OF MONTH (lowercase letters)
    else if (calDateFormat.indexOf("month") != -1) {
        outDate = jsReplace(outDate, "month", monthString.toLowerCase());
    }
    // RETURN DAY OF MONTH (UPPERCASE LETTERS)
    else if (calDateFormat.indexOf("MONTH") != -1) {
        outDate = jsReplace(outDate, "MONTH", monthString.toUpperCase());
    }

    // RETURN DAY OF MONTH 3-DAY ABBREVIATION (Initial Caps)
    if (calDateFormat.indexOf("Mon") != -1) {
        outDate = jsReplace(outDate, "Mon", monthAbbrev);
    }
    // RETURN DAY OF MONTH 3-DAY ABBREVIATION (lowercase letters)
    else if (calDateFormat.indexOf("mon") != -1) {
        outDate = jsReplace(outDate, "mon", monthAbbrev.toLowerCase());
    }
    // RETURN DAY OF MONTH 3-DAY ABBREVIATION (UPPERCASE LETTERS)
    else if (calDateFormat.indexOf("MON") != -1) {
        outDate = jsReplace(outDate, "MON", monthAbbrev.toUpperCase());
    }

    // RETURN WEEKDAY (Initial Caps)
    if (calDateFormat.indexOf("Weekday") != -1) {
        outDate = jsReplace(outDate, "Weekday", weekday);
    }
    // RETURN WEEKDAY (lowercase letters)
    else if (calDateFormat.indexOf("weekday") != -1) {
        outDate = jsReplace(outDate, "weekday", weekday.toLowerCase());
    }
    // RETURN WEEKDAY (UPPERCASE LETTERS)
    else if (calDateFormat.indexOf("WEEKDAY") != -1) {
        outDate = jsReplace(outDate, "WEEKDAY", weekday.toUpperCase());
    }

    // RETURN WEEKDAY 3-DAY ABBREVIATION (Initial Caps)
    if (calDateFormat.indexOf("Wkdy") != -1) {
        outDate = jsReplace(outDate, "Wkdy", weekdayAbbrev);
    }
    // RETURN WEEKDAY 3-DAY ABBREVIATION (lowercase letters)
    else if (calDateFormat.indexOf("wkdy") != -1) {
        outDate = jsReplace(outDate, "wkdy", weekdayAbbrev.toLowerCase());
    }
    // RETURN WEEKDAY 3-DAY ABBREVIATION (UPPERCASE LETTERS)
    else if (calDateFormat.indexOf("WKDY") != -1) {
        outDate = jsReplace(outDate, "WKDY", weekdayAbbrev.toUpperCase());
    }

    // SET THE VALUE OF THE FIELD THAT WAS PASSED TO THE CALENDAR
    calDateField.value = outDate;

    // GIVE FOCUS BACK TO THE DATE FIELD
    calDateField.focus();

    // CLOSE THE CALENDAR WINDOW
    top.newWin.close()
}



