/**
*	File: hills_ford.js
*
*	Author: Matthew Lindley, GForces Web Management: www.gforces.co.uk
*	Purpose: House most of the custom javascript for the Hills Ford website
*
*/


/**
*	Stuff we always want to do onload
*/
document.observe( 'dom:loaded', function () {

	

	modelSearch.init('usedVehiclesType','usedVehiclesTypeInput');
	newModelSearch.init('newVehiclesType','newVehiclesTypeInput');

});



/****************************************
*	Global stuff
****************************************/
Element.addMethods( 'SELECT', {

	addOption: function ( el, text, value, index ) {
		index = index || $(el).options.length;
		$(el).options[ index ] = new Option( text, value );
		return el;
	},

	empty: function ( el, offset ) {
		offset = parseInt( offset ) || 0;
		while ( el.options.length > offset ) {
			el.options[ el.options.length - 1 ] = null;
		}
		return el;
	},

	populate: function ( el, options ) {
		options.data.each( function ( option ) {
			option = $H( option );
			$(el).addOption( option.get( options.textName ), option.get( options.valueName ) );
		});
	}

});

Element.addMethods({

 

 addTbody: function ( el ) {

 

  el.immediateDescendants().wrap( new Element( 'tbody' ) );

 

 },

 

 stripe: function ( el, className ) {

 

  switch ( el.tagName.toLowerCase() ) {

 

   case 'table':

 

    tbody = el.immediateDescendants().find( function ( child ) {

     return child.tagName.toLowerCase() == 'tbody';

    });

 

    if ( tbody == false ) {

     el.addTbody();

    }

 

   break;

 

   case 'tbody':

    tbody = el;

   break;

 

   default:

    return false;

 

  }

 

  tbody.immediateDescendants().invoke( 'removeClassName', className ).each( function ( row, index ) {

   if ( index % 2 == 0 ) {

    row.addClassName( className );

   }

  });

 

 }

});




/****************************************
*	Vehicle pager
****************************************/

var vehiclePager = {

	currentIndex: 0,


	init: function ( element, options ) {

		//  Arguments
		this.element 		= $( element );

		this.options 		= options || {};
		this.options.delay 	= options.delay || 4;

		//  Elements to manipulate
		this.numbers	= $$( '#' + this.element.id + ' div.controlItem a' );
		this.pages 		= $$( '#' + this.element.id + ' div.item' );

		//  Timer
		this.timer = new PeriodicalExecuter( this.goNext.bind( this ), this.options.delay );

		//  Click events for the numbers
		this.numbers.invoke( 'observe', 'click', this.numberClick.bind( this ) );

	},


	goNext: function () {

		//  Hide current page
		this.hidePage( this.currentIndex );

		//  Go to next page
		this.currentIndex++;

		//  Gone too far?
		if ( this.currentIndex >= this.numbers.length ) {
			this.currentIndex = 0;
		}

		//  Show new page
		this.showPage( this.currentIndex );

	},


	goPage: function ( index ) {

		this.stopTimer();

		return false;

	},


	hidePage: function ( index ) {

		this.numbers[ index ].removeClassName( 'active' );
		this.pages[ index ].hide();

	},


	numberClick: function ( ev ) {

		Event.stop( ev );

		el = ev.element();
		
		if ( el.tagName.toLowerCase() != 'div' ) {
			el = el.up(0);
		}

		this.stopTimer();

		this.hidePage( this.currentIndex );

		this.currentIndex = el.previousSiblings().length;

		this.showPage( this.currentIndex );
		
		this.startTimer();

	},


	showPage: function ( index ) {
		this.numbers[ index ].addClassName( 'active' );
		this.pages[ index ].show();
		$('vehiclePagerBtn').href = this.pages[ index ].down().href;
	},


	stopTimer: function () {

		if ( this.timer !== false ) {
			this.timer.stop();
			this.timer = false;
		}

	},
	
	startTimer: function () {

		if ( this.timer === false ) {
			this.timer = new PeriodicalExecuter( this.goNext.bind( this ), this.options.delay );
		}

	}

}

/****************************************
*	Location pager
****************************************/

var locationPager = {

	currentIndex: 0,


	init: function ( element, options ) {

		//  Arguments
		this.element 		= $( element );

		this.options 		= options || {};
		this.options.delay 	= options.delay || 4;

		//  Elements to manipulate
		this.numbers	= $$( '#' + this.element.id + ' div.controlItem a' );
		this.pages 		= $$( '#' + this.element.id + ' div.item' );

		//  Timer
		this.timer = new PeriodicalExecuter( this.goNext.bind( this ), this.options.delay );

		//  Click events for the numbers
		this.numbers.invoke( 'observe', 'click', this.numberClick.bind( this ) );

	},


	goNext: function () {

		//  Hide current page
		this.hidePage( this.currentIndex );

		//  Go to next page
		this.currentIndex++;

		//  Gone too far?
		if ( this.currentIndex >= this.numbers.length ) {
			this.currentIndex = 0;
		}

		//  Show new page
		this.showPage( this.currentIndex );

	},


	goPage: function ( index ) {

		this.stopTimer();

		return false;

	},


	hidePage: function ( index ) {

		this.numbers[ index ].removeClassName( 'active' );
		this.pages[ index ].hide();

	},


	numberClick: function ( ev ) {

		Event.stop( ev );

		el = ev.element();
		
		if ( el.tagName.toLowerCase() != 'div' ) {
			el = el.up(0);
		}

		this.stopTimer();

		this.hidePage( this.currentIndex );

		this.currentIndex = el.previousSiblings().length;

		this.showPage( this.currentIndex );

	},


	showPage: function ( index ) {
		this.numbers[ index ].addClassName( 'active' );
		this.pages[ index ].show();
	},


	stopTimer: function () {

		if ( this.timer !== false ) {
			this.timer.stop();
			this.timer = false;
		}

	}

}

function financeSearch(){

	
    if( $('budgetSearchMonthlyPayments').value != '' && $('budgetSearchTerm').value != ''){
        
		var aprVal = $F('aprValue');
        var monthly_apr = ( parseFloat( aprVal ) / 12 ) /100;
        
        var totalFunds = 0;
        var totalInterest = 0;
        var totalAll = 0;
        
        var monthly_interest_payment = new Array();
        var monthly_total_payment = new Array();
        
        // Loop over the term to generate the monthly values
        for( var i = 0; i < $('budgetSearchTerm').value; i++  ){
            
            if( i == 0 ){
                monthly_interest_payment[i] = parseFloat( $('budgetSearchMonthlyPayments').value ) * parseFloat( monthly_apr );
                monthly_total_payment[i] = parseFloat( $('budgetSearchMonthlyPayments').value ) - parseFloat( monthly_interest_payment[i] );
            }else{
                monthly_interest_payment[i] = ( parseFloat( $('budgetSearchMonthlyPayments').value ) + parseFloat( monthly_total_payment[ i -1 ] ) )* parseFloat( monthly_apr ); 
                monthly_total_payment[i] = ( parseFloat( $('budgetSearchMonthlyPayments').value ) + parseFloat( monthly_total_payment[ i -1 ] ) ) - parseFloat( monthly_interest_payment[i] );
                totalFunds = monthly_total_payment[i];
                
            }    
            totalInterest = parseFloat( totalInterest + monthly_interest_payment[i] );
        }
        
        totalInterest = totalInterest.toFixed(2);
        totalFunds = totalFunds.toFixed(2);
        
        var finance_total = parseFloat( totalInterest ) + parseFloat( totalFunds);
        finance_total = finance_total.toFixed(2);
        
        if( $('budgetSearchDeposit').value != '' ){
        
            var finance_total_funds = parseFloat( totalFunds ) + parseFloat( $('budgetSearchDeposit').value );
        }else{
            
            var finance_total_funds = parseFloat( totalFunds );
        }
        finance_total_funds = finance_total_funds.toFixed(2);
        
        var maxPrice = finance_total_funds * 1.035;
        $('finance_maxPrice').value = maxPrice.toFixed(0);
        $('finance_show_maxPrice').innerHTML = maxPrice.toFixed(0);
        $('finance_show_maxPrice_div').style.display='block';
        
        
        
    }
    
}
    

//Search Marque Model stuff

    var modelSearch = {

		init: function (element,field) {
			
			this.divCarImages = element;
			
		    //  Toggle actions for vehicle pictures
			$$('#' + this.divCarImages + ' a').invoke( 'observe', 'click', function ( ev ) {
	
				Event.stop( ev );		//  Stop link working
	
				el = ev.element();		//  Reference element
				el.toggleClassName( 'active' );		//  Add/remove active class
	
				$(field).value = getCarTypes(this.divCarImages);
				getMakes();
	
			}.bind( this ) );
	
		}

    }
    
    var newModelSearch = {

		init: function (element,field) {
			
			this.divCarImages = element;
			
		    //  Toggle actions for vehicle pictures
			$$('#' + this.divCarImages + ' a').invoke( 'observe', 'click', function ( ev ) {
	
				Event.stop( ev );		//  Stop link working
	
				el = ev.element();		//  Reference element
				el.toggleClassName( 'active' );		//  Add/remove active class
	
				$(field).value = getCarTypes(this.divCarImages);
				getNewMakes()
	
			}.bind( this ) );

	
		}


    }
    
	function getCarTypes(divCarImages) {

		//  Get the rel property of all car image links with the class active
		return $$('#' + divCarImages + ' a').findAll( function ( el ) {
			return el.hasClassName( 'active' );
		}).pluck( 'rel' ).join( ',' );

	}
    
   function getMakes() {
        //marqueDetailId

        var target = baseHref + 'ajax.php';
        var params = 'type=getMakes&vehicleType=' + $F('usedVehiclesTypeInput');

        var myAjax = new Ajax.Request(target,
        {
            method: 'post',
            parameters: params,
            onSuccess: function (request) {

                var i;
                for(i = $('marqueDetailId').options.length - 1 ; i >= 0 ; i-- ) {
                    $('marqueDetailId').remove(i);
                }

                var outText = request.responseText;
                outText = outText.split(',');

                if ( outText.length > 0 ) {
                    for (i = 0 ; i < outText.length ; i++) {
						bits = outText[i].split(':');
                        //alert(outText[i]);
                        $('marqueDetailId').options[ $('marqueDetailId').options.length ] = new Option( bits[1], bits[0] );

                    }
                }
                
                getMarqueModels();

            },

            onFailure: function(request) {
                alert( 'request failed, please try again' );
            }
        });
    }
    
    function getModels() {
        //marqueDetailId

        var target = baseHref + 'ajax.php';
        var params = 'type=getMarqueModels&id=' + $('marqueDetailId').options[$('marqueDetailId').selectedIndex].value + '&vehicleType='+ $F('usedVehiclesTypeInput'); 

        var myAjax = new Ajax.Request(target,
        {
            method: 'post',
            parameters: params,
            onSuccess: function (request) {

                var i;
                for(i = $('model').options.length - 1 ; i >= 0 ; i-- ) {
                    $('model').remove(i);
                }

                var outText = request.responseText;
                outText = outText.split(',');

                if ( outText.length > 0 ) {
                    for (i = 0 ; i < outText.length ; i++) {

                        //alert(outText[i]);
                        $('model').options[ $('model').options.length ] = new Option( outText[i], outText[i] );

                    }
                }

            },

            onFailure: function(request) {
                alert( 'request failed, please try again' );
            }
        });
    }
    
   function getNewMakes() {
        //marqueDetailId

        var target = baseHref + 'ajax.php';
        var params = 'type=getNewMakes&vehicleType=' + $F('newVehiclesTypeInput');

        var myAjax = new Ajax.Request(target,
        {
            method: 'post',
            parameters: params,
            onSuccess: function (request) {

                var i;
                for(i = $('newMarqueDetailId').options.length - 1 ; i >= 0 ; i-- ) {
                    $('newMarqueDetailId').remove(i);
                }

                var outText = request.responseText;
                outText = outText.split(',');

                if ( outText.length > 0 ) {
                    for (i = 0 ; i < outText.length ; i++) {
						bits = outText[i].split(':');
                        //alert(outText[i]);
                        $('newMarqueDetailId').options[ $('newMarqueDetailId').options.length ] = new Option( bits[1], bits[0] );

                    }
                }
                
                getNewModels();

            },

            onFailure: function(request) {
                alert( 'request failed, please try again' );
            }
        });
    }
    
    function getNewModels() {
        //marqueDetailId

        var target = baseHref + 'ajax.php';
        var params = 'type=getNewModels&id=' + $('newMarqueDetailId').options[$('newMarqueDetailId').selectedIndex].value + '&vehicleType='+ $F('newVehiclesTypeInput');

        var myAjax = new Ajax.Request(target,
        {
            method: 'post',
            parameters: params,
            onSuccess: function (request) {

                var i;
                for(i = $('newModel').options.length - 1 ; i >= 0 ; i-- ) {
                    $('newModel').remove(i);
                }

                var outText = request.responseText;
                outText = outText.split(',');

                if ( outText.length > 0 ) {
                    for (i = 0 ; i < outText.length ; i++) {

                        //alert(outText[i]);
                        $('newModel').options[ $('newModel').options.length ] = new Option( outText[i], outText[i] );

                    }
                }

            },

            onFailure: function(request) {
                alert( 'request failed, please try again' );
            }
        });
    }

/// favourites stuff

	function saveToFavourites( carId ) {
		var target = baseHref + 'ajax.php';
	    var params = 'type=addToWishList&carId=' + carId;

	    var myAjax = new Ajax.Request(target,
	    {
	        method: 'post',
	        parameters: params,
	        onSuccess: function (request) { if( request.responseText != '' ){ alert( request.responseText );} rebuildFavourites(); },
	        onFailure: function (request) { if( request.responseText != '' ){ alert( request.responseText );} }
	    });
	}
	
	function removeFromFavourites( carId ) {
		var target = baseHref + 'ajax.php';
	    var params = 'type=removeFromWishList&carId=' + carId;

	    var myAjax = new Ajax.Request(target,
	    {
	        method: 'post',
	        parameters: params,
	        onSuccess: function (request) { rebuildFavourites();  },
	        onFailure: function (request) {  }
	    });
	}
	
	function rebuildFavourites(){
		var target = baseHref + 'ajax.php';
	    var params = 'type=rebuildWishList';
	    
	    var myAjax = new Ajax.Request(target,
	    {
	        method: 'post',
	        parameters: params,
	        onSuccess: function (request) { $('favouritesHolder').innerHTML = request.responseText;  },
	        onFailure: function (request) {  }
	    });
	}
