/**
*	Tabs for the autoSearchForm
*/
var autoSearchTabs = {

	/***  Settings/default properties  ***/

	tabs: [],


	/***  Main init function  ***/

	init: function () {

		//  Save tabs
		this.tabs = $$('#usedCarSearchTabs a');

		//  Observe clicks on the tabs
		this.tabs.each( function ( tab, index ) {
			tab.observe( 'click', function ( ev ) {
				Event.stop( ev );
				this.resetTabs();
				this.showForm( index );
			}.bind( this ));
		}.bind( this ));

	},


	/***  Class methods  ***/

	resetTabs: function () {
		this.tabs.invoke( 'removeClassName', 'active' );
	},

	showForm: function ( index ) {

		//  Highlight tab
		this.tabs[index].addClassName( 'active' );

		//  Hide all forms
		$$('form.autoSearchForm').invoke( 'hide' );

		//  Show form
		$$('form.autoSearchForm')[index].show();

	}

}


/**
*	Budget search code
*/
var budgetSearch = {

	/***  Settings/default properties  ***/

	apr: 12.5,
	regexpCurrency: /^\d+(\.\d{1,2})?$/,
	requiredFields: [ 'deposit', 'payment', 'term' ],


	/***  Main init function  ***/

	init: function ( options ) {

		options = options || {};

		//  Check fields are set correctly
		if ( !options.fields ) {
			alert( 'Budget search error:\n\nNo fields set.\n' );
			return false;
		} else {

			/***  BUTTONS  ***/

			if ( !options.buttons ) {
				alert( 'Budget search error:\n\nNo buttons set.\n' );
				return false;
			} else {
				if ( !$(options.buttons.submit) ) {
					alert( 'Budget search error:\n\n"Submit" button not found.\n' );
					return false;
				}
			}

			this.buttons = options.buttons;

			//  Hide submit button
			$( this.buttons.submit ).hide();


			/***  FIELDS  ***/

			//  Set fields to a readable hash
			options.fields = $H( options.fields );

			//  Loop required fields and error if not set or it doesn't exist in the DOM
			this.requiredFields.each( function ( property ) {
				if ( !options.fields.get( property ) ) {
					alert( 'Budget search error:\n\nField "' + property + '" not set.\n' );
					return false;
				} else if ( !$( options.fields.get( property ) ) ) {
					alert( 'Budget search error:\n\nField given for "' + property + '" does not exist.\n' );
					return false;
				}

				//  Field must exist so add click event
				el = $( options.fields.get( property ) );

				el.observe( 'keyup', function ( ev ) {
					this.calculate();
				}.bind( this ));

				el.observe( 'change', function ( ev ) {
					this.calculate();
				}.bind( this ));

			}.bind( this ));

			//  All ok
			this.fields = options.fields;


			/***  LABELS  ***/

			this.labels = options.labels;

			$(this.labels.wrapper).hide();

		}

		//  Check APR
		if ( typeof options.apr == 'number' ) {
			this.apr = options.apr;
		}

	},


	/***  Class methods  ***/

	calculate: function () {

		$(this.buttons.submit).hide();
		$(this.labels.wrapper).hide();

		var deposit 	= parseFloat( this.get( 'deposit' ) );
		var payment		= parseFloat( this.get( 'payment' ) );
		var term		= parseFloat( this.get( 'term' ) );

		var total		= payment * ( term * 12 );
		var interest	= Math.round( total * this.apr ) / 100;
		var budget		= deposit + total + interest;

		$(this.labels.budget).update( budget );

		$(this.fields.get( 'budget' )).value = budget;

		$(this.buttons.submit).show();
		$(this.labels.wrapper).show();

	},

	get: function ( property ) {

		//  Return the value of a set property
		return $F( this.fields.get( property ) );

	},

	validateField: function ( f ) {

		if ( f.type == 'text' ) {
			f.value = $F(f).replace( /[^0-9\.]/g, '' );
		}

		v = $F(f);

		return ( this.regexpCurrency.test( v ) );

	},

	validateForm: function () {

		var valid = true;

		this.requiredFields.each( function ( el ) {
			if ( valid && !this.validateField( this.fields.get( el ) ) ) {
				valid = false;
			}
		}.bind( this ));

		return valid;

	}

}


/**
*	Favourites list
*/
favouritesList = {

	save: function ( carId ) {

		if ( !/^\d+$/.test( carId ) ) {
			return false;
		}

		new Ajax.Request( baseHref + 'ajax.php', {
			method: 'post',
			parameters: 'type=addToFavourites&id=' + carId,
			onSuccess: function ( t ) {

				r = t.responseText.evalJSON();

				if ( r.error ) {
					alert( r.msg );
					return false;
				}

				v = r.vehicle;

				//  Target URL
				var url		= baseHref + v.site_folder + '/used-cars/view/' + v.id + '/' + v.linkHeading;

				//  Create link and image
				var link 	= new Element( 'a', { href: url } );
				var image	= new Element( 'img', { src: baseHref + 'images/global_auto/thumbs/' + v.image_src, width: '60', height: '45' } );

				//  Get first thumb without any <a> tag inside
				$$('span.favThumb').find( function ( span ) {
					return ( $A( $( span ).childElements().pluck( 'tagName').invoke( 'toLowerCase' ) ).indexOf( 'a' ) == -1 )
				})
					.down()									//  Frame
					.wrap( link )							//  Wrap with link
					.insert( {top:image} )					//  Insert image of car at the start of the link to make it clickable
					.observe( 'click', function ( ev ) {	//  Monitor image onclick for IE
						Event.stop( ev );
						document.location = url;
					});

				alert( r.msg );

			}
		});

	}

}


/**
*  Vertical stripe
*/
verticalStripe = {

	offset: 0,

	init: function ( table, options ) {

		options 		= options || {}
		this.offset 	= options.offset || this.offset;

		$$( 'tbody tr', table ).each( function ( row ) {

			$( row ).childElements().each( function ( cell, index ) {
				if ( ( index >= this.offset ) && ( index > 0 ) && ( index % 2 == 0 ) ) {
					cell.addClassName( 'trAlt' );
		   		}
			}.bind( this ));

		}.bind( this ));

	}

}


/**
*	Manage the homepage banners
*/
var homepageBanners = {

	/***  Settings/default properties  ***/

	delay: 4,
	currentIndex: 0,
	timer: false,


	/***  Main init function  ***/

	init: function ( options ) {

		//  Set defaults if nothing set
		options				= options || {};
		options.delay		= options.delay || 5;

		//  Get all the banners
		this.banners = $$( '.homepageBanner' );

		//  Manual controls and stop the timer
		$('homepageBannerBack').observe( 'click', function ( ev ) {
			Event.stop( ev );
			this.stopTimer();
			this.goBack();
		}.bind( this ));

		$('homepageBannerNext').observe( 'click', function ( ev ) {
			Event.stop( ev );
			this.stopTimer();
			this.goNext();
		}.bind( this ));

		$('homepageBannerLink').observe( 'click', function ( ev ) {
			Event.stop( ev );
			var b = this.banners[this.currentIndex];
            if ( b.href != '' && !/#$/.test( b.href ) ) {
				document.location = b.href;
			}
		}.bind( this ));

		//  Make banners moveable by setting their position to absolute and moving them to the default position
		this.banners.each( function ( banner ) {
			banner.setStyle({
				display: 'block',
				position: 'absolute'
			}).clonePosition( $('bannerWrapper'), { offset: $('bannerWrapper').getWidth(), onComplete: function () { console.log( 'fewfewfew' ); } });
		});

		//  Default to last banner because of the way the browser lays
		this.currentIndex = this.banners.length - 1;

		this.startTimer( options.delay );

	},


	/***  Class methods  ***/

	changeImage: function ( i, position ) {

		var c = this.banners[this.currentIndex];	//  Current
		var n = this.banners[i];					//  New

		//  Get all the banners which are they current or new
		this.banners.findAll( function ( img, index ) {
			return ( index != i && index != this.currentIndex );
		}.bind( this )).each( function ( el ) {
			el.setStyle({ zIndex: 0 });
		}.bind( this ));

		//  Put the new banner on top of the current one
		n.setStyle({ zIndex: '3' });
		c.setStyle({ zIndex: '2' });

		//  Get the width of the current banner to work out the offset
		var w = n.getWidth();

		//  Position and move the new image
		switch ( position ) {

			case 'left':
				n.clonePosition( $('bannerWrapper'), { offsetLeft: -w });
				this.slide( n, w );
			break;

			case 'right':
				n.clonePosition( $('bannerWrapper'), { offsetLeft: w });
				this.slide( n, -w );
			break;

		}

	},

	goBack: function () {

		//  Get prev image index
		var i = ( this.currentIndex > 0 ) ? this.currentIndex - 1 : this.banners.length - 1;
		this.changeImage( i, 'left' );
		this.currentIndex = i;

	},

	goNext: function () {

		//  Get next image index
		var i = ( this.currentIndex < ( this.banners.length - 1 ) ) ? this.currentIndex + 1 : 0;
		this.changeImage( i, 'right' );
		this.currentIndex = i;

	},

	slide: function ( element, offset ) {
		new Effect.Move( element, { x: offset, mode: 'relative', duration: 0.6 });
	},

	startTimer: function ( delay ) {
		delay = delay || this.delay;
		this.timer = new PeriodicalExecuter( this.goNext.bindAsEventListener( this ), delay );
	},

	stopTimer: function () {

		//  Stop the timer (probably a click on a manual link)
		if ( this.timer !== false ) {
			this.timer.stop();
			this.timer = false;
		}

	}

}