﻿
var firstTime12 = true;
var firstTime34 = true;
function PickerLoad(n) {
    //alert("hello");
    var date = document.getElementById('date' + n).getElementsByTagName("input")[0];
    // initialise the "Select date" link
    $('#date-pick' + n)
					.datePicker(
    // associate the link with a date picker
						{
						createButton: false,
						startDate: '01/01/2009',
						endDate: '31/12/2019'
		}
					).bind(
    // when the link is clicked display the date picker
						'click',
						function() {
						    updateSelects($(this).dpGetSelected()[0]);
						    $(this).dpDisplay();
						    return false;
						}
					).bind(
    // when a date is selected update the SELECTs
						'dateSelected',
						function(e, selectedDate, $td, state) {
						    updateSelects(selectedDate);
						}
					).bind(
						'dpClosed',
						function(e, selected) {
						    updateSelects(selected[0]);
						}
					);

    var updateSelects = function(selectedDate) {
        selectedDate = new Date(selectedDate);
        var d = selectedDate.getDate();
        var m = selectedDate.getMonth();
        var y = selectedDate.getFullYear();
        ($('#d' + n)[0]).selectedIndex = d - 1;
        ($('#m' + n)[0]).selectedIndex = m;
        ($('#y' + n)[0]).selectedIndex = y - 2009;

        date.value = "" + d + "." + (m + 1) + "." + y;
        setByDay(selectedDate, n);
    }
    // listen for when the selects are changed and update the picker
    $('#d' + n + ', #m' + n + ', #y' + n)
					.bind(
						'change',
						function() {
						    var d = new Date(
										$('#y' + n).val(),
										$('#m' + n).val() - 1,
										$('#d' + n).val()
									);
						    $('#date-pick' + n).dpSetSelected(d.asString());
						    date.value = "" + d.getDate() + "." + (d.getMonth() + 1) + "." + d.getFullYear();
						    setByDay(d, n);
						}
					);

    // default the position of the selects to today

    if (date.value.length > 7) {
        //alert("ddd  " + n);
        var ar = date.value.split(/[\.\/]/);
        ($('#d' + n)[0]).selectedIndex = eval(ar[0]) - 1;
        ($('#m' + n)[0]).selectedIndex = eval(ar[1]) - 1;
        ($('#y' + n)[0]).selectedIndex = eval(ar[2]) - 2009;
    }
    else {
        var today = new Date();
        if ((n == '2') || (n == '4'))
            today.setDate(today.getDate() + 1);
        ($('#d' + n)[0]).selectedIndex = today.getDate() - 1;
        ($('#m' + n)[0]).selectedIndex = today.getMonth();
        ($('#y' + n)[0]).selectedIndex = today.getFullYear() - 2009;

        date.value = "" + today.getDate() + "." + (today.getMonth() + 1) + "." + today.getFullYear();
    }
    // and update the datePicker to reflect it...
    $('#d' + n).trigger('change');
}

function setByDay(date, n) {
    if ((firstTime12) && (n == '1')) {
        firstTime12 = false;
        return;
    }
    if ((firstTime34) && (n == '3')) {
        firstTime34 = false;
        return;
    }
    var next;
    var i = 1;
    if ((n == '1') || (n == '3')) {
        next = eval(n) + 1;
        date.setDate(date.getDate() + 1);
    }
    else {
        i = -1;
        next = eval(n) - 1;
        date.setDate(date.getDate() - 1);
    }
    var y = (($('#y' + next)[0]).selectedIndex - ($('#y' + n)[0]).selectedIndex) * i;
    var m = (($('#m' + next)[0]).selectedIndex - ($('#m' + n)[0]).selectedIndex) * i;
    var d = (($('#d' + next)[0]).selectedIndex - ($('#d' + n)[0]).selectedIndex) * i;
    if (y > 0) return;
    if ((y == 0) && (m > 0)) return;
    if ((m == 0) && (d > 0)) return;


    ($('#d' + next)[0]).selectedIndex = date.getDate() - 1;
    ($('#m' + next)[0]).selectedIndex = date.getMonth();
    ($('#y' + next)[0]).selectedIndex = date.getFullYear() - 2009;
    $('#date-pick' + next).dpSetSelected(date.asString());
    var inputDate = document.getElementById('date' + next).getElementsByTagName("input")[0];
    inputDate.value = "" + date.getDate() + "." + (date.getMonth() + 1) + "." + date.getFullYear();
}


Date.dayNames =  dayNames ; //['Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота'];
Date.abbrDayNames =  abbrDayNames ; //['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'];
Date.monthNames = monthNames; //['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Нояборь', 'Декабрь'];
Date.abbrMonthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
Date.firstDayOfWeek = 1;

Date.format = 'dd/mm/yyyy';
//Date.format = 'mm/dd/yyyy';
//Date.format = 'yyyy-mm-dd';
//Date.format = 'dd mmm yy';
Date.fullYearStart = '20';

(function() {
    function add(name, method) {
        if (!Date.prototype[name]) {
            Date.prototype[name] = method;
        }
    };


    add("isLeapYear", function() {
        var y = this.getFullYear();
        return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
    });


    add("isWeekend", function() {
        return this.getDay() == 0 || this.getDay() == 6;
    });


    add("isWeekDay", function() {
        return !this.isWeekend();
    });


    add("getDaysInMonth", function() {
        return [31, (this.isLeapYear() ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][this.getMonth()];
    });


    add("getDayName", function(abbreviated) {
        return abbreviated ? Date.abbrDayNames[this.getDay()] : Date.dayNames[this.getDay()];
    });


    add("getMonthName", function(abbreviated) {
        return abbreviated ? Date.abbrMonthNames[this.getMonth()] : Date.monthNames[this.getMonth()];
    });


    add("getDayOfYear", function() {
        var tmpdtm = new Date("1/1/" + this.getFullYear());
        return Math.floor((this.getTime() - tmpdtm.getTime()) / 86400000);
    });


    add("getWeekOfYear", function() {
        return Math.ceil(this.getDayOfYear() / 7);
    });


    add("setDayOfYear", function(day) {
        this.setMonth(0);
        this.setDate(day);
        return this;
    });


    add("addYears", function(num) {
        this.setFullYear(this.getFullYear() + num);
        return this;
    });


    add("addMonths", function(num) {
        var tmpdtm = this.getDate();

        this.setMonth(this.getMonth() + num);

        if (tmpdtm > this.getDate())
            this.addDays(-this.getDate());

        return this;
    });


    add("addDays", function(num) {
        this.setDate(this.getDate() + num);
        return this;
    });


    add("addHours", function(num) {
        this.setHours(this.getHours() + num);
        return this;
    });


    add("addMinutes", function(num) {
        this.setMinutes(this.getMinutes() + num);
        return this;
    });


    add("addSeconds", function(num) {
        this.setSeconds(this.getSeconds() + num);
        return this;
    });


    add("zeroTime", function() {
        this.setMilliseconds(0);
        this.setSeconds(0);
        this.setMinutes(0);
        this.setHours(0);
        return this;
    });


    add("asString", function() {
        var r = Date.format;

        return r
			.split('yyyy').join(this.getFullYear())
			.split('yy').join((this.getFullYear() + '').substring(2))
			.split('mmm').join(this.getMonthName(true))
			.split('mm').join(_zeroPad(this.getMonth() + 1))
			.split('dd').join(_zeroPad(this.getDate()));
    });


    Date.fromString = function(s) {
        var f = Date.format;
        var d = new Date('01/01/1977');
        var iY = f.indexOf('yyyy');
        if (iY > -1) {
            d.setFullYear(Number(s.substr(iY, 4)));
        } else {
            // TODO - this doesn't work very well - are there any rules for what is meant by a two digit year?
            d.setFullYear(Number(Date.fullYearStart + s.substr(f.indexOf('yy'), 2)));
        }
        var iM = f.indexOf('mmm');
        if (iM > -1) {
            var mStr = s.substr(iM, 3);
            for (var i = 0; i < Date.abbrMonthNames.length; i++) {
                if (Date.abbrMonthNames[i] == mStr) break;
            }
            d.setMonth(i);
        } else {
            d.setMonth(Number(s.substr(f.indexOf('mm'), 2)) - 1);
        }
        d.setDate(Number(s.substr(f.indexOf('dd'), 2)));
        if (isNaN(d.getTime())) {
            return false;
        }
        return d;
    };

    // utility method
    var _zeroPad = function(num) {
        var s = '0' + num;
        return s.substring(s.length - 2)
        //return ('0'+num).substring(-2); // doesn't work on IE :(
    };

})();
