/**
 * @author Krzysztof Winiarski . eSKY Sp. z o.o. www.esky.pl
 * File contains:
 *
 * eskyCalendar
 * Depends on jQuery and its plugins: dimensions, bgiframe
 * Displays calendar which is fully styled with CSS.
 *
 * eskyCities
 * Depends on jQuery and its plugins: dimensions, bgiframe
 * Displays dynamic box with iframe containing list of cities
 */
//ESKY CALENDAR
cal_days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
cal_current_date = new Date();

function Calendar(input) {
	this.date = new Date();
	this.html = '';
	this.input = input;
}
Calendar.prototype.setDate = function(month, year) {
	this.month = (isNaN(month) || month == null) ? this.date.getMonth() : month;
	this.year  = (isNaN(year) || year == null) ? this.date.getFullYear() : year;
	return new Array(this.month,this.year);
}
Calendar.prototype.readDate = function(field) {
	return document.getElementById(this.input).value;
}
Calendar.prototype.arrayDate = function(string) {
	var re = new RegExp("^[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}$","i");
	if(re.test(string)==false||string=='') return false;

	var s = string.split('-');
	return new Array(parseInt(s[0],10),(parseInt(s[1],10)-1),parseInt(s[2]));
}
Calendar.prototype.leadZero = function(n) {
	return (parseInt(n,10)<10) ? "0"+n : n;
}
Calendar.prototype.stringDate = function(d,m,y) {
	return this.leadZero(d)+'-'+this.leadZero(m+1)+'-'+y;
}
Calendar.prototype.makeDate = function(d,m,y,zero){
	o = new Date(y,m,d);
	if(zero){this.zeroTime(o);}
	return o;
}
Calendar.prototype.zeroTime = function(o) {
	o.setHours(0); o.setMinutes(0); o.setSeconds(0); o.setMilliseconds(0); return o;
}
Calendar.prototype.getHTML = function() {
	return this.html;
}
Calendar.prototype.next = function() {
	var nx = new Array(this.month,this.year);
	if(nx[0]++>=11){
		nx[0]=0;nx[1]++;
	}
	return this.setDate(nx[0],nx[1]);
}
Calendar.prototype.prev = function() {
	var nx = new Array(this.month,this.year);
	if(nx[0]--<=0){
		nx[0]=11;nx[1]--;
	}
	return this.setDate(nx[0],nx[1]);
}
Calendar.prototype.buildHTML = function(months,n2) {
	//alert(n2);
	this.generateHTML(this.input,n2);
	for(i=1;i<months;i++) {
		this.next();
		this.generateHTML(this.input,n2);
	}
}
Calendar.prototype.fromToday = function(value) {
	var d = new Date();
	d.setMilliseconds(d.getMilliseconds() + parseInt(value*86400000));
	return this.zeroTime(d);
}
Calendar.prototype.generateHTML = function(input,n2){
	//alert (n2);
	// get first day of month
	var firstDay = new Date(this.year, this.month, 0);
	var startingDay = firstDay.getDay();

	// find number of days in month
	var monthLength = cal_days_in_month[this.month];

	// compensate for leap year
	if (this.month == 1) { // February only!
	if((this.year % 4 == 0 && this.year % 100 != 0) || this.year % 400 == 0){
		monthLength = 29;
	}
	}
	var monthName = cal_months_labels[this.month]
	// do the header

	var html = '<table class="calendar-table" cellpadding="0" cellspacing="0">';
	html += '<tr><th class="calendar-previous'+n2+'"><a href="javascript:" class="calendar-previous'+n2+'">&laquo;</a></th><th colspan="5" class="month-name">&nbsp;&nbsp;'+monthName + "&nbsp;" + this.year+'&nbsp;&nbsp;</th><th><a href="javascript:" class="calendar-next'+n2+'">&raquo;</a></th></tr>';
	html += '<tr class="calendar-header">';
	for(var i = 0; i <= 6; i++ ){
		html += '<td class="calendar-header-day">'+cal_days_labels[i]+'</td>';
	}
	html += '</tr><tr>';

	var sd = this.arrayDate(this.readDate());
	var selected = this.makeDate(sd[0],sd[1],sd[2],true);
	var today = this.zeroTime(this.date);
	var day = 1;
	for (var i = 0; i < 9; i++) {
	for (var j = 0; j <= 6; j++) {
		html += '<td class="calendar-day">';
		if (day <= monthLength && (i > 0 || j >= startingDay)) {
			var calDay = new Date(this.year,this.month,day);
			
			css = 'month-day';
			css += n2;
			css += (calDay.toDateString()==today.toDateString()) ? ' is-today' : '';
			css += (j>4) ? ' is-weekend' : '';
			css += (calDay<=this.fromToday(2)) ? ' is-blocked' : ''; 
			css += (calDay<today) ? ' is-disabled' : '';
			css += (calDay.toDateString()==selected.toDateString()) ? ' is-selected' : '';
			
			html += '<a  class="'+css+'" rel="'+this.stringDate(day,this.month,this.year)+'">'+day+'</a>';
			day++;
		} else {
			html += '&nbsp;';
		}
		html += '</td>';
	}
	if (day > monthLength) { break; } else { html += '</tr><tr>'; }
	}
	html += '</tr></table>';
	this.html += html;
}
function esky_cities_remove() {
	$('#esky_cities').empty().remove();
	$(document).blur();
}
jQuery.fn.extend({
	esky_cities: function() {
	$(this).each(function(){
		$this = $(this);
		var c1 = $this.prev().offset();
		var url = $this.attr('href');		
		var title = $this.attr('title');
		var scrolling = ($.browser.msie) ? 'yes' : 'auto';
		var scrolling = 'auto';
		$this.click(function(){
			esky_cities_remove();
			var c2 = $this.prev().offset();
			
			$('body')
			.append(
				$('<div></div>')
					.attr('id','esky_cities')
					.css({
						'position':'absolute',
						'top':(c1.top>0)?c1.top:c2.top,
						'left':(c1.left>0)?c1.left-0:c2.left-50
						
						
					})//css
					.append(
						$('<h3></h3>')
							.text(title)
							.append($('<a></a>')
								.attr('href','javascript:void(0);')								
								.text(txt_close)
								.click(esky_cities_remove)
							)
					)
					.append(
						$('<iframe >')
							
							.attr('id','esky_cities_frame')
							.attr('src',url)
							.attr('width',220)
							.attr('height',200)
							.attr('frameborder',0)
							.attr('scrolling',scrolling)
							.attr('marginwidth',0)
							.attr('marginheight',0)
							.attr('allowTransparency','true')
							.css({
								'border':'none',
								'background':'transparent',
								'font-weight':'bold'
								
							})
					)
					.bgIframe()
			);//append
			return false;
		}); //onclick
	}); //each
	},

	//====================================== 1 ========================================
	esky_calendar_render: function(parameters, th2, th2_1) {
	//$this = $(this);
	//$this = $('#esky_calendar');
	
	$this=th2;

	
	
	var defaults = { field: false, month: null, year: null, loop: 1, next: false, prev: false, fade: false };
	var p = $.extend(defaults, parameters);


	var c = new Calendar(p.field);
	
	//alert (p.field);
	//if (p.field=='outdate') $this = $('#esky_calendar');
	//if (p.field=='retdate') $this = $('#esky_calendar2');

	if(!p.month&&!p.year){
	var a = c.arrayDate(c.readDate());
	var d = c.setDate(a[1],a[2]);
	}
	else{
		var d = c.setDate(p.month,p.year);
	}
	
	
	

	if(p.next===true) var d = c.next();
	var px = { field: p.field, month: d[0], year: d[1], loop: p.loop, next: true, prev: false, fade: false };

	if(p.prev===true) var d = c.prev();
	var pv = { field: p.field, month: d[0], year: d[1], loop: p.loop, next: false, prev: true, fade: false };

	var pc = { field: p.field, month: c.date.getMonth(), year: c.date.getFullYear(), loop: p.loop, next: false, prev: false, fade: false };

	var pa = { field:  p.field, month: d[0], year: d[1], loop: p.loop, next: false, prev: false, fade: false };
	

	c.buildHTML(p.loop,p.field);
	

	$this
		.html(c.getHTML())				
		.prepend(
			$('<div></div>')
			.attr('id','calendar-top'+'-'+p.field)
			.css({'position':'absolute'}) //--------- TU BLAD
			//--.prepend($('<a href="javascript:" class="calendar-next" title="'+cal_text.NEXT+'">&raquo;</a>').click(function(){$this.esky_calendar_render(px, th2)}))
			//.prepend($('<a href="javascript:" class="calendar-button calendar-current">'+cal_text.THISMONTH+'</a>').click(function(){$this.esky_calendar_render(pc, th2)}))
			//--.prepend($('<a href="javascript:" class="calendar-previous" title="'+cal_text.PREV+'">&laquo;</a>').click(function(){$this.esky_calendar_render(pv, th2)}))
		)
		//.append($('<a href="javascript:" class="calendar-button calendar-close">'+cal_text.CLOSE+'</a>').click(function(){$this.remove()}));
		
		$('a.calendar-next'+p.field)
		.click(function(){
			$this.esky_calendar_render(px, th2)
			//if(th2_1!=null) $this.esky_calendar_render(px, th2_1)
		})
		$('a.calendar-previous'+p.field)
		.click(function(){
			$this.esky_calendar_render(pv, th2)
		})

		$('a.month-day'+p.field).not('.is-disabled,.is-blocked')
		.click(function(){
			$('#'+p.field).val( $(this).attr('rel') );
			
			//c.buildHTML(p.loop);
			//$(this).addClass('month-day is-selected');
			//$this.remove();
			//alert ( p.field);
			th2.esky_calendar_render(pa, th2);
			//
			//th2.remove();
		})

		.mouseover(function(){
			$(this).addClass('is-hover');
		})
		.mouseout(function(){
			$(this).removeClass('is-hover');
		})
			
		$('a.is-blocked').not('.is-disabled').click(function(){
			alert(cal_info);
		})

		$this.bgIframe();
		return $this;
	},
	//===================================== 2 ========================================
	/*
	esky_calendar_render2: function(parameters, th2) {
	//$this = $(this);
	//$this = $('#esky_calendar');
	$this2=th2;
	
	var defaults = { field: false, month: null, year: null, loop: 1, next: false, prev: false, fade: false };
	var p2 = $.extend(defaults, parameters);

alert ('2 - '+ p2.field);
	var c2 = new Calendar(p2.field);
	
	if(!p2.month&&!p2.year){
	var a = c2.arrayDate(c2.readDate());
	var d = c2.setDate(a[1],a[2]);
	}
	else{
		var d = c2.setDate(p2.month,p2.year);
	}
	

	if(p2.next===true) var d = c2.next();
	var px = { field: p2.field, month: d[0], year: d[1], loop: p2.loop, next: true, prev: false, fade: false };

	if(p2.prev===true) var d = c2.prev();
	var pv = { field: p2.field, month: d[0], year: d[1], loop: p2.loop, next: false, prev: true, fade: false };

	var pc = { field: p2.field, month: c2.date.getMonth(), year: c2.date.getFullYear(), loop: p2.loop, next: false, prev: false, fade: false };

	var pa = { field:  p2.field, month: d[0], year: d[1], loop: p2.loop, next: false, prev: false, fade: false };
	

	c2.buildHTML(p2.loop,p2.field);
	

	$this2
		.html(c2.getHTML())		
		.prepend(
			$('<div></div>')
			.attr('id','calendar-top'+'-'+p2.field)
			.prepend($('<a href="javascript:" class="calendar-button calendar-next" title="'+cal_text.NEXT+'">&raquo;</a>').click(function(){$this2.esky_calendar_render(px, th2)}))
			.prepend($('<a href="javascript:" class="calendar-button calendar-current">'+cal_text.THISMONTH+'</a>').click(function(){$this2.esky_calendar_render(pc, th2)}))
			.prepend($('<a href="javascript:" class="calendar-button calendar-previous" title="'+cal_text.PREV+'">&laquo;</a>').click(function(){$this2.esky_calendar_render(pv, th2)}))
		)
		.append($('<a href="javascript:" class="calendar-button calendar-close">'+cal_text.CLOSE+'</a>').click(function(){$this2.remove()}));

		$('a.month-day'+p2.field).not('.is-disabled,.is-blocked')
		.click(function(){
			$('#'+p2.field).val( $(this).attr('rel') );
			alert ('2 - '+p2.field);
			//c.buildHTML(p.loop);
			$(this).addClass('month-day is-selected');
			//$this.remove();
			
			//th2.esky_calendar_render(pa, th2);
			//
			//th2.remove();
		})
		.mouseover(function(){
			$(this).addClass('is-hover');
		})
		.mouseout(function(){
			$(this).removeClass('is-hover');
		})

		$('a.is-blocked').not('.is-disabled').click(function(){
			alert(cal_info);
		})

		$this2.bgIframe();
		return $this2;
	},
	/**/
	esky_calendar: function(parameters){

		//$('#esky_calendar').remove();
		var $this = $(this);
		var xy = $this.prev().offset();
		var top = (parameters.top) ? parameters.top : xy.top;
		var left = (parameters.left) ? parameters.left : xy.left;
		$('body').append(
			$('<div></div>')
			.attr('id','esky_calendar')
			.css({position:'absolute',top:top,left:left})
			.hide()
		);
		$('#esky_calendar').esky_calendar_render(parameters).show();
		return $this;
	}
});