var weekdays_long=new Array();
var weekdays_short=new Array();
var months_long=new Array();

weekdays_long['de'] = ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"];
weekdays_long['en'] = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
weekdays_long['ru'] = ["Воскресенье", "Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота"];

weekdays_short['de'] =["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"];
weekdays_short['en'] =["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"];
weekdays_short['ru'] =["Вс", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"];

months_long['de'] = ["Januar", "Februar", "M\u00E4rz", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"];
months_long['en'] = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
months_long['ru'] = ["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"];

/* Calendar actions for FTR project (needs jQuery) */

var calendarAction = {
	
	sessionCounter:0,
	currentDateTimestamp:0,
	todayTimestamp:'',
	currentCellSelector:'',
	isRecurrentOfferRequest:0, /* 0 - false, 1,2... - true */
	recurrentDaysCounterDefaultValue:1,
	recurrentDaysCounterMaxValue:10,
	calendarInstance:'',
	
	init:function() {
		var _this=this;
		this.serverTimeOffset = jQuery('#server_time_offset').attr('value')*3600;
		this.sessionCounter = jQuery('#calendar_dates_stored>div').length;
		jQuery('#calendar_editor_form #save_item').click(function() {
			return _this.storeItem();
		});
		jQuery('#calendar_editor_form #cancel_item').click(function() {
			return _this.cancelItem();
		});
		jQuery('#calendar_editor_form #delete_item').click(function() {
			return _this.deleteItem();
		});
		jQuery('#calendar_editor_message').css('display', 'block');
		this.inited = 1;
		if (jQuery('#cal1Container').length)
			this.initCalendar();
		if (jQuery('#disableCalendar').length&&jQuery('#disableCalendar').attr('value')=='true')
			this.disableCalendar();
		if (jQuery('#setCalendarToDate').length)
			this.setCalendarToDate();
	},
	initCalendar:function() {
		var today = new Date;
		this.todayTimestamp = Math.round(jQuery.datepicker.parseDate('mm dd yy', today.getMonth()+1 +' ' + today.getDate() +' ' + today.getFullYear())/1000);
		this.calendarInstance = new YAHOO.widget.Calendar("cal1", "cal1Container", {
			 start_weekday: 1,
			 mindate:today
		});
		this.calendarInstance.cfg.setProperty("WEEKDAYS_SHORT", weekdays_short[LANG.toLowerCase()]);
		this.calendarInstance.cfg.setProperty("MONTHS_LONG", months_long[LANG.toLowerCase()]);
		this.calendarInstance.render();
	},
	disableCalendar:function() {
		this.calendarInstance.cfg.setProperty("maxdate", '1/1/2011');
		this.calendarInstance.render();
		this.markTodayDate();
		return false;
	},
	enableCalendar:function() {
		this.calendarInstance.cfg.setProperty("maxdate", '');
		this.calendarInstance.render();
		return false;
	},
	setCalendarToDate:function() {
		this.calendarInstance.cfg.setProperty("pagedate", jQuery('#setCalendarToDate').attr('value'));
		this.calendarInstance.render();
		return false;
	},
	renderCalendar:function() {
		this.calendarInstance.render();
		return false;
	},
	clearCurrentSelectedDay:function() {
		return false;
	},
	markTodayDate:function() {
		var today = new Date;
		jQuery(this.getCellSelector(today/1000)).html('<div class="today">'+today.getDate()+'</div>');
		return false;
	},
	getServerTimestamp:function(clientTimestamp) {
		var date = new Date;
		var UTCOffsetInSeconds = -date.getTimezoneOffset()/60*3600;
		var serverTimestamp = clientTimestamp+UTCOffsetInSeconds-this.serverTimeOffset;
		return serverTimestamp;
	},
	getClientTimestamp:function(serverTimestamp) {
		var date = new Date;
		var UTCOffsetInSeconds = -date.getTimezoneOffset()/60*3600;
		var clientTimestamp = serverTimestamp-UTCOffsetInSeconds+this.serverTimeOffset;
		return clientTimestamp;
	},
	getCellSelector:function(unixTimestamp) {
		var date_object = new Date(unixTimestamp*1000);
		return '.y'+date_object.getFullYear()+' .m'+(date_object.getMonth()+1)+' .d'+date_object .getDate();
	},
	setOfferRequestData:function() {
		if(!this.inited) this.init();
		var _this=this;
		/* render preloaded data; each div has class with timestamp of date and data for one cell/date	 */
		jQuery.each(jQuery('#calendar_dates>div'), function() {
			_this.setCellData(jQuery(this));
		});
		/* render added data  */
		jQuery.each(jQuery('#calendar_dates_stored input.offer_request_date_timestamp_stored'), function() {
			var dateTimestamp = _this.getClientTimestamp(jQuery(this).attr('value'));
			if (dateTimestamp >= _this.todayTimestamp) {
				jQuery(_this.getCellSelector(dateTimestamp)).addClass('possible');
			}
		});
	},
	setCellData:function(selectorObject) {
		var _this=this;
		var popupContent = selectorObject.find('.calendar_popup_content').html();
		var cellSelector ='';
			jQuery.each(selectorObject.find('input'), function() {
				var dateTimestamp = _this.getClientTimestamp(jQuery(this).attr('value'));
				if (dateTimestamp >= _this.todayTimestamp || jQuery(this).hasClass('force_show') ) {
					jQuery(_this.getCellSelector(dateTimestamp)).addClass(jQuery(this).attr('class'));
					cellSelector = _this.getCellSelector(dateTimestamp);
				}
			});
		if (cellSelector)
			_this.createOfferRequestPopup(cellSelector, popupContent);
		return false;
	},
	createOfferRequestPopup:function(cellSelector, content) {
		if (content) {
			jQuery(cellSelector).append('<div style="position:relative;"><div class="calendar_offer_request_popup"><div class="arr"></div>'+content+'</div></div>');
			jQuery(cellSelector).find('.calendar_offer_request_popup').css({ 
					'top' : -jQuery(cellSelector).find('.calendar_offer_request_popup').height()-48, 
					'left' : -(jQuery(cellSelector).find('.calendar_offer_request_popup').width())/2 });
		}
		return false;
	},
	showhideOfferRequestEditor:function() {
		jQuery('#calendar_editor_form').toggle();
	},
	showOfferRequestEditor:function() {
		if (!jQuery('#calendar_editor_form').length)
			return false;
		jQuery('#calendar_editor_form').css('display', 'block');
		this.setOfferRequestDefaultData();
	},
	hideOfferRequestEditor:function() {
		jQuery('#calendar_editor_form').css('display', 'none');
	},
	setOfferRequestDefaultData:function() {
		var _this=this;
		var arrDates = this.calendarInstance.getSelectedDates(); /* all selected dates */
		var dateTimestamp = this.getServerTimestamp(this.currentDateTimestamp);
		this.currentCellSelector = '.y'+arrDates[0].getFullYear()+' .m'+(arrDates[0].getMonth()+1)+' .d'+arrDates[0].getDate();
		var date_string = weekdays_long[LANG.toLowerCase()][arrDates[0].getDay()]+', '+arrDates[0].getDate()+'.'+(arrDates[0].getMonth()+1)+'.'+arrDates[0].getFullYear();		
		var time_limitation = '';
		jQuery('#calendar_editor_form #delete_item').css('display', 'none');
		jQuery('#calendar_editor_form #recurrent_date_block').css('display', 'block');
		/* if offer/request for current date is stored */
		if(jQuery("#stored_offer_request_"+dateTimestamp).length) {
			time_limitation = jQuery("#stored_offer_request_"+dateTimestamp).find('.offer_request_time_limitation_stored').attr('value');
			/* show delete link */
			jQuery('#calendar_editor_form #delete_item').css('display', 'block');
			/* hide recurrent block if needed */
			if(jQuery("#stored_offer_request_"+dateTimestamp).find('.offer_request_recurrent_enable_stored').attr('value')>0) {
				jQuery('#calendar_editor_form #recurrent_date_block').css('display', 'none');
			}
		} else {
			if (jQuery(this.currentCellSelector).hasClass('possible')) {
				time_limitation = jQuery('#calendar_dates').find('div.'+dateTimestamp+' input').attr('alt');
				jQuery('#calendar_editor_form #delete_item').css('display', 'block');
				if (jQuery(this.currentCellSelector).hasClass('recurrent')) {
					jQuery('#calendar_editor_form #recurrent_date_block').css('display', 'none');
				}
			}
		}
		jQuery('#calendar_editor_form .date span').html(date_string);
		jQuery('#offer_request_time_limitation').attr('value', time_limitation);
	},
	clearOfferRequestEditorData:function() {
		jQuery("#offer_request_time_limitation").attr('value', "");
		jQuery("#offer_request_recurrent_enable").removeAttr('checked');
		jQuery("#recurrent_days_counter").attr('value', "");
		return false;
	},
	storeItem:function() {
		var dateTimestamp = this.getServerTimestamp(this.currentDateTimestamp);
		this.isRecurrentOfferRequest = 0;
		// if offer/request for current date is stored 
		if(jQuery("#stored_offer_request_"+dateTimestamp).length) {
			if(jQuery('#offer_request_recurrent_enable').attr('checked')) {
				jQuery("#stored_offer_request_"+dateTimestamp).remove();
				this.isRecurrentOfferRequest = this.getRecurrentDaysCount();
				for (var i=0; i<this.getRecurrentDaysCount(); i++ ) {
					this.addCalendarDatesStoredFields(i);
				}
			} else {
				jQuery("#stored_offer_request_"+dateTimestamp).find('.offer_request_time_limitation_stored').attr('value', jQuery("#offer_request_time_limitation").attr('value'));
			}
		} else {
			// creating new fields and store data
			if ( jQuery('#offer_request_recurrent_enable').attr('checked') || jQuery(this.currentCellSelector).hasClass('recurrent') ) {
				this.isRecurrentOfferRequest = this.getRecurrentDaysCount();
				for (var i=0; i<this.getRecurrentDaysCount(); i++ ) {
					this.addCalendarDatesStoredFields(i);
				}
			} else {
				this.addCalendarDatesStoredFields(0);
			}
		}
		jQuery(this.currentCellSelector).removeClass('selected');
		this.clearOfferRequestEditorData();
		this.hideOfferRequestEditor();
		return false;
	},
	addCalendarDatesStoredFields:function(i) {
		var dateTimestamp = this.getServerTimestamp(this.currentDateTimestamp+(86400*7*i));
		var storedItemId = "stored_offer_request_"+(dateTimestamp);
		jQuery('#calendar_dates_stored').append('<div id="'+storedItemId+'"></div>');
		jQuery('#'+storedItemId).append('<input type="hidden" class="offer_request_date_timestamp_stored" name="availability_dates['+this.sessionCounter+']" value="'+(dateTimestamp)+'" />');
		jQuery('#'+storedItemId).append('<input type="hidden" class="offer_request_time_limitation_stored" name="availability_dates_times['+this.sessionCounter+']" value="'+jQuery("#offer_request_time_limitation").attr('value')+'" />');
		jQuery('#'+storedItemId).append('<input type="hidden" class="offer_request_recurrent_enable_stored" name="availability_dates_recurrent['+this.sessionCounter+']" value="'+this.isRecurrentOfferRequest+'" />');
		this.sessionCounter++;
		jQuery(this.getCellSelector(this.getClientTimestamp(dateTimestamp))).addClass('possible');
	},
	getRecurrentDaysCount:function() {
		var recurrent_count = jQuery("#recurrent_days_counter").attr('value');
		if (isNaN(jQuery("#recurrent_days_counter").attr('value')) || jQuery("#recurrent_days_counter").attr('value')<1 || jQuery("#recurrent_days_counter").attr('value') == '')
			recurrent_count = this.recurrentDaysCounterDefaultValue;
		return recurrent_count;
	},
	cancelItem:function() {
		jQuery(this.currentCellSelector).removeClass('selected');
		this.clearOfferRequestEditorData();
		this.hideOfferRequestEditor();
		return false;
	},
	deleteItem:function() {
		var dateTimestamp = this.getServerTimestamp(this.currentDateTimestamp);
		
		/* delete stored date (which eas added during current session ) */
		if(jQuery("#stored_offer_request_"+dateTimestamp).length) {
			jQuery("#stored_offer_request_"+dateTimestamp).remove();
		}
		/* delete stored date */
		if(jQuery("#calendar_dates div."+dateTimestamp+' input.possible[value="'+dateTimestamp+'"]').length) {
			jQuery("#calendar_dates div."+dateTimestamp+' input.possible[value="'+dateTimestamp+'"]').remove()
		}
		jQuery(this.currentCellSelector).removeClass('possible');
		jQuery(this.currentCellSelector).removeClass('selected');
		this.clearOfferRequestEditorData();
		this.hideOfferRequestEditor();
		return false;
	},
	/* only for offer_detail page */
	setSelectedDateToOfferDetail:function() {
		var arrDates = this.calendarInstance.getSelectedDates();
		var dateTimestamp = this.getServerTimestamp(this.currentDateTimestamp);
		var date_string = weekdays_long[LANG.toLowerCase()][arrDates[0].getDay()]+', '+arrDates[0].getDate()+'.'+(arrDates[0].getMonth()+1)+'.'+arrDates[0].getFullYear();		
		var time_limitation = jQuery('#calendar_dates').find('input[value="'+dateTimestamp+'"]').attr('alt');
		if (typeof time_limitation == "undefined")
			time_limitation = '';
		else time_limitation = ' - '+time_limitation;
		jQuery('#detail_view_user_selected_date').html(date_string+time_limitation+'<input name="date" type="hidden" value="'+dateTimestamp+'" />');
		return false;
	}
}
