var shuffleArray = function( array ) {
	var i = array.length, j, t;
	while( i ) {
		j = Math.floor( ( i-- ) * Math.random() );
		t = array[ i ];
		array[ i ] = array[ j ];
		array[ j ] = t;
	};
	return array;
};

var today = new Date( now.getFullYear(), now.getMonth(), now.getDate() );

var date365 = new Date( today.valueOf() + 365 * 24 * 60 * 60 * 1000 );
var date44 = new Date( today.valueOf() + 45 * 24 * 60 * 60 * 1000 );
var routeColors = ['cyan', 'orange', 'green', 'violet'];
var datesErrorTexts = {
	errorInputText: 'Проверьте правильность ввода даты',
	errorPatternText: 'Проверьте правильность ввода даты',
	errorEmptyText: 'Введите дату',
	errorMinMaxText: 'Дата находится вне диапазона'
}

Controller = function() {
	Controller.superClass.apply( this, arguments );
	
	this.Id = 'Controller';
	//this.Drag = new Drag();
	this.form = false;
	this.calendar = false;
	
	//IE Calendar issue workaround (disappearing month name)
	if ($.browser.msie) {
		$('#days div.month-block').each(function(){
			this.firstChild.style.backgroundColor='transparent';
		})
	}
	
	this.elementReset = this.getEl( 'resetForm' );
	$('#resetForm').hover(
		function(){	$(this).addClass( 'hover' ) },
		function(){ $(this).removeClass( 'hover' ) }
	)
	/*$('#button').hover(
		function(){	$(this).addClass( 'hover' ) },
		function(){ $(this).removeClass( 'hover' ) }
	)*/
	this.addHandler( this.elementReset, 'click', this.resetInputs );
	
	this.button = new Button( this.getEl( 'button' ) );
	this.button.attachObserver( 'buttonSubmited', this.send, this );
	this.button.attachObserver( 'buttonClicked', this.checkOnClick, this );

	//if( this.getEl( 'promo' ) ) this.promoCode();
	this.sDays = new Array();
	
	this.searchUrl = false;
	/*this.searchStoreSaveParams = new Store( sAjaxRequestCommander,
		{	'Commander.CommandExecutionMode': 'SYNCHRONOUS',
			'SaveParametersOnly': 'True'
	});
	this.searchStoreSaveParams.attachObserver( 'Loaded', this.checkStateOfStoreSaveParams, this );*/
	var searchUrl = window.location.pathname.substr( 0, 8 ) == '/flight/'  ? sAjaxSearchCommander : sAjaxRequestCommander;	// если авиа, то идем другим путем
	this.searchStore = new Store( searchUrl, { 'Commander.CommandExecutionMode': 'ASYNCHRONOUS' });
	
	
	this.searchStore.attachObserver( 'Loaded', this.checkState , this );
}
Controller.inheritsFrom( IL );

//----------------------------------------------------------------------------//

// создает форму
Controller.prototype.createForm = function( form, target ) {
	form = new form( target );
	form.attachObserver( 'formStatusChange', this.check, this );
	return form;
}

// получает параметр SearchId и передает его дальше
Controller.prototype.checkState = function( result ) {
	if( Boolean( result[ 'CommandId' ] ) ) {
		var SearchId = result[ 'CommandId' ];
		var ContextSessionId = result[ 'ContextSessionId' ];
		var checkerSG = new Checker( '/ajax/check-storage-global.html', {
			'SearchId': SearchId,
			'ContextSessionId': ContextSessionId,
			'Quantity': 2
		});
		checkerSG.attachObserver( 'Loaded', function(){
			this.fillForm( this.searchUrl, { 'SearchId': SearchId } );
			this.submit();
		}, this );
		checkerSG.attachObserver( 'Error', function(){
			alert( 'Во время обработки вашего запроса на нашем сервере произошла ошибка. ' +
				  'Пожалуйста, попробуйте ещё раз через несколько минут ' +
				  'или свяжитесь с нашей службой клиентской поддержки по телефону (495) 787-28-88.' );
			this.sendFeedbackAboutProblem( 'В 3й раз не достучались.' );
			this.sended = false;
		}, this );
		/*window.setTimeout( function(){
			checkerSG.load()
		}, 20000 );*/
		checkerSG.load();
		//checkerSG.attachObserver( 'Error', this.stateError, this );
	} else {
		alert( 'Во время обработки вашего запроса на нашем сервере произошла ошибка. ' +
			  'Пожалуйста, попробуйте ещё раз через несколько минут ' +
			  'или свяжитесь с нашей службой клиентской поддержки по телефону (495) 787-28-88.' );
		this.sendFeedbackAboutProblem( 'Не получен Id поиска.' );
		this.sended = false;
	}
}

Controller.prototype.sendFeedbackAboutProblem = function( comments ){
	var id = this.Id;
	$.ajax({
		url: '/ajax/feedback-about-server-problem.html',
		type: 'POST',
		dataType: 'json',
		data: {
			'ElementName': 'Feedback',
			//'FromEmail': 'bilet@ozon.travel',
			//'FromName': 'OZON.travel',
			//'To': 'Серж <skhabarov-veliky@ozon.travel>',
			//'Cc': 'Светлана <sgalahova@ozon.travel>',
			'Subject': 'S',
			'Body': 'B',
			'Comment': comments
		},
		complete: function( xhr, status ){
			var y = 1;
			//alert( status );
		}
	});
}

// проверка контроллера во время заполнения данных
Controller.prototype.check = function() {
	if( !this.button || !this.button.setValid ) return false;
	if(
		( this.form && this.form.status )
		//&& ( this.calendar && this.calendar.status )
	) {
		this.button.setValid( true );
		return true;
	} else {
		this.button.setValid( false );
		return false;
	}
	return true;
}

// реакция на нажатие кнопки
Controller.prototype.checkOnClick = function() {
	this.checkToSubmit();
}

// проверка по нажатию кнопки
Controller.prototype.checkToSubmit = function() {
	this.status = true;

	if( !this.form.checkToSubmit() ) {
		this.status = false;
	}
	
	/*if( !this.calendar || !this.calendar.status ) {
		//alert( this.calendar.getError() );
		this.status = false;
	}*/

	this.button.setValid( this.status );
	return this.status;

/*	
	if( !this.form || !this.form.status ) {
		for( var i = 0, len = this.form.inputs.length; i < len; i++ ) {
			this.form.inputs[ i ].checkToSubmit();
			if( !this.form.inputs[ i ].status) {
				this.form.inputs[ i ].blur();
			}
		}
		for( var i = 0, len = this.form.dates.length; i < len; i++ ) {
			this.form.dates[ i ].check();
			if( !this.form.dates[ i ].status) {
				this.form.dates[ i ].blur();
			}
		}
		//alert( this.form.getError() );
		return;
	}
*/

/*	if( !this.calendar || !this.calendar.status ) {
		alert( this.calendar.getError() );
		return;
	}
*/
}


Controller.prototype.send = function() {}
Controller.prototype.init = function() {}

Controller.prototype.fillForm = function( url, params ) {
	this.button.fillForm( url, params );
}

Controller.prototype.submit = function() {
	this.button.submit();
}


Controller.prototype.setNumberOfDatesInCalendar = function( count ) {
	//if( !this.calendar || !this.calendar.changeMode ) return;
	this.calendar.changeMode( count );
}

Controller.prototype.resetInputs = function(){
	this.form.reset();
	this.calendar.clear();
	this.persons.reset();
	$('#resetForm').addClass( 'hidden' );
	this.check();
}

// преобразует дату из 2010-02-02 в объект дата
Controller.prototype.translateDate = function( sDate ) {
	sDate = sDate.substring( 0, 10 );
	return new Date( Number( sDate.substring( 0, 4 ) ), Number( sDate.substring( 5, 7 ) ) - 1, Number( sDate.substring( 8, 10 ) ) );
}


// -------------------------------------------------------------------------- //
/*
Controller.prototype.promoCode = function() {
	this.promo = new TextInput( this.getEl( 'promo' ).childNodes[1] );
	this.promo.setTip( 'промо код' );
}
*/
// -------------------------------------------------------------------------- //
/* -------------------------------- Form ------------------------------------ */
// -------------------------------------------------------------------------- //

IndexForm = function( target ) {
	IndexForm.superClass.apply( this, arguments );

	this.Id = 'IndexForm';
	this.status = false;
}
IndexForm.inheritsFrom( Form );

// -------------------------------------------------------------------------- //
// после выбора даты в календаре кладем ее в поле ввода
IndexForm.prototype.setInputDate = function( params, obj ) {
	this.dates[ params.index ].setDefault( params.date );
	this.setMinToNextDate( params.index, params.date );
	this.setMaxToPrevDate( params.index, params.date );
	this.checkSelfMax( params.index );
	//this.dates[ params.index ].checkPattern();
	//this.check();
}

IndexForm.prototype.setMinToNextDate = function( index, date ){
	if ( this.dates[ index + 1 ] ){
		this.dates[ index + 1 ].setMin( date );
		this.dates[ index + 1 ].setMax( date365 );
	}
}

IndexForm.prototype.setMaxToPrevDate = function( index, date ){
	if ( index >= 1 ){
		this.dates[ index - 1 ].setMax( date );
	}
}
IndexForm.prototype.checkSelfMax = function( index ){
	if ( this.dates[ index ].min.valueOf() >= this.dates[ index ].max.valueOf() ){
		this.dates[ index ].setMax( date365 );
	}
	/*в сложном маршруте, чтобы избежать ситуации, когда min больше при изменении дат max */
}

// когда в календаре все даты выбраны и ставим новую, обнуляем все кроме первой
IndexForm.prototype.unsetInputDate = function( countToDelete ) {
	//if( !index || typeof( index ) != 'number' ) return;
	this.dates[ 0 ].setMax( date365 );
	for( var i = this.dates.length - countToDelete, len = this.dates.length; i < len; i++ ){
		this.dates[ i ].clear();
		this.dates[ i ].setMin( this.dates[ 0 ].getData() );
	}
	//this.check();
}


// переопределяем функцию 
IndexForm.prototype.check = function() {
	var oS = this.status;
	
	this.status = true;
	for( var c in this.inputs ) {
		if( !this.inputs[ c ].status ) {
			this.status = false;
			break;
		}
	}

	if ( this.status && this.dates ) {
		for( var c in this.dates ) {
			if( !this.dates[ c ].status ) {
				this.status = false;
			}
		}
	}

/*	var inp1Id = ( this.getInput(0) && this.getInput(0).getData( 'Id' ) ) || false;
	var inp2Id = ( this.getInput(1) && this.getInput(1).getData( 'Id' ) ) || false;

	if( inp1Id && inp2Id && ( inp1Id == inp2Id ) ) {
		this.status = false;
	}
*/
	//if( !( oS === this.status ) )
	this.notify( 'formStatusChange', this );
	//return this.status;
}

IndexForm.prototype.checkToSubmit = function() {
	var oS = this.status;
	
	this.status = true;
	for( var c in this.inputs ) {
		if( !this.inputs[ c ].checkToSubmit() ) {
			this.status = false;
		}
	}

	if ( this.status && this.dates ) {
		for( var c in this.dates ) {
			if( !this.dates[ c ].checkToSubmit() ) {
				this.status = false;
			}
		}
	}
	
	//if( !( oS === this.status ) ) this.notify( 'formStatusChange', this );
	return this.status;
}

/*
IndexForm.prototype.check = function() {
	var oS = this.status;
	
	this.status = true;
	for( var i = 0, len = this.inputs.length; i < len; i++ ) {
		//this.inputs[ i ].check();
		if( !this.inputs[ i ].status ) {
			this.status = false;
		}
	}
	if (this.status && this.dates) {
		for( var j = 0, len = this.dates.length; j < len; j++ ) {
			//this.dates[ j ].check();
			if( !this.dates[ j ].data ) {
				this.status = false;
			}
		}
	}

	var inp1Id = ( this.getInput(0) && this.getInput(0).getData( 'Id' ) ) || false;
	var inp2Id = ( this.getInput(1) && this.getInput(1).getData( 'Id' ) ) || false;

	if( inp1Id && inp2Id && ( inp1Id == inp2Id ) ) {
		this.status = false;
	}

	if( !( oS === this.status ) ) this.notify( 'formStatusChange' );
	return this.status;
}
*/
