/**
 * SearchEngine Initialisation class
 *
 * @author Pascal Bleuse
 * @version 08 Dec 2009
 */

var SearchEngine = new Class( {

	Implements: Options,
	
	options: {
		lang: CookieManager.get( 'lang' ) || 'en',
		cmd: '/cmd/?cmd=GetAirportsMatch&format=json',
		proxy: false,
		extLang: false,
		iframe: false,
		redirectPage: 'Prices',
		hasPrices: true,
		forceComplete: true,
		ignoreGroup: false,
		withCountry: false,
		getCheapPrice: true,
		form: $('searchEngine'),
		search: ['origin', 'destination'],
		opposite: {
			origin: 'destination',
			destination: 'origin'
		},
		date: ['depDate', 'retDate'],
		dateText: ['depDateText', 'retDateText'],
		oneway: {
			field: $('oneway'),
			text: 'One way',
			state: false
		},
		submit: {
			field: $('se_submit'),
			text: 'Search',
			wait: 'Wait',
			force: false
		},
		// Default value
		origin: {
			text: 'I want to fly from...',
			anywhere: 'Anywhere',
			loaded: null,
			iata: null,
			iso: null
		},
		destination: {
			text: 'I want to fly to...',
			anywhere: 'Anywhere',
			loaded: null,
			iata: null,
			iso: null
		},
		calendar: {
			active: true,
			popup: false, // Enable/Disable popup possibility on Smoothbox
			container: { // if popup enabled, info is require
				parent: null,
				row: null
			},
			pattern: 'D d M Y',
			cal_start: null,
			cal_end: null,
			days: null,
			months: null
		},
		depDate: {
			text: 'Whenever',
			loaded: null,
			loaded_txt: null,
			loaded_url: null
		},	
		retDate: {
			text: 'Whenever',
			loaded: null,
			loaded_txt: null,
			loaded_url: null
		},
		wayfare: {
			enabled: false,
			click: 'ConvertSearchFields',
			args: ['checkbox','','','airfare']
		}
	},
	
	initialize: function( options ) {
	
		var $this = this;

		if( $type( options ) == 'object' ) this.setOptions( options );
		
		if( this.options.proxy == true ) this.options.cmd = this.options.cmd + '&proxy=true';
		
		// Init Search Engine
		this.options.search.each( function( el ) {
			$this[el] = {};
			$this[el].field = $(el);
			$this[el].date = null;
			
			var loader = $this.options.form.getElement( '.autocompleter-loading' );
			
			var cmd = $this.options.cmd + '&lang=' + $this.options.lang + '&extLang=' + $this.options.extLang;
			if( $this.options.ignoreGroup ) cmd += '&ignoreGroup=' + $this.options.ignoreGroup;
			if( $this.options.withCountry ) cmd += '&withCountry=' + $this.options.withCountry;
			
			$this[el].ac =  new Autocompleter.BTSE( $this[el].field, cmd, {
				indicatorClass: 'autocompleter-loading',
				delay: 400,
				minLength: ( $this.options.withCountry == true ? 2 : 3 ),
				postVar: 'match',
				ajaxOptions: {
					method: 'get',
					link: 'cancel'
				},
				forceComplete: $this.options.forceComplete,
				onFailure: function() {
					$this.options.submit.field.disabled = false;
					$this.options.submit.force = true;
				},
				onRequest: function() {
					$this.options.submit.field.disabled = true;
				},
				onComplete: function() {
					$this.options.submit.field.disabled = false;
				},
				onFocus: function( ele ) {
					ele.removeClass( 'error' );
					if( this.clearFocus == true ) {
						this.searchEngineSetSelection( null );
						ele.value = '';
						CookieManager.remove( el );
						CookieManager.remove( el + 'Country' );
					} else {
						this.clearFocus = true;
					}
				},
				onBlur: function( ele ) {
					if( ele.value.length > 0 && ele.value.length < this.options.minLength ) {
						this.searchEngineSetSelection( null );
						ele.addClass( 'error' );
					} else if( this.options.forceComplete == true ) {
						if( ele.value == '' )
							ele.value = $this.options[el].text;
					} else if( this.options.forceComplete == false ) {
						if( ele.value == '' ) {
							if( $this[$this.options.opposite[el]].field.value != $this.options[$this.options.opposite[el]].text && $this[$this.options.opposite[el]].field.value != $this.options[$this.options.opposite[el]].anywhere ) {
								ele.value = $this.options[el].anywhere;
							} else if( $this[$this.options.opposite[el]].field.value == $this.options[$this.options.opposite[el]].anywhere ) {
								ele.value = $this.options[el].text;
								$this[$this.options.opposite[el]].field.value = $this.options[$this.options.opposite[el]].text;
							} else {
								ele.value = $this.options[el].text;
							}
						} else {
							if( ele.value != $this.options[el].text && ele.value != $this.options[el].anywhere && $this[$this.options.opposite[el]].field.value == $this.options[$this.options.opposite[el]].text ) {
								$this[$this.options.opposite[el]].field.value = $this.options[$this.options.opposite[el]].anywhere;
							} else if( ele.value == $this.options[el].text && $this[$this.options.opposite[el]].field.value == $this.options[$this.options.opposite[el]].anywhere ) {
								ele.value = $this.options[el].text;
								$this[$this.options.opposite[el]].field.value = $this.options[$this.options.opposite[el]].text;
							} else if( ele.value == $this.options[el].anywhere && ele.value == $this[$this.options.opposite[el]].field.value ) {
								ele.value = $this.options[el].text;
								$this[$this.options.opposite[el]].field.value = $this.options[$this.options.opposite[el]].text;
							}
						}
					}
				},
				onSelection: function() {
					if( $this.search_complete() == true && $this.origin.ac.iata == $this.destination.ac.iata ) {
						$this[$this.options.opposite[el]].ac.searchEngineSetSelection( null );
						$this[$this.options.opposite[el]].field.focus();
						$this[$this.options.opposite[el]].field.value = '';
						return false;
					} else if( this.iata != null || this.iso != null ) {
						var cookieSet = {};
						cookieSet[el] = this.iata;
						cookieSet[el + 'Country'] = this.iso;
						CookieManager.set( cookieSet );
						$this.getRouteCheapPrices();
					} else {
						CookieManager.remove( el );
						CookieManager.remove( el + 'Country' );
					}
				},
				onShow: function() {
					this.clearFocus = false;
				},
				onHide: function() {
					this.clearFocus = false;
				}
			} );
			
			// Apply loaded iata and iso value
			$this[el].ac.searchEngineSetSelection( {'iata':$this.options[el].iata, 'iso': $this.options[el].iso} );

		} );
		
		// Load value field
		if( this.options.forceComplete == true ) {
			this.origin.field.value = ( this.options.origin.loaded == null ) ? this.options.origin.text : this.options.origin.loaded;
			this.destination.field.value = ( this.options.destination.loaded == null ) ? this.options.destination.text : this.options.destination.loaded;
		} else {
			if( this.options.origin.loaded == null && this.options.destination.loaded == null ) {
				this.origin.field.value = this.options.origin.text;
				this.destination.field.value = this.options.destination.text;
			} else {
				this.origin.field.value = ( this.options.origin.loaded == null ) ? this.options.origin.anywhere : this.options.origin.loaded;
				this.destination.field.value = ( this.options.destination.loaded == null ) ? this.options.destination.anywhere : this.options.destination.loaded;
			}
		}
		
		this.options.form.addEvents( {
			submit: function( e ) {
				if( $this.options.submit.force == true )
					return;
				
				e.stop();
				
				// Wayfare event
				if( $this.options.wayfare.enabled == true && window[$this.options.wayfare.click] != undefined ) {
					window[$this.options.wayfare.click]( $this.options.wayfare.args[0], $this.options.wayfare.args[1], $this.options.wayfare.args[2], $this.options.wayfare.args[3] );
				}
			
				function getPageName() {
					if( $this.origin.ac.iata != null && $this.destination.ac.iata != null ) // iata -> iata
						return $this.options.redirectPage;
					if( $this.origin.ac.iata != null && $this.destination.ac.iata == null || $this.origin.ac.iata == null && $this.destination.ac.iata != null ) // iata -> all
						return 'CheapFlights';
					if( $this.origin.ac.iata != null && $this.destination.ac.iso != null || $this.origin.ac.iso != null && $this.destination.ac.iata != null ) // iata -> iso
						return 'CheapFlights';
					if( $this.origin.ac.iso != null || $this.destination.ac.iso != null ) // iso -> all
						return 'CheapFlights';
					if( $this.origin.ac.iata == null && $this.destination.ac.iata == null ) // false
						return null;
				}

				$this.query = '';
				$this.options.submit.field.value = $this.options.submit.wait;
				
				if( getPageName() == $this.options.redirectPage ) { // Routes or Prices page
					Redirect.set( {
						origin: $this.origin.ac.iata,
						destination: $this.destination.ac.iata,
						originText: $this.origin.field.value,
						destinationText: $this.destination.field.value,
						depDate: $this.origin.date || null,
						retDate: $this.destination.date || null,
						oneway: ( $this.options.oneway.state == false ? true : false )
					} );
					if( $this.options.redirectPage == 'Routes' && $this.options.hasPrices == false )
						Redirect.set( {hasPrices: false} );
					Redirect.go( $this.options.redirectPage );
				} else if( $this.options.forceComplete == false && getPageName() == 'CheapFlights' ) { // CheapFlights page
					Redirect.set( {
						origin: $this.origin.ac.iata,
						destination: $this.destination.ac.iata,
						originCountry: $this.origin.ac.iso,
						destinationCountry: $this.destination.ac.iso,
						originText:  ( $this.origin.ac.iata != null || $this.origin.ac.iso != null ) ? $this.origin.field.value : null,
						destinationText: ( $this.destination.ac.iata != null || $this.destination.ac.iso != null ) ? $this.destination.field.value : null
					} );

					Redirect.go( 'CheapFlights' );
				} else {
					$this.options.submit.field.value = $this.options.submit.text;
					return false;
				}
			}
		} );
		
		
		// Init Calendar
		if( $this.options.calendar.active == true ) {
			this.calendar = new Calendar( {
				depDate: { depDate: "d-m-Y", depDateText: this.options.calendar.pattern, depDateURL: "Ymd" },
				retDate: { retDate: "d-m-Y", retDateText: this.options.calendar.pattern, retDateURL: "Ymd" }
			},{
				direction: 0, 
				pad: 0.5,
				offset: 1,
				navigation: 1,
				cal_start: $this.options.calendar.cal_start,
				cal_end: $this.options.calendar.cal_end,
				days: $this.options.calendar.days,
				months: $this.options.calendar.months,
				onHideStart: function() {
					$this.origin.date = this.calendars[0].els[2].value;
					$this.destination.date = this.calendars[1].els[2].value;
					if( this.calendars[0].els[2].value == '' ) this.calendars[0].els[0].value = $this.options.depDate.text;
					if( this.calendars[1].els[2].value == '' ) this.calendars[1].els[0].value = $this.options.retDate.text;
					// Set cookies
					var dates = {depDate:$this.origin.date,retDate:$this.destination.date};
					CookieManager.set( dates );
				}
			} );
			this.calendar.addEvent( 'reset', function( cal ) {
				cal.els[0].value = $this.options[cal.el.id].text;
				cal.els[1].value = '';
				cal.els[2].value = '';
				CookieManager.remove( cal.el.id );
			} );
			
			// Init default calendar value
			this.options.date.each( function( item, index ) {
				$this.calendar.calendars[index].els[0].value = $this.options[item].loaded || $this.options[item].text;
				$this.calendar.calendars[index].els[1].value = $this.options[item].loaded_txt || '';
				$this.calendar.calendars[index].els[2].value = $this.options[item].loaded_url || '';
			} );
			this.origin.date = this.options.depDate.loaded_url || null;
			this.destination.date = this.options.retDate.loaded_url || null;
			
			// Add event on one way check box
			this.options.oneway.field.addEvents( {
				domready: function() {
					$this.options.oneway.field.checked = $this.options.oneway.state;
					if( $this.options.oneway.state == false ) $this.toggle_oneway();
				},
				click: function() {
					$this.options.oneway.state = $this.options.oneway.field.checked;
					$this.toggle_oneway();
					CookieManager.remove( 'retDate' );
				}
			} );
		
			// Remove events on date text fields
			this.options.dateText.each( function( el ) {
				$(el).removeEvents();
				$(el).addEvents( {
					focus: function() {
						this.blur();
					}
				} );
			} );
			
			this.isPopUpInit = false;
			this.initPopUpCalendar();
		
		}
		
		this.getRouteCheapPrices();
		
		window.addEvent( 'changeCurrency', function() {
			$this.getRouteCheapPrices();
		} );
	},
	
	getRouteCheapPrices: function() {
		
		if( this.options.getCheapPrice == false )
			return;
		
		if( this.search_complete() == true ) {
			var $this = this;
			
			var url = '/cmd/?cmd=GetRouteCheapPrices&format=json';
			if( this.options.proxy == true ) url = url + '&proxy=true';

			// pattern with seller var fromPattern = '{FROM}: <span class="price">{price}</span><span class="cur"> {currency}</span> {WITH} <span class="airline">{airlineName}</span> {separator} <span class="airline">{sellerName}</span>';
			var fromPattern = '{FROM}: <span class="price">{price}</span><span class="cur"> {currency}</span> {WITH} <span class="airline">{airlineName}</span>';
			this.jsonSearch = new JSONCache( {
				url: url,
				link: 'cancel',
				onRequest: function() {
					$this.options.form.getElement( '.fromPrice' ).addClass( 'wait' );
					$this.options.form.getElement( '.fromPrice' ).set( 'text', _d( 'WAIT' ) );
				},
				onComplete: function( obj ) {
					if( $type( obj ) == 'object' && obj.prices.length > 0 ) {
						var fromObject = {
							FROM: _d( 'FROM PRICE' ),
							price: Common.round( obj.prices[0].price, 2 ),
							currency: CookieManager.get( 'currency' ),
							WITH: _d( 'WITH' ),
							airlineName: obj.prices[0].airlineName,
							separator: obj.prices[0].sellerName != null ? '/' : null,
							sellerName: obj.prices[0].sellerName
						};
						$this.options.form.getElement( '.fromPrice' ).removeClass( 'wait' );
						$this.options.form.getElement( '.fromPrice' ).set( 'html', fromPattern.substitute( fromObject ) );
					} else {
						$this.options.form.getElement( '.fromPrice' ).removeClass( 'wait' );
						$this.options.form.getElement( '.fromPrice' ).set( 'html', '' );
					}
				},
				onCancel: function() {
					$this.options.form.getElement( '.fromPrice' ).removeClass( 'wait' );
					$this.options.form.getElement( '.fromPrice' ).set( 'html', '' );
				},
				onFailure: function() {
					$this.options.form.getElement( '.fromPrice' ).removeClass( 'wait' );
					$this.options.form.getElement( '.fromPrice' ).set( 'html', '' );
				}
			} );
			var params = {};
			params.origin = $this.origin.ac.iata;
			params.destination = $this.destination.ac.iata;
			/* Temp disable
			params.originCountry = $this.origin.ac.iso;
			params.destinationCountry = $this.destinationCountry.ac.iso;
			*/
			params.currency = CookieManager.get( 'currency' );
			this.jsonSearch.get( params, params.origin + params.destination + params.currency );
		} else {
			this.options.form.getElement( '.fromPrice' ).removeClass( 'wait' );
			this.options.form.getElement( '.fromPrice' ).set( 'html', '' );
		}
		
	},
	
	toggle_oneway: function() {

		var $this = this;
		
		this.destination.date = null;
		this.calendar.calendars[1].els[1].value = '';
		this.calendar.calendars[1].els[2].value = '';
		this.calendar.calendars[1].el.value = ( this.options.oneway.state == true ) ? this.options.retDate.text : this.options.oneway.text;
		this.calendar.calendars[1].el.disabled = ( this.options.oneway.state == true ) ? false : true;
		this.calendar.calendars[1].button.disabled = ( this.options.oneway.state == true ) ? false : true;
		this.calendar.calendars[0].hilite_it = this.options.oneway.state;
		this.calendar.calendars[0].inactive_it = this.options.oneway.state;
		if( this.options.oneway.state == true ) this.calendar.calendars[1].button.removeClass( 'disable' );
		else this.calendar.calendars[1].button.addClass( 'disable' );
		
		if( this.options.oneway.state == true )
			CookieManager.remove('oneway');
		else
			CookieManager.set({'oneway':true});
		
	},
	
	search_complete: function() {
		
		if( ( $type( this.origin ) != false && this.origin.ac.iata != null ) && ( $type( this.destination ) != false && this.destination.ac.iata != null ) )
			return true;
		else
			return false;
		
	},
	
	initPopUpCalendar: function() {
		
		var $this = this;
		// Check if popup if enabled
		if( this.options.calendar.popup == false )
			return false;
		
		// Check if container is defined
		if( this.options.calendar.container.parent == null || this.options.calendar.container.row == null )
			return false;
		
		// Add button row in popup
		var div = new Element( 'div', {
			styles: {
				clear: 'both'
			}
		} );
		var button = new Element( 'button',{
			text: this.options.submit.text,
			'class': 'buttons small blue',
			events: {
				click: function() {
					$this.options.submit.field.click();
					TB_remove();
				}
			},
			styles: {
				'float': 'right'
			}
		} ).inject( div );
		// Clone current calendar on current container
		window.addEvent('onSBShow', function() {
			if( TB_inline_id == $this.options.calendar.container.row ) { // Check if smoothbox is open with date id
				$($this.options.calendar.container.row).clone().inject( $($this.options.calendar.container.parent) );
				div.setStyle( 'visibility', 'visible' );
				div.inject( $('TB_ajaxContent') );
			}
		} );
		// Destroy clone
		window.addEvent('onSBHide', function() {
			if( $this.isPopUpInit == true ) {
				if( TB_inline_id == $this.options.calendar.container.row ) { // Check if smoothbox is open with date id
					div.setStyle( 'visibility', 'hidden' );
					$($this.options.calendar.container.parent).empty();
				}
			}
		} );
	},
	
	popUpCalendar: function() {
		
		// Check if popup if enabled
		if( this.options.calendar.popup == false )
			return false;
		
		this.isPopUpInit = true;
		TB_show( _d( 'SELECT DATE' ), 'TB_inline?height=80&width=400&inlineId=' + this.options.calendar.container.row );
		
	}
	
} );
