var WBCheapFlights = new Class( {
	Implements : [Options,Events],
	options: {
		originCountry : '', 
		origin : '' ,
		destinationCountry : '',
		destination : '',
		lang : 'en' ,
		currency : CookieManager.get( 'currency' ) || 'EUR',
		baseURI : '/cmd/',
		groupBy: true,
		target: null,
		p : null,
		airlines : [],
		airlinesEx : [],
		product : 'beta',
		airlineText : true,
		elements : {
			container: { id: '' },
			main: { id: '' , tag : 'div'},
			header :{ tag : 'div'},
			body : { tag : 'div'}
		},	
		list : { elements : {
			main : {'id': ''},
			list: { 'id': ''},
			elementContainer: { tag: 'div'},
			element: { 'class': ''}
			},
			ns : {
				elementContainer : '' ,
				element : '' 
			}
		},
		animation : {
			elements : {
				loader : { 'class' : 'loading_full' }
			}
		}
	},
	List : null , 
	loadedResult: null,
	Transport : null, 
	Animation : null ,

	getOption : function( name ){
		return WBHelper.getValue( 'options.'+ name , this );
	},
	initialize: function(options){
		
		var $this = this;
		if (options) 
			this.setOptions( options );

		// Rendering order is important	
		if( this.getOption('elements.container.id') && $( this.getOption('elements.container.id'))){
			this.container = $( this.getOption('elements.container.id')) ;
			this.container.empty();
		} else{ 
			this.container = document.body ;
		} ;
		
		this.render( this.container );
	
		this.List = new WBList( this.options.list ) ; 			
		this.List.render( this.body ? this.body : this.main );

		this.Animation = new WBAnimation( this.options.animation );	
		this.Animation.render();
		
		this.Transport = new Request.JSON( { method: 'get' } );
		
		this.loaded = false;
		
		// reload when currency change
		window.addEvent( 'changeCurrency', function() {
			$this.options.currency = CookieManager.get( 'currency' );
			$this.clear();
			$this.load();
		} );
	},
	clear: function(){
		this.List.clear();
		this.loadedResult = null;
	},	
	render: function(container, position){
		
		this.main = WBHelper.createElement(this.options.elements.main);
		if (!container) 
			container = document.body;
		if(!position) 
			position = '';
		this.main = this.main.inject(container, position);
		if( el = WBHelper.createElement( this.options.elements.header) ){
			this.header = el.inject(this.main);
		}
		if( el = WBHelper.createElement( this.options.elements.body) ){
			this.body = el.inject(this.main);
		}
		
		//adjust list height
		bodyHeight = this.main.clientHeight - ( this.header ? this.header.clientHeight : 0 ) ;	
		this.body.setStyle( 'height', 	bodyHeight );
	},	
	load: function( params ){
	
		if (!params) 
			params = {};
		params.cmd = 'GetCheapPrices';
		params.originCountry = params.originCountry ? params.originCountry : this.getOption('originCountry'); 
		params.origin = params.origin ? params.origin : this.getOption('origin');
		params.destinationCountry = params.destinationCountry ? params.destinationCountry :this.getOption('destinationCountry');
		params.destination = params.destination ? params.destination : this.getOption('destination');
		params.currency = params.currency ? params.currency : this.getOption('currency');	
		params.lang = params.lang ? params.lang : this.getOption('lang'); 	
		params.groupBy = params.groupBy ? params.groupBy : this.getOption('groupBy');
		if( __airlines = params.airlines ? params.airlines : this.getOption('airlines')){
			params.airlines = __airlines.toString();
		}else if( __airlinesEx = params.airlinesEx ? params.airlinesEx : this.getOption('airlinesEx')){
			params.airlinesEx = __airlinesEx.toString();
		}
		
		this.Transport.setOptions({ 'url' : this.getOption('baseURI') , data : params });	
		this.Transport.send();
		
		// After first call, clear origin/destination param for clear options loaded by cookie
		if( this.loaded == false ) {
			this.options.origin = '';
			this.options.originCountry = '';
			this.options.destination = '';
			this.options.destinationCountry = '';
			this.loaded = true;
		}
	},	
	handleResponse : function( _json ){

		var $this = this;
		// need to preprare the data before feeding to List
		if(_json.prices.length == 0 )
			return ;
		
		this.loadedResult = _json ;	
		var CFPattern =		'<div class="first" style="margin: 0px; width: 30%;">' +
										'<p><span class="firstPrice">{price}</span><span>{currency}</span></p>' +
										'<p>{priceDateFormatted}</p>' +
										'<p><span class="widget_info_price">{priceAge}</span></p>' +
									'</div>' +
									'<div style="float: right; width: 70%;">' +
										'<p>{depName} ({depAirport})</p>' +
										'<p>{arrName} ({arrAirport})</p>' +
										'<p style="color: #9999CF;">{VIA} {viaName} {viaAirport}</p>' +
										'<p><img src="/I/logos/logo-{sellerId}-75x20.gif" alt="{sellerName}" title="{sellerName}" align="absmiddle" /><span class="airlineName">{airlineName}</span></p>' +
									'</div>' +
									'<div style="clear: both;"></div>';
		
		_json.prices.each( function( item, index ) {
			params = {};
			
			// List needs code & name parameters to be set up
			params.code = index;
			params.name =	null;
			var priceElem = $this.List.appendElement( params );

			var CFObject = {
				price: ( item.price >= 10000 ) ? Common.round( item.price ) : Common.round( item.price, 2 ),
				currency: CookieManager.get( 'currency' ),
				priceDateFormatted: item.priceDateFormatted,
				depName: item.depName,
				depAirport: item.depAirport,
				arrName: item.arrName,
				arrAirport: item.arrAirport,
				VIA: ( item.viaAirport != null ) ? _d( 'VIA' ) : null,
				viaName: item.viaName,
				viaAirport: ( item.viaAirport != null ) ? '(' + item.viaAirport + ')' : null,
				priceAge: item.priceAge,
				airlineId: item.airlineId,
				airlineName: ($this.options.airlineText ?  item.airlineName : ''),
				sellerId: item.sellerId,
				sellerName: item.sellerName
			};
			
			var row = new Element( 'div', {
				html: CFPattern.substitute( CFObject )
			} );
			 
			row.addEvents( {
				click: function() {
					Redirect.set( {
						origin: item.depAirport,
						destination: item.arrAirport,
						originText: item.depName,
						destinationText: item.arrName,
						depDate: item.flightDateURI,
						lang: $this.options.lang,
						p : $this.options.p 
					} );
					if($this.options.product == 'whichbudget'){
						Redirect.options.site = 'whichbudget' ,
						Redirect.go( 'Routes', $this.options.target );
					}else{
						Redirect.go( 'Prices', $this.options.target );					
					}
				}
			} );
			row.inject( priceElem );
		} );
		this.fireEvent('afterHandleResponse' , { container : this.List.main, content : this.List.list } );
	},
	showLoader : function(){
		this.Animation.showLoader( this.main )
	},
	hideLoader : function(){
		this.Animation.hideLoader()
	}
} );
