/**
 * Counter widget
 * 
 * @author slava
 * 
 * Depends:
 *   ui.core.js
 */
(function($){
	$.widget("ui.daysCount", {
		_init: function() {
			var o = this.options;
			var el = this.element;
			var self = this;
			
			this.type = o.type;
			
			var content = $('#content');
			var IE6 = $.browser.msie && $.browser.versionX == 6;
			var IE8 = $.browser.msie && $.browser.versionX == 8;
			
			this.prep = el.find(o.prep);
			this.verb = el.find(o.verb);
			this.counter = el.find(o.counter);
			
			this.date = el.find(o.date);
			this.day = el.find(o.day);
			this.month = el.find(o.month);
			this.year = el.find(o.year);
			
			
			var uri = window.location.pathname
			                         .replace(/\/time\/(days-count|counter|estimate|delta)\/?/, '')
			                         .split('/');
			if (uri[uri.length - 1] == '') uri.pop();
			
			if (this.type == 'counter') {
								
				this.days = el.find(o.days);			
				
				if (uri.length === 1 && uri[0]) {
					var uriDate = uri[0].split('.')
					
					this.day.val(uriDate[0]);
					this.month.val(uriDate[1]);
					this.year.val(uriDate[2]);
				}
				
			} else if (this.type == 'estimate') {
				
				this.estimatedDate = el.find(o.estimatedDate);				
				
				if (uri.length > 1 && uri[0]) {
					var uriDate = uri[0].split('.')
					
					this.day.val(uriDate[0]);
					this.month.val(uriDate[1]);
					this.year.val(uriDate[2]);
					
					if (!isNaN(uri[1])) {
						this.counter.val(uri[1]);
					}
				} else {
					var date = new Date(this.year.val(), this.month.val() - 1, this.day.val());
					var newYear = new Date(parseInt(this.year.val()) + 1, 1 - 1, 1);
					var count = Math.round((newYear - date) / o.oneDay);
					this.counter.val(count);
				}
				
			} else if (this.type == 'delta') {
			    
			    this.from = {
			        day  : el.find('.from .day'),
			        month: el.find('.from .month'),
			        year : el.find('.from .year')
			    }
			    this.to = {
			        day  : el.find('.to .day'),
			        month: el.find('.to .month'),
			        year : el.find('.to .year')
			    }
			    this.unit = el.find('.days');
			    
			    if (uri.length > 1 && uri[0] && uri[1]) {
					var uriDateFrom = uri[0].split('.'),
					    uriDateTo = uri[1].split('.');
				
				    this.from.day.val(uriDateFrom[0]);
    				this.from.month.val(uriDateFrom[1]);
    				this.from.year.val(uriDateFrom[2]);
					
					this.to.day.val(uriDateTo[0]);
					this.to.month.val(uriDateTo[1]);
					this.to.year.val(uriDateTo[2]);
				} else {
					var date = new Date(this.year.val(), this.month.val() - 1, this.day.val());
					var newYear = new Date(parseInt(this.year.val()) + 1, 1 - 1, 1);
					var count = Math.round((newYear - date) / o.oneDay);
					this.counter.val(count);
				}
			}
			
            var month = this.month;
			month.selectmenu({
				close: function(event, selectmenu){
					var list = selectmenu.list;
					$(document).trigger('hideCluetip');
					content.height('');
					list.shadow('hide');
				},
				open: function(event, selectmenu){
					var list = selectmenu.list;
					list.css('top', list.position().top - selectmenu.newelement.height() + (IE8 ? 0 : -2));
					if (!IE6) {
						list.width('auto');
					}
					if (list.height() + list.offset().top > content.height() + content.offset().top) {
						content.height(list.height() + list.offset().top - content.offset().top);
					}
					list.shadow();
					list.shadow('show');
				},
				style: 'dropdown',
				transferClasses: true
			});
			
			el.find(o.day + ', ' + o.month + ', ' + o.year + (this.type == 'counter' ? '' : ', ' + o.counter)).bind('keyup input change blur', function(){
				self._count();
			});
			
			this._count(true);
		},
		
		_count: function(leaveHash) {
			var o = this.options;
			var el = this.element;
			
			this.date.removeClass('red-h36');
			
			if (this.type == 'counter') {
				
				var day = this.day.val();
				var year = this.year.val();
				
				if (day && year) {
					if (this._checkDate()) {
						var month = parseInt(this.month.val());
						
						var tmpDate = new Date();
						var today = new Date(tmpDate.getFullYear(), tmpDate.getMonth(), tmpDate.getDate());
						
						var date = new Date(0, month - 1, day);
						date.setFullYear(year);
						
						var count = Math.round((today - date) / o.oneDay);
						var countAbs = Math.abs(count);
						
						var counter = el.find(o.counter);
						var countStr = countAbs.toString();
						counter.text(countStr.length > 4 ? countStr.replace(/(\d{1,3}(?=(\d{3})+$))/g, '\$1 ') : countStr);
						
						if (count > 0) {
							if (day == 2) {
								el.find(o.prep).text(s('from-o'));
							} else {
								el.find(o.prep).text(s('from'));
							}
							
							if (countAbs % 10 == 1 && countAbs % 100 != 11) {
								el.find(o.verb).text(s('passed'));
								el.find(o.days).text(s('day'));
							} else {
								el.find(o.verb).text(s('passed-mult'));
								if (countAbs % 10 >= 2 && countAbs % 10 <= 4 && (countAbs % 100 < 10 || countAbs % 100 >= 20)) {
									el.find(o.days).text(s('days-gen'));
								} else {
									el.find(o.days).text(s('days'));
								}
							}
						} else {
							el.find(o.prep).text(s('before'));
							
							if (countAbs % 10 == 1 && countAbs % 100 != 11) {
								el.find(o.verb).text(s('remeain'));
								el.find(o.days).text(s('day'));
							} else {
								el.find(o.verb).text(s('remain-mult'));
								if (countAbs % 10 >= 2 && countAbs % 10 <= 4 && (countAbs % 100 < 10 || countAbs % 100 >= 20)) {
									el.find(o.days).text(s('days-gen'));
								} else {
									el.find(o.days).text(s('days'));
								}
							}
						}
						
						this._setResultLinks();
						if (!leaveHash) {
							this._setHash();
						}
					} else {
						this.date.addClass('red-h36');
					}
				}
				
			} else if (this.type == 'estimate') {
			
				this.counter.removeClass('counter-error');
				
				var day = this.day.val();
				var year = this.year.val();
				var counter = this.counter.val();
				
				if (day && year && counter) {
					if (this._checkDate() && this._checkCounter()) {
						var month = this.month.val();
						var date = new Date(0, month - 1, day);
						date.setFullYear(year);
						date.setDate(date.getDate() + parseInt(counter));
						
						if (!isNaN(date)) {
							el.find(o.estimatedDate).text(date.getDate() + ' ' + this.month.find('option').eq(date.getMonth()).text() + ' ' + date.getFullYear() + s('year'));
							
							var tmpDate = new Date();
							var now = new Date(tmpDate.getFullYear(), tmpDate.getMonth(), tmpDate.getDate());
							
							if (date - now > 0) {
								el.find(o.verb).text(s('comes'));
							} else {
								el.find(o.verb).text(s('came'));
							}
							
							this._setResultLinks();
							if (!leaveHash) {
								this._setHash();
							}
						} else {
							this.counter.addClass('counter-error');
						}
					} else {
						if (this._checkCounter()) {
							this.date.addClass('red-h36');
						} else {
							this.counter.addClass('counter-error');
						}
					}
				}
				
			} else if (this.type == 'delta') {
			    this.counter.removeClass('counter-error');
			    
			    var dateFrom = new Date (
			            this.from.year.val(), 
    			        this.from.month.val()-1, 
    			        this.from.day.val()
    			    ),
    			    dateTo = new Date (
			            this.to.year.val(), 
    			        this.to.month.val()-1, 
    			        this.to.day.val()
    			    );
    			
    			var fromTime = dateFrom.getTime(),
    			    toTime = dateTo.getTime();
    			
    			if (fromTime <= toTime)
    			{    			
    			    var days = Math.round((toTime - fromTime) / this.options.oneDay);    			    
    			    this.counter.text(days);
    			    this.unit.text(
    			        UnitCase('day', days)
    			    );
    			    this._setResultLinks();
    			} 
    			else
    			{
    			    if (this._checkCounter())
						this.date.addClass('red-h36');
					else
						this.counter.addClass('counter-error');
    			}
			}
		},
		
		_checkDate: function() {
			var flag = false;
			var day = this.day.val();
			var month = parseInt(this.month.val());
			var year = this.year.val();
			
			var pattern = /^\d+$/;
			if (day.search(pattern) != -1 && year.search(pattern) != -1) {
				var date = new Date(0, month - 1, day);
				date.setFullYear(year);
				
				if(day == date.getDate() && month - 1 == date.getMonth() && year == date.getFullYear()) {
					flag = true;
				}
			}
			
			return flag;
		},
		
		_checkCounter: function() {
			var counter = this.counter.val();
			
			var pattern = /^\d+$/;
			if (counter.search(pattern) == -1) {
				return false;
			} else {
				return true;
			}
		},
		
		update: function(leaveHash) {
			this._count(leaveHash);
		},
		
		_setResultLinks: function() {
			var resultLinks = $(this.options.resultLinks);
            var year = this.year.val();
            var month = this.month.val();
            var day = this.day.val();
            var url, codeText;

            if (this.type == 'counter') {
                url = 'http://' + window.BaseServer + '/time/counter/' + day + '.' + month + '.' + year;
                codeText = this.prep.text() + ' ' + day + ' ' + this.month.find('option').eq(parseInt(month) - 1).text() + ' ' + year + ' ' + this.verb.text() + ' ' + this.counter.text() + ' ' + this.days.text();
            } else if (this.type == 'estimate') {
                url = 'http://' + window.BaseServer + '/time/estimate/' + day + '.' + month + '.' + year + '/' + this.counter.val();
                codeText = ordinal_number(this.counter.val()) + s('day after') + day + ' ' + this.month.find('option').eq(parseInt(month) - 1).text() + ' ' + year + ' ' + this.verb.text() + ' ' + this.estimatedDate.text();
            } else if (this.type == 'delta') {                
                var dateFrom = this.from.day.val() + '.' + this.from.month.val() + '.' + this.from.year.val(),
                    dateTo = this.to.day.val() + '.' + this.to.month.val() + '.' + this.to.year.val();
                
                url = 'http://' + window.BaseServer + '/time/delta/' + dateFrom + '/' + dateTo + '/';
                codeText = s('between') + ' ' + dateFrom + ' ' + s('and') + ' ' + dateTo + ' ' + this.counter.text() + ' ' + this.unit.text();
            }
			
            resultLinks.find('#result-link-url').val(url);
            resultLinks.find('#result-link-code').val('<a href="' + url + '">' + codeText + '</a>');
		},
		
		_setHash: function() {/*empty*/}
	});
	
	$.extend($.ui.daysCount, {
		defaults: {
			estimatedDate: '.estimated-date',
			counter: '.counter',
			date: '.date',
			day: '.day',
			days: '.days',
			month: '.month',
			oneDay: 1000 * 60 * 60 * 24,
			prep: '.prep',
			resultLinks: '#result-links',
			type: 'counter',
			verb: '.verb',
			year: '.year'
		}
	});
})(jQuery);
