/**
 * @author 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) {
	this.generateHTML(this.input);
	for(i=1;i<months;i++) {
		this.next();
		this.generateHTML(this.input);
	}
}
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){
	// 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 colspan="7">'+monthName + "&nbsp;" + this.year+'</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 += (calDay.toDateString()==today.toDateString()) ? ' is-today' : '';
			css += (j>4) ? ' is-weekend' : '';
			css += (calDay<=this.fromToday(1)) ? ' 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 url = $this.attr('href');
		var title = $this.attr('title');
		var scrolling = ($.browser.msie) ? 'yes' : 'auto';
		$this.click(function(){
			esky_cities_remove();
			var c = $(this).prev().offset();
			$('body')
			.append(
				$('<div></div>')
					.attr('id','esky_cities')
					.css({
						'position':'absolute',
						'top':c.top,
						'left':c.left
					})//css
					.append(
						$('<h3></h3>')
							.text(title)
							.append($('<a></a>')
								.attr('href','javascript:void(0);')
								.text(txt_close)
								.click(esky_cities_remove)
							)
					)
					.append(
						$('<iframe>')
							.attr('src',url)
							.attr('width',300)
							.attr('height',330)
							.attr('frameborder',0)
							.attr('scrolling',scrolling)
							.attr('marginwidth',0)
							.attr('marginheight',0)
							.attr('allowTransparency','true')
							.css({
								'border':'none',
								'background':'transparent'
							})
					)
					.bgIframe()
			);//append
			return false;
		}); //onclick
	}); //each
	},
	esky_calendar_render: function(parameters) {
	$this = $(this);
	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);
	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 };

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

		$('a.month-day').not('.is-disabled,.is-blocked')
		.click(function(){
			$('#'+p.field).val( $(this).attr('rel') );
			$this.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;
	},
	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;
	}
});
