var TSearch = {
	DirectionsInput: [],
	DatesInput: [],
	PlusMinusInput: [],
	MoreParams: [],
	Calendar: {},
	Options: {}
};

Date.prototype.toNormalDate = function () {
	var m = Number(this.getMonth()) + 1;
	var date = ((String(this.getDate()).length == 1) ? "0" + this.getDate() : this.getDate()) + '.' + ((String(m).length == 1) ? "0" + m : m) + '.' + this.getFullYear()
	return date;	
}

/**
 * Helper
 * сюди всяке сміття
 */
TSearch.Helper = (function (){
	var Keys = {
		TAB: 9,
		ESC: 27,
		ENTER: 13,
		UP: 38,
		RIGHT: 39,
		LEFT: 37,
		DOWN: 40
	}

	var checkEnableDay = function(currentDay, calendarObj){
        return null;
	}
	
	var getPosition = function (el) { 
	    return el.offset();
	}	
	
	var Log = function (msg, title) {
        return;
		if (typeof(console) != 'undefined') {
			if (title) {
				console.log("===" + title + "===");				
			}
			
			if (msg) {
				console.log(msg);
			}
		}
	}
	
	var i18n = {
		ru: {
			days: ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'],
			months: ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 
			         'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'],
      short_months: ['янв', 'февр', 'март', 'апр', 'май', 
			         'июнь', 'июль', 'авг', 'сент', 'окт', 'нояб', 'дек'],
			months_d: ['Января', 'Февраля', 'Марта', 'Апреля', 'Майя', 
			         'Июня', 'Июля', 'Августа', 'Сентября', 'Октября', 'Ноября', 'Декабря'],
            no_results : 'вариантов нет'         
		},
		en: {
			days: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
			months: ['January', 'February', 'Mart', 'April', 'May', 
			         'Juny', 'July', 'August', 'September', 'October', 'November', 'December'],
			months_d: ['January', 'February', 'Mart', 'April', 'May', 
			         'Juny', 'July', 'August', 'September', 'October', 'November', 'December'],
            no_results : 'no results'
		},
		uk: {
			days: ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'],
			months: ['Січень', 'Лютий', 'Березень', 'Квітень', 'Травень', 
			         'Червень', 'Липень', 'Серпень', 'Вересень', 'Жовтень', 'Листопад', 'Грудень'],
			months_d: ['Січень', 'Лютий', 'Березень', 'Квітень', 'Травень', 
			         'Червень', 'Липень', 'Серпень', 'Вересень', 'Жовтень', 'Листопад', 'Грудень'],
            no_results : 'нема вариантів'         
		}
	}

	var Result = {
            //var i18n = Helper.i18n[language];
            
			init: function (input, useCode) {
				this.Helper = TSearch.Helper;
				this.Input  = input;
				this.UseCode = useCode;
				this.Index = 0;
				
				this.InputCode  = $('#' + this.Input.attr('name') + 'Code_input');
				
				if (this.UseCode !== true) {
					this.InputCode.hide();
				}
				
				this.Box    = $('div.SuggestResult');
				this.ResultTable = $('table.SuggestResult');
				this.XY     = this.Helper.getPosition(input);
				
				this.Box.css({
					position: 'absolute',
					left: this.XY.left,
					top: (this.XY.top + this.Input.height() + 11)
				});

				return this;
			},
			
			fillResult: function (result) {
				this.ResultTable.html('');
				var line, self = this;

				for (var i = 0; i < result.length; i += 1) {
					line = $('<tr/>');
					line.data(result[i]);
					
					line.append('<td class="SuggestResult" city="' + result[i].name + '">' + result[i].name + '</td>');
					
					if (this.UseCode !== true) {
						var style = 'style="display:none"';
					}
					
					line.append('<td class="AirpCode" ' + style + '>' + result[i].code + '</td>');
					
					this.ResultTable.append(line);
					if (result.length < 10) {
						$(this.ResultTable).height(25*result.length);
						$(this.ResultTable).css("padding","0");
					} else {
						$(this.ResultTable).height((result.length ? 25 : 250));
						$(this.ResultTable).css("margin-right", 8);
						$(this.ResultTable).css("padding","7px 7px 7px 0");
					}
					
				}
				
				this.ResultTable.find('tr:first').addClass('hover');

				this.ResultTable.find('tr').live('mouseover', function () {
					self.ResultTable.find('tr').removeClass('hover');
					$(this).addClass('hover');
				}).live('click', function () {
					self.selectActiv($(this));
				});				
			
				this.Box.css({
					visibility: 'visible'
				});
				
				this.ResultTable = $('table.SuggestResult');
			},
			
			showEmpty: function () {
				this.ResultTable.html('<tr><td class="NoResults">' + i18n[language]['no_results'] + '</td><tr>');
				this.Box.css({
					visibility: 'visible'
				})
			},
			
			hide: function () {	
				this.ResultTable.html('');
				this.Box.css({
					visibility: 'hidden'
				});
			},
			
			goDown: function () {
				var Activ = this.ResultTable.find('hover'),
					All   = this.ResultTable.find('tr');

					All.removeClass('hover');

				if (All.eq((this.Index + 1))) {
					All.eq((this.Index + 1)).addClass('hover');
					this.Index++;
				} else {
					All.eq(All.length).addClass('hover');
				}
			},
			
			goUp: function () {
				var Activ = this.ResultTable.find('hover'),
					All   = this.ResultTable.find('tr');
	
					All.removeClass('hover');
	
				if (All.eq((this.Index - 1))) {
					All.eq((this.Index - 1)).addClass('hover');
					this.Index--;
				} else {
					All.eq(All.length).addClass('hover');
					this.Index = All.length;
				}
			},
			
			selectActiv: function (self) { 
				var self = self || this.ResultTable.find('.hover');
			
				this.Input.data(self.data());
				
				this.InputCode.val(self.find('.AirpCode').text());

				this.Input.val(self.find('.SuggestResult').text());
				this.hide();

				this.Helper.nextTabIndex(this.Input.attr('tabindex'))
			}
			
		}	
	//генеруємо параметри для пошуку
	var getLoaderParams = function () {
		var Params = {};
		Params["Services"] = [];
		var CookieParams = '';
        
		if (TSearch.DirectionsInput.length > 0) {
			for (var i = 0; i < TSearch.DirectionsInput.length; i++) {
                if(!TSearch.DirectionsInput[i].CodeInput.attr('disabled')){
                	Params[TSearch.DirectionsInput[i].Input.attr('id').replace('_input', '')] = TSearch.DirectionsInput[i].Input.val();
				    Params[TSearch.DirectionsInput[i].CodeInput.attr('id').replace('_input', '')] = TSearch.DirectionsInput[i].CodeInput.val();
                    CookieParams += TSearch.DirectionsInput[i].CodeInput.attr('id') + '=' + TSearch.DirectionsInput[i].CodeInput.val() + ';' + TSearch.DirectionsInput[i].Input.attr('id') + '=' + TSearch.DirectionsInput[i].Input.val() + ';';
                }
                
                if (typeof(TSearch.DirectionsInput[i].Input.data().service != 'undefined') && TSearch.DirectionsInput[i].Input.data()) {
                	var data = TSearch.DirectionsInput[i].Input.data();
                	
                	if (data.service) {
                    	$.each(data.service.split(','), function (i, item) {
                        	if (indexOf(Params["Services"], item) == -1 && item != '') {
                        		Params["Services"].push(item);
                        	}
                    	})                		
                	} 
                }              
			}
			
			Params["Services"] = Params["Services"].join(',');
						
			if (Params["Services"] == '' && ReadCookie('SearchParams_bus')) {
				var c = ReadCookie('SearchParams_bus').split(';');
				$.each(c, function (index, value) {
					if (value != '') {
						value = value.split('=');
						if (value[0] == 'Services' && value[1]) {
							Params["Services"] = value[1];
						}
					}
				})
			}
			
			CookieParams += "Services=" + Params["Services"] + ';';
		}
		
		if (TSearch.DatesInput.length > 0) {
			for (var i = 0; i < TSearch.DatesInput.length; i++) {
				if (TSearch.DatesInput[i].Input.attr('disabled')) continue;
				Params[TSearch.DatesInput[i].Input.attr('id').replace('_input', '')] = TSearch.DatesInput[i].Input.val();
                CookieParams += TSearch.DatesInput[i].Input.attr('id') + '=' + TSearch.DatesInput[i].Input.val() + ';';
			}			
		}
		
		var trip = $('.jNiceChecked').parent().parent().attr('class');
        CookieParams += 'direction=' + $('.jNiceChecked').next().val() + ';';
		if (trip == 'direction_where'){            
			if (TSearch.DirectionsInput.length > 0) {
				for (var i = 0; i < TSearch.DirectionsInput.length; i++) {
                    if(!TSearch.DirectionsInput[i].CodeInput.attr('disabled')){
					    if (TSearch.DirectionsInput[i].CodeInput.attr('id').substr(0, 9) == 'StartAirp') {
						    Params['EndAirp2Code'] = TSearch.DirectionsInput[i].CodeInput.val();                            
					     } else if (TSearch.DirectionsInput[i].CodeInput.attr('id').substr(0, 7) == 'EndAirp') {
						    Params['StartAirp2Code'] = TSearch.DirectionsInput[i].CodeInput.val();
					     }
                    }
				}
			}
		}

		if (TSearch.MoreParams.length > 0) {
		    var checkboxGroup = {};
			for (var i = 0; i < TSearch.MoreParams.length; i++) {
				if (TSearch.MoreParams[i].attr('disabled')) continue;
                if(TSearch.MoreParams[i].attr('type') == 'select-one'){
                    el_id = TSearch.MoreParams[i].attr('id');
                    el_text = TSearch.MoreParams[i].next().find('.jNiceSelectText').text();
                    el_value = $('#' + el_id + ' option:contains(' + el_text + ')').attr('value');
                    Params[el_id.replace('_input', '')] = el_value;
                    CookieParams += el_id + '=' + el_value + '#' + el_text + ';';
                }   else if(TSearch.MoreParams[i].attr('type') == 'radio'){           
                    $('input[name=' + $(TSearch.MoreParams[i]).attr('name') + ']').each(function(){          
                        if($(this).prev('span.jNiceChecked').length == 1){
                            el_value = $(this).prev('span.jNiceChecked').next().val();
                            Params[TSearch.MoreParams[i].attr('name')] = el_value;
                            CookieParams += TSearch.MoreParams[i].attr('name') + el_value + ';'; 
                        }
                    });    
                }   else if(TSearch.MoreParams[i].attr('type') == 'checkbox'){ 
                    if(TSearch.MoreParams[i].attr("checked")){
                        if(typeof(checkboxGroup[TSearch.MoreParams[i].attr('name')]) == 'undefined'){
                            checkboxGroup[TSearch.MoreParams[i].attr('name')] = [];
                        }
                        checkboxGroup[TSearch.MoreParams[i].attr('name')].push(TSearch.MoreParams[i].val());  
                    }    
                }   else{        
                    Params[TSearch.MoreParams[i].attr('id').replace('_input', '')] = TSearch.MoreParams[i].val();
                    CookieParams += TSearch.MoreParams[i].attr('id') + '=' + TSearch.MoreParams[i].val() + ';';
                }
			}
			
			for(checkKey in checkboxGroup){
			    Params[checkKey] = checkboxGroup[checkKey].join(',');
			    CookieParams += checkKey + "_input=" + Params[checkKey] + ";";
			}
					
		}
		
        CreateCookie('SearchParams_' + cur_domain, CookieParams, 1);        
        
		this.Log(Params, 'Send Params');
		return Params;
	}
	
	var nextTabIndex = function (i){
		i++;

		var el = $('#' + TSearch.Options.formId + ' input[tabindex=' + (Number(i)) + ']'); 

		if (el.length == 0){
            return;
        }   else if (!el.val() && !el.attr('disabled') && el.is(':visible')) {
			el.focus().click();
		}   else { 			
			this.nextTabIndex((Number(i)));
		}
	}
    
    var blockManipulation = function(block, action){
        switch(action){
            case 'hide':
                if(!block.hasClass('hidden')){
                    block.addClass('hidden');
                    $('input', block).attr('disabled', 'disabled');
                    $('select', block).attr('disabled', 'disabled');
                    $('div.disabled_select', block).show();
                    $('a.close', block).hide();
                }
                break;
                
            case 'show':
                block.removeClass('hidden');
                $('input', block).removeAttr('disabled');
                $('select', block).removeAttr('disabled');                                
                $('div.disabled_select', block).hide();
                $('div.direction_where', block).show();
                $('a.close', block).hide();
                break;
            
            case 'show_with_blocked_selects':
                block.removeClass('hidden');
                $('input', block).removeAttr('disabled');
                $('select', block).attr('disabled', 'disabled');
                $('div.disabled_select', block).show();
                $('a.close', block).hide();
                break;
            
            case 'show_short':            
                block.removeClass('hidden');
                $('input', block).removeAttr('disabled');
                $('select', block).removeAttr('disabled');
                $('div.disabled_select', block).hide();                
                
                $('div.direction_where', block).hide();
                $('div.direction_where input', block).attr('disabled', 'disabled');
                $('a.close', block).hide();
                break;
                
             case 'show_short_with_disables':            
                block.removeClass('hidden');
                $('input.disabled', block).attr('disabled', 'disabled');
                $('select.disabled', block).attr('disabled', 'disabled');
                $('div.disabled_select', block).show();                
                
                $('div.direction_where', block).hide();
                $('div.direction_where input', block).attr('disabled', 'disabled');
                $('a.close', block).hide();
                break;   
        }
    }
    
    var showLastCloseButton = function(){
        close_button = $('fieldset.complex_dir:visible:last a.close', TSearch.Form);
        if(close_button.length > 0){
            close_button.show();
        }
    }    
    var hideLastDirection = function(){
        block = $('fieldset.complex_dir:visible:last', TSearch.Form);
        if(block.length > 0){
            blockManipulation(block, 'hide');
            showLastCloseButton();
            $('div.add_direction', TSearch.Form).show();
        }
    }    
    var showLastDirection = function(){
        block = $('fieldset.complex_dir:hidden:first', TSearch.Form);
        if(block.length > 0){
            blockManipulation(block, 'show');
            $('a.close', TSearch.Form).hide();
            showLastCloseButton();
        }
        if( $('fieldset.complex_dir:hidden', TSearch.Form).length == 0 ){
            $('div.add_direction', TSearch.Form).hide();
        }
    }    
    	
	return {
		Keys: Keys,
		Log: Log,
		getPosition: getPosition,
		i18n: i18n,
		Result: Result,
		getLoaderParams: getLoaderParams,
		nextTabIndex: nextTabIndex,
        blockManipulation : blockManipulation,
        hideLastDirection : hideLastDirection,
        showLastCloseButton : showLastCloseButton,
        showLastDirection : showLastDirection,
        checkEnableDay : checkEnableDay
	}
}())

/**
 * AutoCompliete
 * 
 */
TSearch.AutoCompliete = (function () {
	var AutoCompliete, Proto,
		Helper = TSearch.Helper,
		i18n = Helper.i18n[language],
		Keys = Helper.Keys;
	
	AutoCompliete = function (Input) {
		this.Input   = Input;
		this.UseCode = (Input.hasClass('use_code') ? true : false);
		this.URL     = TSearch.Options.getCityUrl;
		this.Label   = $('#' + this.Input.attr('name') + '_label');
		this.Icon    = this.Input.parent().find('.icon.glass').css('cursor', 'pointer');

		this.CodeInput = $('#' + this.Input.attr('name') + 'Code_input');
		
		this.initControls();
	}
	
	Proto = AutoCompliete.prototype;
	
	Proto.beforeRequest = function(ajaxObj){}
	
	Proto.initControls = function () {
		var self = this;
		this.Input.bind('click focus', function () {
			if (typeof(use_order) != 'undefined' && 
					use_order === true && 
						self.Input.attr('tabindex') > 1 && !$('input[tabindex=' + (self.Input.attr('tabindex') - 1) + ']').val()) {
				var i = Number(self.Input.attr('tabindex')) - 1;
				$('input[tabindex=' + i + ']').trigger('click');
			} else {
				self.Label.empty();
				$(this).select();				
			}
		}).blur(function () {
			if (!self.Input.val()) {
				self.CodeInput.val('');
				self.Label.text(MO_cityLabel);
			}
		});
		
		this.Icon.bind('click', function () {
			$(this).parent().find('input').click();
		})
		
		
		this.Input.bind('keyup', function (e) {
			self.Label.empty();
			if (e.keyCode == Keys.DOWN) {
				Helper.Result.goDown();
				
			} else if (e.keyCode == Keys.UP) {
				Helper.Result.goUp();	
				
			} else if (e.keyCode == Keys.LEFT || e.keyCode == Keys.RIGHT) {
				return;
				
			} else if (e.keyCode == Keys.ENTER || e.keyCode == Keys.TAB) {
				if (Helper.Result.Box.css("visibility") == 'visible') {
					Helper.Result.selectActiv();
				}
			} else if (e.keyCode == Keys.ESC) {
				if (typeof Helper.Result.Box != 'undefined') {
					Helper.Result.hide();					
				}

			} else {
				if (self.Input.val().length > 2) {
		            if (self.CodeInput.attr('id').substr(0, 9) == 'StartAirp'){
		            	TSearch.dir = 'departure';
		            } else {
		                TSearch.dir = 'arrival';
		                TSearch.code = TSearch.DirectionsInput[0].CodeInput.val();
		            }					
															
					var params = {
						filter: self.Input.val(),
						lang: language,
						code: TSearch.code,
						dir: TSearch.dir
					};
					
					if(self.Input.val() != self.TempValue){					
			            self.TempValue = self.Input.val();
			            var Temp = self.TempValue;
						
						setTimeout(function () {
							self.makeSuggest(params, Temp);
						}, 500)
					}
					
				} else {
					if (typeof Helper.Result.Box != 'undefined') {
						Helper.Result.hide();					
					}
				}			
			}			
		})
	}
	
	Proto.makeSuggest = function (params, CurrentQuery) {
		var self = this;
		
		if (this.TempValue == CurrentQuery) {
		
		$.ajax({
    	    type: "post",
    	    url: this.URL,
    	    dataType: "json",
    	    data: params,
    	    beforeSend: function() {
    	        self.beforeRequest(this);
				self.timerSuggest = null;
				self.Success = false;
    	        $(self.CodeInput).show().val('').addClass("wait").removeClass('hide');
    	    },
    	    success: function(data) {
   	    		$(self.CodeInput).removeClass("wait");
   	    		self.Label.empty();
    	        self.Success = true; 
    	        self.draw(data);
    	        
    	        Helper.Log(data, 'Response');
    	    },
    	    error: function() {
    	        if (self.Try < 3) {
    	            self.Try += 1;
    	            setTimeout(function() { self.makeSuggest(params) }, 350);
    	            return;
    	        }
    	        $(self.CodeInput).removeClass("wait");
    	        alert(MO_str_SuggestUnavailable);
    	    }
    	});
		}
	}
	
	Proto.draw = function (response) {
		this.ResultBox = Helper.Result.init(this.Input, this.UseCode);
				
		var i = response.length;
		if (i == 1) {
			this.Input.val(response[0].name);
			
			this.CodeInput.val(response[0].code);
			
			this.ResultBox.hide();
			Helper.nextTabIndex(this.Input.attr('tabindex'));
			this.Input.data(response[0]);
			
		} else if (i == 0) {
			this.ResultBox.Box.css({
				height: 25,
				width: "91px !important",
				padding: 0			
			});
			
			this.ResultBox.ResultTable.css({
				marginRight: 0,
				height: 25
			});
			
			this.ResultBox.showEmpty();
		} else {
			this.ResultBox.Box.css({
				height: (i < 10 ? (25 * i) : 250),
				width: "auto !important",
				padding: 7			
			});	
	
			this.ResultBox.fillResult(response);
		}		
	}
	
	return AutoCompliete;
}())

/**
 * Calendar
 */
TSearch.Calendar = (function () {
	var Calendar, Proto, 
		Helper = TSearch.Helper,
		i18n   = Helper.i18n[language];
	
	Calendar = function () {
		$('body').append('<div class="datepicker" id="calendarMini"><div class="corner_tl"><div class="IE6"></div></div><div class="corner_tr"><div class="IE6"></div></div><div class="corner_br"><div class="IE6"></div></div><div class="corner_bl"><div class="IE6"></div></div><div class="side_t"><div class="IE6"></div></div><div class="side_b"><div class="IE6"></div></div><div class="side_l"><div class="IE6"></div></div><div class="side_r"><div class="IE6"></div></div><div class="boxContent"><div><div class="wrapp"><table class="monthPan"></table><table cellspacing="4" class="dlabelPan"></table><table cellspacing="4" class="daysPan"></table></div></div></div></div>');
		
		this.Box    = $('#' + TSearch.Options.calendarId);
		this.Header = this.Box.find('.monthPan');
		this.Label  = this.Box.find('.dlabelPan');
		this.Grid   = this.Box.find('.daysPan');
		this.MaxDay = TSearch.Options.maxDays[cur_domain] * 1000 * 3600 * 24;
		this.MinDay = TSearch.Options.minNextDay[cur_domain] * 1000 * 3600 * 24;
		
		
		this.date = new Date();			
		Helper.Log(this.date, 'Today');		
		
		this.initControls();
	}
	
	Proto = Calendar.prototype;
	
	Proto.init = function () {
		this.today = new Date(this.date.getFullYear(), this.date.getMonth(), this.date.getDate()).getTime();
		
		this.fillGrid();
		this.fillHeader();
		this.fillLabel();
	}
	
	Proto.initControls = function () {
		var self = this;
		$('.monthArRight').live('click', function () {
			self.date = new Date(self.date.getFullYear(), self.date.getMonth() + 1, 1);
			self.fillGrid(self.Output.attr('name').replace('Date', ''));
			self.fillHeader();
		});
		
		$('.monthArLeft').live('click', function () {
			self.date = new Date(self.date.getFullYear(), self.date.getMonth() - 1, 1);
			self.fillGrid(self.Output.attr('name').replace('Date', ''));	
			self.fillHeader();
		});
		
		$('.daysPan td').live('click', function () {
			if ($(this).hasClass('cantPick')) return;
			
			var date = $(this).attr('date');
			self.Output.val(date);
			self.Output.click();
			self.hide();
			
			Helper.nextTabIndex(self.Output.attr('tabindex'));
			self.listenerSelDate();

			if ($('#Date_input').length) {
				$('#Date_input').change();
			}
		})
	}
	
	Proto.listenerSelDate = function () {}
	
	Proto.fillGrid = function (p) {	    
		var date     = this.date,
			year     = date.getFullYear(), 					   // поточний рік
			month    = date.getMonth(), 					   // поточний місяць
			first    = new Date(year, month, 1).getDay(),      // перший день місяця	
			last     = new Date(year, month + 1, 0).getDate(), // останній день місяця
			prev     = new Date(year, month, 0).getDate(),     // останній день минулого місяця 
			i, Week, Day, data, title,
			m = month, def, dependsDate = null, p = p || 0, firstDate = $('#fs_travel_period_from').val();

		this.Grid.html('');
				
		for (i = 1; i < 43; i += 1) {
			if ((i - 1) % 7 == 0) {
				Week = $("<tr/>");
				this.Grid.append(Week);
			}

			if (i < first) {
				date = new Date(year, month - 1, prev - first + i + 1);
				m = ((month - 1) < 0 ? 0 : (month - 1));
			} else if (i > last + first - 1) {
				m = ((month + 1) < 12 ? (month + 1) : 0);
				date = new Date(year, month, i - first + 1);
			} else if (first == 0) {
				date = new Date(year, month - 1, prev - 6 + i);
				m = ((month - 1) < 0 ? 0 : (month - 1));
				if (i == 6) {
					first = 7;
				}
			} else {
				m = month;
				date = new Date(year, month, i - first + 1);
			}
			
			def = date.getTime() - this.today;	
			Day = $("<td date='" + date.toNormalDate() + "'>" + date.getDate() + "</td>");
			
			var self = this;
			
			if (date.getTime() < this.today || Helper.checkEnableDay(date, this) == false) {
				Day.addClass('othermonth cantPick');	
			} else if (date.getMonth() < month && def < this.MaxDay) {
				Day.addClass('othermonth');
			} else if (date.getMonth() > month && def < this.MaxDay) {
				Day.addClass('othermonth');
			} else if (date.getTime() == this.today) {
				Day.addClass('today');
			} else if (def > this.MaxDay) {
				Day.addClass('cantPick othermonth');
			}

			if (p > 1 && TSearch.DatesInput[(p-2)].Input.val() || firstDate) {
				var selectDate = (firstDate) ? firstDate.split('.') : TSearch.DatesInput[(p-2)].Input.val().split('.');
				var dateToTime = new Date(selectDate[2], (selectDate[1] - 1), selectDate[0]).getTime();
				if (date.getTime() < (dateToTime + this.MinDay)) {
					Day.addClass('othermonth cantPick');
					$('.today').addClass('cantPick');
				} else {
					Day.addClass('othermonth');
				}
			}
			Week.append(Day);
		}
		
	}
	
	Proto.fillHeader = function () {
		var title = i18n.months[this.date.getMonth()] + ' ' + this.date.getFullYear();
		this.Header.html('<tr><td class="monthArLeft"><a class="arleft"></a></td><td class="monthContent"><span>' + title + '</span></td><td class="monthArRight"><a class="arright"></a></td></tr>');
	}
	
	Proto.fillLabel = function () {
		var tr = $('<tr/>');
		for (var i = 0; i < 7; i++) {
			tr.append("<td>" + i18n.days[i] + "</td>");
		}
		this.Label.append(tr);
	}
	
	Proto.setPosition = function (offset) {
		var top = offset.top + 28;
		this.Box.addClass('dp_search');
		
		if (typeof(TSearch.Options.scrollFixed) != "undefined" && TSearch.Options.scrollFixed) {
			top = top - 28;
			//offset.left = offset.left + 3;
			//this.Box.removeClass('dp_search');
		}

		this.Box.css({
			left: offset.left,
			top: top
		})
	}
	
	Proto.show = function(output) {
		this.Output = output;
		this.fillGrid(this.Output.attr('name').replace('Date', ''));
		
		if (this.Box.is(':visible')) {
			this.hide();
		} else {
			this.Box.show();		
		}
		
		$('.page').bind("click", {self: this}, this.hideIfClickOutside);	
	}
	
	Proto.hide = function () {
		this.Box.hide();
	}
	
	Proto.hideIfClickOutside = function (e) {
		var self = e.data.self;
	    if (e.target != self.Output[0]) {
	    	if (typeof(TSearch.Options.searchButton) != "undefined") {
		    	if (e.target != TSearch.Options.searchButton[0] && e.target != TSearch.Options.searchButton.find('canvas')[0]){
					self.hide();
				}
			} else {
				if($(e.target).attr('id') != 'DateToHref') {
					self.hide();
				}
			}
	    }		
	}
	
	return Calendar;	
}())

/**
 * DatePicker
 */
TSearch.DatePicker = (function () {
	var DatePicker, Proto,
		Helper = TSearch.Helper;
	
	DatePicker = function (Input) {
		this.Input   = Input;
		
		this.initControls();
	}
	
	Proto = DatePicker.prototype;
	
	Proto.initControls = function () {
		var self = this;
		
		this.Input.bind('click', function () {
			var XY = Helper.getPosition($(this));
			TSearch.Calendar.setPosition(XY);
			TSearch.Calendar.show(self.Input);
		})
	}
	
	return DatePicker;
}())


/**
 * Init
 */
TSearch.Init = (function () {
	var Init, Proto, Helper = TSearch.Helper;
	
	Init = function (options) {
		TSearch.Options = options;
		this.Form   = $('#' + options.formId);	
				
		Helper.Log(TSearch.Options, 'Options');
		
		this.getDirectionsInput();
		this.getDatesInput();
		this.getPlusMinusInput();
		this.getTimeInput();
		this.getMoreParams();
		
		TSearch.Calendar = new TSearch.Calendar();
		TSearch.Calendar.init();
		
		var self = this;
		
		$('body').append('<div class="SuggestResult"><div class="SuggestResult_ins"><table class="SuggestResult"></table></div></div>');
		
		$('.choose_direction li span').click(function (){
			var trip = $(this).parent().parent().attr('class');
            $('div.add_direction', self.Form).hide();
			if (trip == 'direction_where'){
                $('.complex_dir', self.Form).removeClass('complex_dir');
                $('div.timecol', self.Form).show();
                
                Helper.blockManipulation($('#Direction1'), 'show');
                Helper.blockManipulation($('#Direction2'), 'show_short');
                Helper.blockManipulation($('#Direction3'), 'hide');                
                
			} else if (trip == 'complex_direction'){
                $('fieldset:gt(0)', self.Form).addClass('complex_dir');
                Helper.blockManipulation($('#Direction2'), 'show');
                Helper.blockManipulation($('#Direction3'), 'show');                
                    
                plus_blocks = $('div.timecol', self.Form);
                plus_blocks.hide();
                plus_blocks.find('select').attr('disabled', 'disabled');
                Helper.showLastCloseButton();
            } else {
                $('.complex_dir', self.Form).removeClass('complex_dir');
                $('div.timecol', self.Form).show();
                
                Helper.blockManipulation($('#Direction1'), 'show');
                Helper.blockManipulation($('#Direction2'), 'show_short_with_disables');
                Helper.blockManipulation($('#Direction3'), 'hide');                
			}            
            Helper.nextTabIndex(0);            
		});
		
		$('.insurance_product li span').click(function () {
			var product = $(this).parent().parent().attr('class');
			$('[id*=Product_]', self.Form).hide();
			$('input:not(.not_change), select', self.Form).attr('disabled', 'disabled');
			$('#Product_' + product).find('input, select').removeAttr('disabled');
			$('#Product_' + product).show();
		});
		
		if (typeof(insurance_product) != "undefined") {
			$('.insurance_product li.' + insurance_product + ' span').click();
		}
		
        //Init close direction buttons	
        $('a.close', self.Form).click(function(){
            Helper.hideLastDirection();
        }); 
        $('a.continue_trip', self.Form).click(function(){
            Helper.showLastDirection();
        });
           
        if (typeof(options.searchButton) != "undefined") {
			options.searchButton.click(function () {
				if (self.validation()) {
					TSearch.Options.loader[cur_domain].params = Helper.getLoaderParams();
					TSearch.Options.loader[cur_domain].ajax();				
				}
			});        	
        }     
		
	}
	
	Proto = Init.prototype;
	
	Proto.validation = function () {
		var valid = true;
		$('input', this.Form).each(function () {
			if ($(this).attr('disabled') || $(this).attr('allow_blank')) {
				return true;
			}
			
			if (!$(this).val()) {
				$(this).click();
				valid = false;
				return false;
			}
		});
		
		if($('#in_ukraine_confirm').length) {
			valid = $('#in_ukraine_confirm').is(":checked");
		}

		return valid;
	}
	
	//get Directions Input
	Proto.getDirectionsInput = function () {
		var self = this, Input;	
		
		$('.autocompliete', this.Form).each(function () {
			Input = new TSearch.AutoCompliete($(this));
			
			TSearch.DirectionsInput.push(Input);
		})

		Helper.Log(TSearch.DirectionsInput, 'DirectionsInput');
	}
	
	//get DatePicker Inputs
	Proto.getDatesInput = function () {
		var self = this, Input;
		
		$('.datepicker', this.Form).each(function () {
			Input = new TSearch.DatePicker($(this));

			TSearch.DatesInput.push(Input);
		})		
		
		Helper.Log(TSearch.DatesInput, 'DatesInput');
	}
	
	//get PlusMinus Inputs
	Proto.getPlusMinusInput = function () {
		var self = this, Input;
		
		$('.plusminus', this.Form).each(function () {
			Input = new TSearch.TimePicker($(this));
			
			TSearch.PlusMinusInput.push(Input);
		})		
		
		Helper.Log(TSearch.PlusMinusInput , 'PlusMinusInput');		
	}
	
	//get Time Inputs
	Proto.getTimeInput = function () {
		var self = this, Input;
		
		$('.timepicker', this.Form).each(function () {
			Input = new TSearch.TimePicker($(this));
			
			TSearch.TimeInput.push(Input);
		})		
		
		Helper.Log(TSearch.TimeInput , 'TimeInputs');		
	}
	
	//get More Params
	Proto.getMoreParams = function () {		
		$('.more_params', this.Form).each(function () {
			TSearch.MoreParams.push($(this));
		})		
		
		Helper.Log(TSearch.MoreParams , 'MoreParams');			
	}
	
	return Init;	
}());

