﻿Controller = function() {
	Controller.superClass.apply( this, arguments );
	this.Drag = new Drag();
	this.form = false;
	this.calendar = false;
	this.button = new Button( this.getEl( 'button' ) );
	this.button.attachObserver( 'buttonSubmited', this.send, this );
	this.button.attachObserver( 'buttonClicked', this.alertWrong, this );

	//if( this.getEl( 'promo' ) ) this.promoCode();
	this.sDays = new Array();

	this.searchUrl = false;
	this.searchStore = new Store( sAjaxRequestCommander, { 'Commander.CommandExecutionMode': 'ASYNCHRONOUS' });
	//this.searchStore = new Store( '/ajax/ajax-request-commander-y2.html', { 'Commander.CommandExecutionMode': 'ASYNCHRONOUS' });
	this.searchStore.attachObserver( 'Loaded', this.checkState , this );
}
Controller.inheritsFrom( IL );

//----------------------------------------------------------------------------//

Controller.prototype.checkState = function( result ) {
	if( Boolean( result[ 'CommandId' ] ) ) {
		this.fillForm( this.searchUrl, { 'SearchId': result[ 'CommandId' ] } );
		this.submit();
	} else {
		alert( 'Извините, произошла ошибка. Попрбуйте ещё раз.' );
	}
}

/* ---------------------------------------------------------------------- */

Controller.prototype.alertWrong = function() {
	if( !this.form || !this.form.status ) {
		alert( this.form.getError() );
		return false;
	}

	if( !this.calendar || !this.calendar.status ) {
		alert( this.calendar.getError() );
		return false;
	}
}

/* ---------------------------------------------------------------------- */

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;
	}
}

/* ---------------------------------------------------------------------- */

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.createForm = function( form, target ) {
	var form = new form( target );
	form.attachObserver( 'formStatusChange', this.check, this );
	return form;
}

/* ---------------------------------------------------------------------- */

Controller.prototype.setCalendar = function( count ) {
	if( !this.calendar || !this.calendar.changeMode ) return false;
	this.calendar.changeMode( count );
}

/* ---------------------------------------------------------------------- */

Controller.prototype.setDate = function( params, obj ) {
	var date = params.date;
	var label = this.form.labels[ params.type ];
	
	if( label && label.setContent ) {
		var string = '<big>' + date.getDate() + '</big> ' + obj.monthsListGC[ date.getMonth() ] + ', ' + obj.weekdaysList[ date.getDay() ];
		label.setContent( string );
	}
	this.sDays[ params.type ] = date;
}

/* ---------------------------------------------------------------------- */

Controller.prototype.unSetDate = function( params ) {
	if( !params || typeof( params ) != 'number' ) return;
	if( this.sDays && this.sDays.length > 0 ) {
		this.sDays.splice( params - 1 , 1 );
	}
	var label = this.form.labels[ params - 1 ];
	if( label && label.setContent ) {
		label.setContent( '' );
	}
}

/* ---------------------------------------------------------------------- */

Controller.prototype.translateDate = function( sDate ) {
	var sDate = sDate.substring( 0, 10 );
	return new Date( Number( sDate.substring( 0, 4 ) ), Number( sDate.substring( 5, 7 ) ) - 1, Number( sDate.substring( 8, 10 ) ) );
}

/* -------------------------------------------------------------------------- */
/* ------------------------------- Promo ------------------------------------ */
/* -------------------------------------------------------------------------- */

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 );
}
IndexForm.inheritsFrom( Form );


/* -------------------------------------------------------------------------- */

IndexForm.prototype.check = function() {
	var oS = this.status;
	
	this.status = true;
	for( var c in this.inputs ) {
		this.inputs[c].check();
		if( !this.inputs[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' );
	return this.status;
}

/* -------------------------------------------------------------------------- */

IndexForm.prototype.setInput = function( template ) {
	var newInput = new PredicateInput( this.element );
	newInput.idx = this.inputs.length;
	this.inputs[ this.inputs.length ] = newInput;
	
	newInput.setTemplate( template );
	newInput.showTemplate( true );

	newInput.attachObserver( 'inputError', this.setError, this );
	newInput.attachObserver( 'inputStatusChange', this.onInputChange, this );
	newInput.attachObserver( 'inputSetted', this.onInputSet, this );
	newInput.attachObserver( 'Typing', this.onInputTyping, this );
	newInput.attachObserver( 'hidePad', this.onPadClosed, this );
	
	newInput.input.tabIndex = (newInput.idx + 1);

	return newInput;
}

/* -------------------------------------------------------------------------- */

IndexForm.prototype.setLabel = function() {
	var newLabel = new Label( this.labels.length, this.element );
	newLabel.idx = this.labels.length;
	this.labels[ this.labels.length ] = newLabel;
	return newLabel;
}

/* -------------------------------------------------------------------------- */

IndexForm.prototype.removeLabel = function( iIdx ) {
	iIdx = iIdx || ( this.labels.length - 1 );
	if( typeof( iIdx ) != 'number' || iIdx >= this.labels.length || !this.labels[ iIdx ] ) return false;
	this.labels[ iIdx ].remove();
	this.labels.splice( iIdx, 1 );
}

/* -------------------------------------------------------------------------- */

IndexForm.prototype.onInputTyping = function( params, input ) {
	var value = input.getValue();
	input.setData( false );

	if( value.length >= 1 ) {
		if ( this.timer) {
			clearTimeout( this.timer );
			this.timer = false;
		}

		var obj = this;
		this.timer = window.setTimeout( function() { loadData( obj.store, input ); }, 100 );
	} else {
		input.pad.construct( false );
	}
}

/* -------------------------------------------------------------------------- */

IndexForm.prototype.storeLoaded = function( result, obj ) {
	obj.target.setTip( false );
	obj.target.setDataList( result );
}

/* -------------------------------------------------------------------------- */

IndexForm.prototype.onPadClosed = function( params, obj ) {
	if(  obj.pad && obj.getData && !obj.getData() ) {
		var val = obj.getValue();

		var cD = false;
		var data = obj.pad.getData();

		for( var i = data.length; i; i-- ) {
			cD = data[ i - 1 ];
			if( cD[ 'Code' ] == null || cD[ 'Name' ] == null || !cD[ 'Name' ] || !cD[ 'Code' ] ) continue;
			if( cD[ 'Code' ].toLowerCase() == val.toLowerCase() || cD[ 'Code' ].toLowerCase() == val.toLowerCase() ) break;
		}

		cD = cD || data[0];
		if( cD && cD[ 'Name' ] ) {
			obj.set( cD, cD[ 'Name' ] );
			obj.setClassName( 'gray', false );
		}
	}
}

/* ---------------------------------------------------------------------- */

function loadData( store, input ) {
	var value = input.getValue();
	store.addParams( { Word: value } );
	store.setTarget( input );
	input.setTip( '<img src="/images/index/loading.gif" alt="Загрузка" title="Загрузка" />' );
	store.load();
}


/* -------------------------------------------------------------------------- */
/* ------------------------------ Persons ----------------------------------- */
/* -------------------------------------------------------------------------- */

Persons = function( target, limit ) {
	Persons.superClass.apply( this, arguments );
	this.element = target;
	
	this.unactivies = target.firstChild;
	this.activies = target.childNodes[1];
	this.label = target.childNodes[2];

	this.activeUnder2 = this.activies.firstChild;
	this.activeBefore2 = this.activies.lastChild;

	this.title = new HTMLGlif();
	this.title.element = target.lastChild;
	
	this.controls = new Array();
	this.persons = new Array();

	this.adult = 0;
	this.child = 0;
	this.baby = 0;

	this.limit;

	this.lastAdult = this.setPerson( 'adult' );
	this.lastAdult.setClassName( 'no', true );
}
Persons.inheritsFrom( HTMLGlif );

/* -------------------------------- Set ------------------------------------- */

Persons.prototype.set = function( adults, childs, infants ) {
	if( this.controls.adult ) {
		for( var i = 0; i < adults - 1; i++ ) {
			this.controls.adult.notify( 'PersonClicked' );
		}
	}

	if( childs > 0 && this.controls.child ) {
		for( var i = 0; i < childs; i++ ) {
			this.controls.child.notify( 'PersonClicked' );
		}
	}
	
	if( infants > 0 && this.controls.baby ) {
		for( var i = 0; i < infants; i++ ) {
			this.controls.baby.notify( 'PersonClicked' );
		}
	}
}

/* -------------------------- Create Persons -------------------------------- */

Persons.prototype.createPerson = function( age, target ) {
	var title = false;
	switch( age ) {
		case 'adult': title = 'Взрослый'; break;
		case 'child': title = 'Ребенок'; break;
		case 'baby': title = 'Младенец'; break;
	}

	var newPerson = new Person( age, target );
	this.setClassName( age, true, newPerson.inner );
	this.setProperty( { title: title }, newPerson.inner );
	newPerson.attachObserver( 'ToggleHover', this.toggleHover, this );
	return newPerson;
}

/* ----------------------------- Set Person --------------------------------- */

Persons.prototype.setPerson = function( age ) {
	var newPerson;
	this[ age ]++;
	if( age != 'adult' || !this.lastAdult ) {
		var target = ( age == 'baby' ? this.activeBefore2 : this.activeUnder2 );
		newPerson = this.createPerson( age, target );
	} else {
		newPerson = this.createPerson( age );
		this.activeUnder2.insertBefore( newPerson.element, this.lastAdult.element );
	}
	
	this.persons[ this.persons.length ] = newPerson;
	newPerson.attachObserver( 'PersonClicked', this.personClicked, this );
	return newPerson;
}

/* ---------------------------- Set Control --------------------------------- */

Persons.prototype.setControl = function( age ) {
	var newPerson = this.createPerson( age, this.unactivies );

	this.controls[ age ] = newPerson;
	newPerson.attachObserver( 'PersonClicked', this.controlClicked, this );
	return newPerson;
}

/* ----------------------------- Get Value ---------------------------------- */

Persons.prototype.getValue = function() {
	var result = {
		Dlts: this.adult,
		Children: this.child,
		Infants: this.baby
	};
	return result;
}

/* --------------------------- Toggle Hover --------------------------------- */

Persons.prototype.toggleHover = function( params, obj ) {
	obj.hover = !obj.hover;
	obj.setClassName( 'hover', obj.hover );
}


/* --------------------------- Set Disabled --------------------------------- */

Persons.prototype.setDisabled = function( age, flag ) {
	if( !this.controls[ age ] ) return false;
	this.controls[ age ].setClassName( 'disabled', flag );
}

/* ---------------------------------------------------------------------- */

Persons.prototype.personClicked = function( params, obj ) {
	if( obj.age == 'adult' ) {
		if( this.adult == 1 ) return false;
		this.checkInfantCount();
	}

	if( obj == this.lastAdult && this.changeLastAdult( obj ) ) return false;

	this[ obj.age ]--;
	obj.remove();
	
	for( var idx in this.persons ) {
		if( obj == this.persons[ idx ] ) break;
	}

	this.persons.splice( idx, 1 );

	this.checkOnDisable();
	this.setTitle();
}

/* ---------------------------------------------------------------------- */

Persons.prototype.controlClicked = function( params, obj ) {
	if( !this.check( obj ) ) return false;
	this.setPerson( obj.age );
	this.checkOnDisable();
	this.setTitle();
}

/* ------------------------------ Check ------------------------------------- */

Persons.prototype.check = function( obj ) {}

Persons.prototype.checkOnDisable = function( obj ) {}

Persons.prototype.checkInfantCount = function() {
	if( this.adult == this.baby ) {
		for( var c in this.persons ) {
			var cP = this.persons[c];
			if( cP.age == 'baby' ) {
				cP.notify( 'PersonClicked' );
				break;
			}
		}
	}
}

/* ------------------------ Change Last Adult ------------------------------- */

Persons.prototype.changeLastAdult = function( obj ) {
	var el = this.lastAdult.element.previousSibling;
	for( var c in this.persons ) {
		var cP = this.persons[c];
		if( cP.element == el ) {
			cP.notify( 'PersonClicked' );
			return true;
		}
	}
	return false;
}

/* ----------------------------- Set Label ---------------------------------- */

Persons.prototype.setLabel = function( label ) {
	this.setContent( label, this.label );
}

/* ----------------------------- Set Title ---------------------------------- */

Persons.prototype.setTitle = function() {
	var string = '<small>' + this.adult + '</small>&nbsp;' + ( this.adult > 1 ? 'взрослых' : 'взрослый' );
	if ( this.child > 0 ) {
		string += ', <small>' + this.child + '</small>&nbsp;' + ( this.child > 1 ? 'детей' : 'ребенок' );
	}
	if ( this.baby > 0 ) {
		string += ', <small>' + this.baby + '</small>&nbsp;' + ( this.baby > 1 ? 'младенца' : 'младенец' );
	}
	
	this.title.setContent( string );
}