//----------------------------------------------------------------------------
function DateReplace4JQ (str) {     // превращение даты дд.мм.гггг в мм/дд/гггг для объекта Date
  if (str) {str = str.substring(3,5) + '/' + str.substring(0,2) + '/' + str.substring(6);}
	return str;
}
//----------------------------------------------------------------------------
/**
	the script only works on "input [type=text]"

**/

// don't declare anything out here in the global namespace

(function($) { // create private scope (inside you can use $ instead of jQuery)

  // functions and vars declared here are effectively 'singletons'.  there will be only a single
  // instance of them.  so this is a good place to declare any immutable items or stateless
  // functions.  for example:

	var today = new Date(); // used in defaults
	//    var months = 'January,February,March,April,May,June,July,August,September,October,November,December'.split(',');
  var months = 'Январь,Февраль,Март,Апрель,Май,Июнь,Июль,Август,Сентябрь,Октябрь,Ноябрь,Декабрь'.split(',');
	var monthlengths = '31,28,31,30,31,30,31,31,30,31,30,31'.split(',');
	//  	var dateRegEx = /^\d{1,2}\/\d{1,2}\/\d{2}|\d{4}$/;
  var dateRegEx = /^\d{2}\.\d{2}\.\d{4}$/;
	var yearRegEx = /^\d{4,4}$/;

  $.fn.simpleDatepicker = function(options) {
	  // next, declare the plugin function
    // functions and vars declared here are created each time your plugn function is invoked
    // you could probably refactor your 'build', 'load_month', etc, functions to be passed
    // the DOM element from below
		
		var opts = jQuery.extend({}, jQuery.fn.simpleDatepicker.defaults, options);
		// replaces a date string with a date object in opts.startdate and opts.enddate, if one exists
		// populates two new properties with a ready-to-use year: opts.startyear and opts.endyear

		setupYearRange();
		
		/** extracts and setup a valid year range from the opts object **/
		function setupYearRange () {

			var startyear, endyear;
			if (opts.startdate.constructor == Date) {
				startyear = opts.startdate.getFullYear();
			} else if (opts.startdate) {
				if (yearRegEx.test(opts.startdate)) {
				startyear = opts.startdate;
				} else if (dateRegEx.test(opts.startdate)) {
					opts.startdate = new Date(DateReplace4JQ(opts.startdate));
					startyear = opts.startdate.getFullYear();
				} else {
				startyear = today.getFullYear();
				}
			} else {
				startyear = today.getFullYear();
			}
			opts.startyear = startyear;

			if (opts.enddate.constructor == Date) {
				endyear = opts.enddate.getFullYear();
			} else if (opts.enddate) {
				if (yearRegEx.test(opts.enddate)) {
					endyear = opts.enddate;
				} else if (dateRegEx.test(opts.enddate)) {
					opts.enddate = new Date(DateReplace4JQ(opts.enddate));
					endyear = opts.enddate.getFullYear();
				} else {
					endyear = today.getFullYear();
				}
			} else {
				endyear = today.getFullYear();
			}
			opts.endyear = endyear;
		}

		function newDatepickerHTML () {
			/** HTML factory for the actual datepicker table element **/
			// has to read the year range so it can setup the correct years in our HTML <select>

			var years = [];

			// process year range into an array
			for (var i = 0; i <= opts.endyear - opts.startyear; i ++) years[i] = opts.startyear + i;

			// build the table structure
			var table = jQuery('<table class="datepicker" cellpadding="0" cellspacing="0"></table>');
			table.append('<thead></thead>');
			table.append('<tfoot></tfoot>');
			table.append('<tbody></tbody>');

			// month select field
			var monthselect = '<select name="month">';
			for (var i in months) monthselect += '<option value="'+i+'">'+months[i]+'</option>';
			monthselect += '</select>';

			// year select field
			var yearselect = '<select name="year">';
			for (var i in years) yearselect += '<option>'+years[i]+'</option>';
			yearselect += '</select>';
			
			jQuery("thead",table).append('<tr class="controls"><th colspan="7">&nbsp;<span class="prevMonth">&laquo;</span>&nbsp;<i class="title_month"></i>'+monthselect+yearselect+'&nbsp;<span class="nextMonth">&raquo;</span></th></tr>');
			jQuery("thead",table).append('<tr class="days"><th>пн</th><th>вт</th><th>ср</th><th>чт</th><th>пт</th><th class="w">сб</th><th class="w">вс</th></tr>');
			jQuery("tfoot",table).append('<tr><td colspan="6"><span class="today">сегодня</span><span class="reset">&nbsp;очистить&nbsp;</span></td><td title="закрыть"><span class="close">&nbsp;X&nbsp;</span></td></tr>');
			for (var i = 0; i < 6; i++) jQuery("tbody",table).append('<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>');
			
			return table;
		}

		function findPosition (obj) {
			/** get the real position of the input (well, anything really) **/
			//http://www.quirksmode.org/js/findpos.html
			var curleft = curtop = 0;
			if (obj.offsetParent) {
				do {
					curleft += obj.offsetLeft;
					curtop += obj.offsetTop;
				} while (obj = obj.offsetParent);
				return [curleft,curtop];
			} else {
				return false;
			}
		}

		function loadMonth (datepickers, e, el, datepicker, chosendate) {
			/** load the initial date and handle all date-navigation **/
			// initial calendar load (e is null)
			// prevMonth & nextMonth buttons
			// onchange for the select fields

			// reference our years for the nextMonth and prevMonth buttons
			var mo = jQuery("select[name=month]", datepicker).get(0).selectedIndex;
			var yr = jQuery("select[name=year]", datepicker).get(0).selectedIndex;
			var yrs = jQuery("select[name=year] option", datepicker).get().length;

//			alert(mo + ' ' + yr);
			
			// first try to process buttons that may change the month we're on
			if (e && jQuery(e.target).hasClass('prevMonth')) {
				if (mo <= 0 && yr) {
					yr = (yr == -1) ? yrs - 1 : yr - 1;
					mo = 11;
					jQuery("select[name=month]", datepicker).get(0).selectedIndex = mo;
					jQuery("select[name=year]", datepicker).get(0).selectedIndex = yr;
				} else {
					mo -= 1;
					jQuery("select[name=month]", datepicker).get(0).selectedIndex = mo;
				}
			} else if (e && jQuery(e.target).hasClass('nextMonth')) {
				if (11 == mo && yr + 1 < yrs) {
					yr += 1; mo = 0;
					jQuery("select[name=month]", datepicker).get(0).selectedIndex = 0;
					jQuery("select[name=year]", datepicker).get(0).selectedIndex = yr;
				} else {
					mo += 1;
					jQuery("select[name=month]", datepicker).get(0).selectedIndex = mo;
				}
			}

			// maybe hide buttons
			if (0 == mo && !yr) jQuery("span.prevMonth", datepicker).hide();
			else jQuery("span.prevMonth", datepicker).show();
			if (yr + 1 == yrs && mo >= 12 - opts.count_cals) jQuery("span.nextMonth", datepicker).hide();
			else jQuery("span.nextMonth", datepicker).show();

			// clear the old cells
			var cells = jQuery("tbody td", datepicker).unbind().empty().removeClass('date').removeClass('date_no_click').text(' ');  /* text(' ') - чтобы ячейки в ИЕ6 были непустые */

			// figure out what month and year to load
			var m = jQuery("select[name=month]", datepicker).val();
			var y = jQuery("select[name=year]", datepicker).val();
			var d = new Date(y, m, 0);  /* третьим параметром была 1 */
			var startindex = d.getDay();
			var numdays = monthlengths[m];

			// http://en.wikipedia.org/wiki/Leap_year
			if (1 == m && ((y%4 == 0 && y%100 != 0) || y%400 == 0)) numdays = 29;

			// test for end dates (instead of just a year range)
			if (opts.startdate.constructor == Date) {
				var startMonth = opts.startdate.getMonth();
				var startDate = opts.startdate.getDate();
			}
			if (opts.enddate.constructor == Date) {
				var endMonth = opts.enddate.getMonth();
				var endDate = opts.enddate.getDate();
			}
			if (mo < 0 || mo > 11 || !y || yr == -1) {
				jQuery(".title_month",datepicker).html(''); 
				jQuery("select[name=year]", datepicker).get(0).selectedIndex = -1;
				return;
			}

			jQuery(".title_month",datepicker).html(months[mo] + ' ' + y)

			// walk through the index and populate each cell, binding events too
			for (var i = 0; i < numdays; i++) {

				var cell = jQuery(cells.get(i+startindex)).removeClass('chosen');

				// test that the date falls within a range, if we have a range
				if (
					(yr || ((!startDate && !startMonth) || ((i+1 >= startDate && mo == startMonth) || mo > startMonth))) &&
					(yr + 1 < yrs || ((!endDate && !endMonth) || ((i+1 <= endDate && mo == endMonth) || mo < endMonth)))) {


					cell
						.text(i+1)
						.addClass('date')
						.hover(
							function () { jQuery(this).addClass('over'); },
							function () { jQuery(this).removeClass('over'); })
						.click(function () {
							var chosenDateObj = new Date(jQuery("select[name=year]", datepicker).val(), jQuery("select[name=month]", datepicker).val(), jQuery(this).text());
							closeIt(datepickers, el, datepicker, chosenDateObj);
						});

					if ((startindex + i) % 7 == 5 || (startindex + i) % 7 == 6) {cell.addClass('w');} /* раскраска выходных */

					// highlight the previous chosen date
					if (i+1 == chosendate.getDate() && m == chosendate.getMonth() && y == chosendate.getFullYear()) cell.addClass('chosen');

				}
			}
			FiltrMonth (el,startindex,cells,y,m,numdays);
		}

		function FiltrMonth (el,startindex,cells,y,m,numdays) {
			// если есть, то позволять выбирать только те даты, что указаны hidden-поле: имя текущего input-a + _hidden
			var el_hidden = $('[name=' + el.attr('name') + '_hidden]').val();
		  if (!el_hidden) {return;}
		  m++;
		  if (m < 10) {m = '0' + m;}
		  var str0 = y + '-' + m + '-';

		  for (var i = 0; i < numdays; i++) {
		    var cell = jQuery(cells.get(i+startindex));
		    if (!cell.text()) {continue;}
		    var j = (i < 9) ? '0' + cell.text() : cell.text();
       	if (el_hidden.indexOf(str0 + j) != -1) {continue;}
		    cell.removeClass('date').addClass('date_no_click').unbind('click');
		  }

		}

		function closeIt (datepickers, el, datepicker, dateObj) {
			/** closes the datepicker **/
			// sets the currently matched input element's value to the date, if one is available
			// remove the table element from the DOM
			// indicate that there is no datepicker for the currently matched input element
			if (dateObj && dateObj.constructor == Date) {
				el.val(jQuery.fn.simpleDatepicker.formatOutput(dateObj));
        el.trigger('keyup');              // передача управления: вызываем обработчик события keyup
			} else if (dateObj == '0000') {     // reset
			  el.val('');
        el.trigger('keyup');
			}
			for (var i = 0; i < opts.count_cals; i ++) {
				datepickers[i].remove();
				datepickers[i] = null;
			}
			jQuery.data(el.get(0), "simpleDatepicker", { hasDatepicker : false });
			if (ie6) {$('SELECT').css('visibility','visible');}   // возвращаем селекторы
		}

    // iterate the matched nodeset
    return this.each(function() {
      // functions and vars declared here are created for each matched element. so if
      // your functions need to manage or access per-node state you can defined them
      // here and use $this to get at the DOM element

			if ( jQuery(this).is('input') && 'text' == jQuery(this).attr('type')) {

				var datepickers = new Array();
				
				jQuery.data(jQuery(this).get(0), "simpleDatepicker", { hasDatepicker : false });

				// open a datepicker on the click event
				jQuery(this).click(function (ev) {

					if (ie6) {$('SELECT').css('visibility','hidden');}    // в ИЕ6 селекторы перекрывают календарь; на время работы с ним все селекторы делаем неведимыми
					var $this = jQuery(ev.target);

					if (false == jQuery.data($this.get(0), "simpleDatepicker").hasDatepicker) {

						// store data telling us there is already a datepicker
						jQuery.data($this.get(0), "simpleDatepicker", { hasDatepicker : true });

						// validate the form's initial content for a date
						var initialDate = $this.val();

						if (initialDate && dateRegEx.test(initialDate)) {
							var chosendate = new Date(DateReplace4JQ(initialDate));
						} else if (opts.chosendate.constructor == Date) {
							var chosendate = opts.chosendate;
						} else if (opts.chosendate) {
							var chosendate = new Date(opts.chosendate);
						} else {
							var chosendate = today;
						}

						// position the datepicker
						var elPos = findPosition($this.get(0));
						var x = (parseInt(opts.x) ? parseInt(opts.x) : 0) + elPos[0];
						var y = (parseInt(opts.y) ? parseInt(opts.y) : 0) + elPos[1];

						// Вставка в DOM, позиционирование и возня со стилями
						for (var i = 0; i < opts.count_cals; i ++) {
							datepickers[i] = newDatepickerHTML();
							jQuery("body").prepend(datepickers[i]);
							jQuery(datepickers[i]).css({ position: 'absolute', left: x + i*(jQuery(datepickers[0]).width() - 1), top: y });
							
							if (i == 0){
								jQuery(".title_month, .close",datepickers[i]).css('display','none')
								jQuery(datepickers[i]).css('border-right','0').find('TBODY TR').find('TD:last').css('border-right','1px solid #999999');
								
							} else if (i == opts.count_cals - 1) {
								jQuery("SELECT, .prevMonth, .nextMonth, .today, .reset",datepickers[i])
											.css('display','none')
											.css('visibility','hidden')
							} else {
								jQuery("SELECT, .prevMonth, .nextMonth, .today, .reset, .close",datepickers[i])
											.css('display','none')
											.css('visibility','hidden')
								jQuery(datepickers[i])
											.css('border-right','0').find('TBODY TR').find('TD:last').css('border-right','1px solid #999999');
							}
							if (opts.count_cals == 1){
								jQuery(".close",datepickers[i]).css('display','inline')
								jQuery(datepickers[i]).css('border-right','2px solid #999').find('TBODY TR').find('TD:last').css('border-right','0');
							}
							
						}
						

						// bind events to the table controls
						jQuery("select", datepickers[0]).bind('change', function () {
							loadMonth (datepickers, null, $this, datepickers[0], chosendate); 
							var mo = jQuery("select[name=month]", datepickers[0]).get(0).selectedIndex;
							var yr = jQuery("select[name=year]", datepickers[0]).get(0).selectedIndex;
							var yrs = jQuery("select[name=year] option", datepickers[0]).get().length;
							for (var i = 1; i < opts.count_cals; i ++) {
								jQuery("select[name=month]", datepickers[i]).get(0).selectedIndex = (mo + i)%12;
								var y = (mo + i > 11) ? yr + 1 : yr;
								if (yr + 1 == yrs && mo + i > 11){y = -1}
								jQuery("select[name=year]", datepickers[i]).get(0).selectedIndex = y;
								loadMonth (datepickers, null, $this, datepickers[i], chosendate); 
							}
						});
						jQuery("span.prevMonth", datepickers[0]).click(function (e) {for (var i = 0; i < opts.count_cals; i ++) {loadMonth (datepickers, e, $this, datepickers[i], chosendate);} });
						jQuery("span.nextMonth", datepickers[0]).click(function (e) {for (var i = 0; i < opts.count_cals; i ++) {loadMonth (datepickers, e, $this, datepickers[i], chosendate);} });
						jQuery("span.today", datepickers[0]).click(function () { closeIt(datepickers, $this, datepickers[0], new Date()); });
						jQuery("span.close", datepickers[opts.count_cals-1]).click(function () { closeIt(datepickers, $this, datepickers[opts.count_cals-1]); });
						jQuery("span.reset", datepickers[0]).click(function () { closeIt(datepickers, $this, datepickers[0],'0000'); });

						// set the initial values for the month and year select fields
						// and load the first month
						jQuery("select[name=month]", datepickers[0]).get(0).selectedIndex = chosendate.getMonth();
						jQuery("select[name=year]", datepickers[0]).get(0).selectedIndex = Math.max(0, chosendate.getFullYear() - opts.startyear);
						loadMonth(datepickers, null, $this, datepickers[0], chosendate);
						
						var chosen_mo = jQuery("select[name=month]", datepickers[0]).get(0).selectedIndex;
						var chosen_yr = jQuery("select[name=year]", datepickers[0]).get(0).selectedIndex;
						var chosen_yrss = jQuery("select[name=year] option", datepickers[0]).get().length;
						
						for (var i = 1; i < opts.count_cals; i ++) {
							jQuery("select[name=month]", datepickers[i]).get(0).selectedIndex = (chosen_mo + i)%12;
							var yy = (chosen_mo + i > 11) ? chosen_yr + 1 : chosen_yr;
							if (chosen_yr + 1 == chosen_yrss && chosen_mo + i > 11){yy = -1}
							jQuery("select[name=year]", datepickers[i]).get(0).selectedIndex = yy;
//							alert(chosendate.getFullYear() + ' ' + opts.startyear);
							loadMonth(datepickers, null, $this, datepickers[i], chosendate);
						}	
					}
				});
			}
    });
  };

    // finally, I like to expose default plugin options as public so they can be manipulated.  one
    // way to do this is to add a property to the already-public plugin fn

	jQuery.fn.simpleDatepicker.formatOutput = function (dateObj) {
	  var mo = (dateObj.getMonth() + 1) + '';
	  if (mo.length == 1) {mo = '0' + mo;}
	  var d = dateObj.getDate() + '';
	  if (d.length == 1) {d = '0' + d;}
		return d  + "." + mo + "." + dateObj.getFullYear();
	};

	jQuery.fn.simpleDatepicker.defaults = {
		// date string matching /^\d{1,2}\/\d{1,2}\/\d{2}|\d{4}$/
		chosendate : today,

		// date string matching /^\d{1,2}\/\d{1,2}\/\d{2}|\d{4}$/
		// or four digit year
		startdate : today.getFullYear(),
		enddate : today.getFullYear() + 1,

		// offset from the top left corner of the input element
		x : 18, // must be in px
		y : 18, // must be in px
		count_cals: 1
	};

})(jQuery);

